Python:通过cog和后台任务将消息发送到Discord中的特定通道

Python:通过cog和后台任务将消息发送到Discord中的特定通道,python,discord,discord.py-rewrite,Python,Discord,Discord.py Rewrite,我有一个Discord Python bot,我正在尝试运行一个后台任务,该任务将持续每隔X秒向一个通道发送一条消息—无需任何命令。当前有任意5秒的测试时间 这里是有问题的cog文件导入和为了效率而删除的东西 class TestCog(commands.Cog): def __init__(self, bot): self.bot = bot self.mytask.start() @tasks.loop(seconds=5.0) as

我有一个Discord Python bot,我正在尝试运行一个后台任务,该任务将持续每隔X秒向一个通道发送一条消息—无需任何命令。当前有任意5秒的测试时间

这里是有问题的cog文件导入和为了效率而删除的东西

class TestCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.mytask.start()

    @tasks.loop(seconds=5.0)
    async def mytask(self):
        channel = client.get_channel(my channel id here)
        await channel.send("Test")

def setup(bot):
    bot.add_cog(TestCog(bot))
我有一种感觉,这是因为self参数是唯一传递的参数,但我在阅读API文档时有点困惑,不知道在这里到底要做什么

我尝试了客户端而不是bot,我尝试了定义discord.client,但就我所读到的,我不应该使用我一直试图避免的东西

在其他使用实际命令的COG中,我将其设置为如下所示:

    @commands.command(name='test')
    async def check(self, ctx):
        if ctx.channel.name == 'channel name':
            await ctx.send("Response message")
这让我相信我传递的参数是错误的。我理解,因为我通过了ctx,我可以获得频道名称,但我不太确定如何用self做到这一点。当尝试传递ctx参数时,我没有得到任何错误,但是由于明显的原因,消息没有发送

我到底错过了什么?谢谢你的帮助

不一致。客户端对象没有获取通道方法。您必须使用不协调。帮会对象:

等待客户。在此处获取指南构建id。在此处获取通道通道id。发送测试
.

您可以使用.loop.create\u taskmytaskarguments将任务添加到asyncio循环中,您将在启动bot之前调用它

您可以使用async def mytaskargument像普通命令一样定义任务,但是请忽略ctx,因为ctx基本上是您通常获得的有关用于调用函数的命令的所有上下文。 相反,您需要使用channel id手动获取channel=bot.get_channelid的channel对象,然后您可以执行wait channel.sendYour message以向所述频道发送消息

要使其循环,只需使用带有asyncio.sleepdelay的while True循环来计时。 这可能会导致计时不准确,因为您必须等待消息发送的时间,因此我建议在函数前面使用clock=asyncio.create_tasksyncio.sleepdelay启动计时任务,并在函数后面使用wait clock捕捉该任务

现在,如果您希望它在每个间隔的某个时间运行,而不仅仅是在启动函数时的某个设置间隔,那么您需要延迟函数的启动,以匹配您设置的时间。您可以使用divmodtime.time,interval来执行此操作,它返回商和剩余的时间以及您的间隔,剩余的时间是自上次间隔开始以来的时间。如果要在间隔开始时启动函数,可以使用wait asyncio.sleepinterval-restins使函数休眠到下一个间隔开始。如果你想在这个时间间隔内设定一个时间,你需要把它分成两部分,一部分是关于你设定的时间是否已经过去,另一部分是关于它是否还没有到来

if remainder < set_time: 
    await asyncio.sleep(set_time - remainder)
else:
    await asyncio.sleep(interval + set_time - remainder)
现在,如果你把所有这些加在一个函数中,你会得到类似这样的东西,这是我在我的机器人中使用的一段代码:

async def reminder(channel, interval, set_time, message):
    await bot.wait_until_ready()
    channel = bot.get_channel(channel)
    quotient, remainder = divmod(time.time(), interval)
    if remainder < set_time:
        await asyncio.sleep(set_time-remainder)
    else:
        await asyncio.sleep(set_time + interval - remainder)
    while True:
        clock = asyncio.create_task(asyncio.sleep(interval))
        await channel.send(message)
        quotient, remainder = divmod(time.time(), interval)
        if remainder-set_time > 1:
            clock.cancel()
            await asyncio.sleep(interval-1)
        await clock

bot.loop.create_task(reminder(774262090801479740, 3600, 3300, "This is the 55th minute of the hour"))
bot.run(TOKEN)
我知道这并不能百分之百地回答问题,但正如您所说,您尝试了botand和client这两种方法,该解决方案应该适合您