問題描述
我正在使用 datetime 文件來打印:現在是早上 7 點,每天早上 7 點.現在因為這超出了命令或事件引用,我不知道如何發送一條不和諧的消息說現在是早上 7 點.只是為了澄清一下,這不是警報,它實際上是針對我的學校服務器的,它會在早上 7 點發送一份我們需要的所有東西的清單.
I am using the datetime file, to print: It's 7 am, every morning at 7. Now because this is outside a command or event reference, I don't know how I would send a message in discord saying It's 7 am. Just for clarification though, this isn't an alarm, it's actually for my school server and It sends out a checklist for everything we need at 7 am.
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 點觸發警報的原因.我只想知道如何在觸發時不和諧地發送消息.
This is what triggers the alarm at 7 am I just want to know how to send a message in discord when this is triggered.
如果您需要任何說明,請詢問.謝謝!
If you need any clarification just ask. Thanks!
推薦答案
您可以創建一個后臺任務來執行此操作并將消息發布到所需的頻道.
You can create a background task that does this and posts a message to the required channel.
您還需要使用 asyncio.sleep()
而不是 time.sleep()
,因為后者會阻塞并且可能會凍結和崩潰您的機器人.
You also need to use asyncio.sleep()
instead of time.sleep()
as the latter is blocking and may freeze and crash your bot.
我還添加了一項檢查,以便頻道不會在早上 7 點每秒都發送垃圾郵件.
I've also included a check so that the channel isn't spammed every second that it is 7 am.
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 的情況下發送消息的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!