为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

郎朗坤 2023-07-27 10:34:01
我正在使用日期时间文件来打印:现在是早上 7 点,每天早上 7 点。现在因为这超出了命令或事件引用,所以我不知道如何以不和谐的方式发送一条消息说现在是早上 7 点。不过需要澄清的是,这不是一个警报,它实际上是针对我的学校服务器的,它会在早上 7 点发送我们需要的所有内容的清单。import datetimefrom time import sleepimport discordtime = datetime.datetime.nowwhile True:    print(time())    if time().hour == 7 and time().minute == 0:        print("Its 7 am")    sleep(1)这就是早上 7 点触发警报的原因,我只想知道触发此警报时如何发送不和谐的消息。如果您需要任何澄清,请询问。谢谢!
查看完整描述

3 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

您可以创建一个后台任务来执行此操作并将消息发布到所需的频道。


您还需要使用asyncio.sleep()而不是time.sleep()因为后者会阻塞并且可能会冻结并崩溃您的机器人。


我还添加了一项检查,以便该频道不会在早上 7 点的每一秒都收到垃圾邮件。


discord.pyv2.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.pyv1.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')


查看完整回答
反对 回复 2023-07-27
?
aluckdog

TA贡献1847条经验 获得超7个赞

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


查看完整回答
反对 回复 2023-07-27
?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

根据discord.py的文档,您首先需要通过其id获取频道,然后才能发送消息。

您必须直接获取通道,然后调用适当的方法。例子:

channel = client.get_channel(12324234183172)
await channel.send('hello')

希望这可以帮助。


查看完整回答
反对 回复 2023-07-27
  • 3 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信