background_task.py not showing messages - Python

后端 未结 1 1996
面向向阳花
面向向阳花 2021-01-24 09:16

I noticed that when I ran a code snippet from the discord.py Github page it didn\'t show the intended message.

My slightly modified code:

import discord
         


        
相关标签:
1条回答
  • 2021-01-24 10:04

    The code fails because self.get_channel(1234567890) is used before the bot has properly connected, resulted in it always returning None. This is because client = MyClient() is done first, meaning the background task is created but the bot has not yet connected, which is done through client.run.

    To fix this, move the creation of the loop to inside the 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')
    
    0 讨论(0)
提交回复
热议问题