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 的情况下发送消息
基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01