使用discord bot按时间间隔发送消息

2024-05-13 10:19:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用discord bot在某个时间间隔发送消息。我在this链接中找到了一些类似的例子

import discord
import asyncio

import nest_asyncio
nest_asyncio.apply()

class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

        # create the background task and run it in the background
        self.bg_task = self.loop.create_task(self.my_background_task())

    async def my_background_task(self):
        counter = 0
        channel = self.get_channel(1234567890) # channel ID goes here
        while not self.is_closed():
            counter += 1
            await channel.send(counter)
            await asyncio.sleep(10) # task runs every 10 seconds


client = MyClient()
client.run('token')

但是当我尝试使用相同的代码时,我的服务器中没有收到任何消息。有人能帮我解决我可能做错的事情吗


Tags: importselfasyncio消息taskinitdefcounter
1条回答
网友
1楼 · 发布于 2024-05-13 10:19:43

您可以尝试使用“任务”(来自discord.ext)

from discord.ext import tasks

@bot.event
async def on_ready():
    send_message.start()

@tasks.loop(seconds=10)  # you can even use hours and minutes
async def send_message():
    await bot.get_channel(id_here).send("message here")

如果这没有帮助,你能描述一下你打算做什么吗

相关问题 更多 >