我使用日期时间文件打印:现在是早上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点的每一秒都被垃圾邮件
discord.py
v2.0
from discord.ext import commands, tasks
import discord
import datetime
time = datetime.datetime.now
class MyClient(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.msg_sent = False
async def on_ready(self):
channel = bot.get_channel(123456789) # replace with channel ID that you want to send to
await self.timer.start(channel)
@tasks.loop(seconds=1)
async def timer(self, channel):
if time().hour == 7 and time().minute == 0:
if not self.msg_sent:
await channel.send('Its 7 am')
self.msg_sent = True
else:
self.msg_sent = False
bot = MyClient(command_prefix='!', intents=discord.Intents().all())
bot.run('token')
discord.py
v1.0
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')
从disconce.py的文档中,您首先需要根据通道的id获取通道,然后可以发送消息。
请参阅:https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-sensid-a-message到特定通道
您必须直接获取通道,然后调用适当的方法。示例:
channel = client.get_channel(12324234183172)
await channel.send('hello')
希望,这有帮助。
当您设置了客户端时,可以从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:
循环可能无法在中工作