Опитвам се да получа последното съобщение от канал на discord, но все пак се натъквам на проблем с „цикличен цикъл на събитията“, може ли някой да ми помогне да прегледам кода си?

Опитвам се да създам програма на python, която непрекъснато обработва последното съобщение, изпратено в конкретен канал (и отпечатва съобщението като низ). Търсих решение в stackoverflow, но не мога да го намеря. Може ли да прегледате моя код вместо мен?


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 turn_on(self):
        print('my account:')
        print(self.user.name)
        print(self.user.id)
        print('------')

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

    async def messages_to_string(self):
        runs_today = 0
        channel = self.get_channel(1234567890000000) # put the channel's id here
        msg = await channel.history(limit=1).flatten()
        msg = msg[0]
        while not self.is_closed():
            runs_today += 1
            await channel.send(runs_today)
            await asyncio.sleep(60) # task runs every minute
        print(msg)

client = MyClient()

client.run('my_token') #put my personal token in here

Винаги получавам тази грешка: RuntimeError: Cannot close a running event loop

имате ли някакви предложения как да го поправя?

Благодаря ти!

РЕДАКТИРАНЕ:

опа, забравих да публикувам следата. Ето го (скрих токена си, защото има чувствителна информация)

     31 client = MyClient()
---> 32 client.run('my_token') #put my personal token in here

~\Anaconda3\lib\site-packages\discord\client.py in run(self, *args, **kwargs)
    712             future.remove_done_callback(stop_loop_on_completion)
    713             log.info('Cleaning up tasks.')
--> 714             _cleanup_loop(loop)
    715 
    716         if not future.cancelled():

~\Anaconda3\lib\site-packages\discord\client.py in _cleanup_loop(loop)
     93     finally:
     94         log.info('Closing the event loop.')
---> 95         loop.close()
     96 
     97 class _ClientEventTask(asyncio.Task):

~\Anaconda3\lib\asyncio\selector_events.py in close(self)
     92     def close(self):
     93         if self.is_running():
---> 94             raise RuntimeError("Cannot close a running event loop")
     95         if self.is_closed():
     96             return

RuntimeError: Cannot close a running event loop

person Teodor Sauca    schedule 06.02.2021    source източник
comment
можете ли да публикувате пълната следа?   -  person Łukasz Kwieciński    schedule 06.02.2021
comment
@ŁukaszKwieciński публикува! Благодаря за отговора   -  person Teodor Sauca    schedule 06.02.2021
comment
Използвате ли странна IDE? Това изглежда свързано: stackoverflow.com/questions/57639751/   -  person effprime    schedule 06.02.2021
comment
@effprime здравей, пробвах го в spyder и получих абсолютно същата грешка. Приложих и nest_asyncio, така че все още съм объркан къде е грешката ми. Благодаря за отговора!   -  person Teodor Sauca    schedule 06.02.2021
comment
Съжалявам, имам предвид коментара, който гласи I encountered the same problem trying to run Discord examples on Jupyter Notebook. Moving to plain python script solved it for me. Наистина това е заобиколно решение, но вероятно не е лошо   -  person effprime    schedule 07.02.2021


Отговори (1)


Предлагам да използвате разширението Tasks:

import discord
from discord.ext import tasks


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

    async def turn_on(self):
        print('my account:')
        print(self.user.name)
        print(self.user.id)
        print('------')

        
        self.runs_today = 0
        # Start the task
        self.messages_to_string.start()

    @tasks.loop(seconds=60.0)
    async def messages_to_string(self):
        channel = self.get_channel(1234567890000000) # put the channel's id here
        msg = await channel.history(limit=1).flatten()
        msg = msg[0]
        self.runs_today += 1
        await channel.send(self.runs_today)
        print(msg)

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

Това изпълнява вашата функция на всеки 60 секунди.

person jacksoor    schedule 07.02.2021