问题描述
我正在使用 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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)