background_task.py 不显示消息 - Python

2023-11-30

我注意到,当我从 Discord.py Github 页面运行代码片段时,它没有显示预期的消息。

我稍微修改过的代码:

import discord
import asyncio

import nest_asyncio
nest_asyncio.apply()

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

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

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

    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')

当我检查 Discord 时,没有任何显示,但它确实在 IDLE 中显示输出:

Logged in as
bot_name
1234567890
------

但在 Discord 服务器中,什么也没有发生。有没有什么办法解决这一问题?


代码失败是因为self.get_channel(1234567890)在机器人正确连接之前使用,导致它总是返回None。这是因为client = MyClient()首先完成,这意味着后台任务已创建,但机器人尚未连接,这是通过client.run.

要解决此问题,请将循环的创建移至内部on_ready event.

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')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

background_task.py 不显示消息 - Python 的相关文章

随机推荐