如何在没有命令或事件的情况下发送消息discord.py

我正在使用日期时间文件来打印:现在是早上 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 点触发警报的原因,我只想知道触发此警报时如何发送不和谐的消息。


如果您需要任何澄清,请询问。谢谢!


郎朗坤
浏览 82回答 3
3回答

隔江千里

您可以创建一个后台任务来执行此操作并将消息发布到所需的频道。您还需要使用asyncio.sleep()而不是time.sleep()因为后者会阻塞并且可能会冻结并崩溃您的机器人。我还添加了一项检查,以便该频道不会在早上 7 点的每一秒都收到垃圾邮件。discord.pyv2.0from discord.ext import commands, tasksimport discordimport datetimetime = datetime.datetime.nowclass 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 = Falsebot = MyClient(command_prefix='!', intents=discord.Intents().all())bot.run('token')discord.pyv1.0from discord.ext import commandsimport datetimeimport asynciotime = datetime.datetime.nowbot = 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')

aluckdog

从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:循环可能不起作用

阿波罗的战车

根据discord.py的文档,您首先需要通过其id获取频道,然后才能发送消息。您必须直接获取通道,然后调用适当的方法。例子:channel = client.get_channel(12324234183172) await channel.send('hello')希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python