簡體   English   中英

如何在沒有命令或事件的情況下發送消息 discord.py

[英]How to send message without command or event discord.py

我正在使用日期時間文件來打印:現在是早上 7 點,每天早上 7 點。現在因為這是在命令或事件引用之外,我不知道如何發送一條不和諧的消息說現在是早上 7 點。 不過為了澄清起見,這不是警報,它實際上是針對我的學校服務器的,它會在早上 7 點發送我們需要的所有內容的清單。

import datetime
from time import sleep
import discord

time = datetime.datetime.now


while True:
    print(time())
    if time().hour == 7 and time().minute == 0:
        print("Its 7 am")
    sleep(1)

這就是在早上 7 點觸發警報的原因,我只想知道如何在觸發時不和諧地發送消息。

如果您需要任何說明,請詢問。 謝謝!

您可以創建一個后台任務來執行此操作並向所需頻道發布消息。

您還需要使用asyncio.sleep()代替time.sleep()因為后者是阻止並可能凍結和崩潰的機器人。

我還包括了一個檢查,以便頻道不會在早上 7 點時每秒收到垃圾郵件。

from discord.ext import commands
import datetime
import asyncio

time = datetime.datetime.now

bot = commands.Bot(command_prefix='!')

async def timer():
    await bot.wait_until_ready()
    channel = bot.get_channel(123456789) # replace with channel ID that you want to send to
    msg_sent = False

    while True:
        if time().hour == 7 and time().minute == 0:
            if not msg_sent:
                await channel.send('Its 7 am')
                msg_sent = True
        else:
            msg_sent = False

    await asyncio.sleep(1)

bot.loop.create_task(timer())
bot.run('TOKEN')

Discord.py 文檔中,當您設置了客戶端時,您可以使用以下格式直接向頻道發送消息:

channel = client.get_channel(12324234183172)
await channel.send('hello')

擁有頻道后(在設置客戶端之后),您可以放置​​根據需要編輯的代碼片段,以選擇合適的頻道以及所需的消息。 請記住"You can only use await inside async def functions and nowhere else." 所以你需要設置一個異步函數來這樣做,你的簡單While True:循環可能不起作用

從 discord.py 的文檔中,您首先需要通過其 id 獲取頻道,然后才能發送消息。

請參閱: https : //discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel

您必須直接獲取通道,然后調用適當的方法。 例子:

channel = client.get_channel(12324234183172)
await channel.send('hello')

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM