How to send message without command or event discord.py(如何在没有命令或事件 discord.py 的情况下发送消息)
问题描述
我正在使用 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 的情况下发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在没有命令或事件 discord.py 的情况下发送消息
基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
