【问题标题】:send message at a time interval using discord bot使用不和谐机器人按时间间隔发送消息
【发布时间】:2021-06-30 01:59:07
【问题描述】:

我正在尝试使用不和谐机器人在某个时间间隔发送消息。我从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')

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

【问题讨论】:

  • 有错误吗?你是在你的电脑上还是在谷歌 colab 或其他东西上运行它。如果你在电脑上运行它。你可以删除nest_asyncio.apply()
  • 不,没有错误。我从replit.com
  • 我试过调试。显然它进入while not self.is_closed():,但只有一次。由于某种原因,它在那之后就不起作用了

标签: python discord discord.py bots


【解决方案1】:

您可以尝试使用“任务”(来自 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")

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

【讨论】:

    猜你喜欢
    • 2020-01-24
    • 1970-01-01
    • 2019-07-11
    • 2019-12-10
    • 2021-04-03
    • 2022-11-02
    • 2020-11-12
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多