Visionario / django_pyrogram_bot

Django Pyrogram Bot: Basic, simple and 100% functional example demonstrating how Pyrogram integrates with Django, ready to use.
MIT No Attribution
14 stars 4 forks source link

RuntimeError: There is no current event loop in thread 'Thread-1 (process_request_thread)'. #4

Open dshahrokhian opened 11 months ago

dshahrokhian commented 11 months ago

Hello there! First of all, thank you for this repository. I was faced with the challenge of integrating Pyrogram into my Django application.

I have followed the instructions and started the bot, and using it via django shell like #2 does the job.

Nonetheless, as soon as I integrate the bot into my actual Django application (somewhere in views.py), I face the same issue I faced before using this repo:

Traceback (most recent call last):
...
  File "/home/X/dev/git/backend/backend/data_app/views.py", line 137, in _create_chat
    app = Client(
  File "/home/X/dev/Y/lib/python3.10/site-packages/pyrogram/client.py", line 267, in __init__
    self.dispatcher = Dispatcher(self)
  File "/home/X/dev/Y/lib/python3.10/site-packages/pyrogram/dispatcher.py", line 58, in __init__
    self.loop = asyncio.get_event_loop()
  File "/usr/lib/python3.10/asyncio/events.py", line 656, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1 (process_request_thread)'.

For context, I am trying to create a Telegram chat whenever I get a request at localhost:8000/create_chat. Here's an extract of my views.py:

from django.conf import settings
from pyrogram import Client

# to be able to import 'bot'
import sys
sys.path.append("..")
from bot.utils import RunningBot
...
...
def post(self, request, *args, **kwargs):
        """
        Creates a chat, and generates a join link
        """
        # Initialize Pyrogram client
                bot_settings = settings.PYROGRAM_BOT
        running_bot = RunningBot()
        running_bot_data = running_bot.read_data()

        app = Client(
                name=f"{bot_settings['BOT_NAME']}",
                session_string=running_bot_data["session_string"],
                no_updates=True,
                workers=1,
        )

        with app:
            chat = app.create_group("test", [])
            invite_link = app.export_chat_invite_link(chat.id)
        ...
        ...
        return Response(serializer.data, status=status.HTTP_201_CREATED)

Any ideas? How am I supposed to use the running bot, instead of instantiating a new one, and running once again into async issues?

Thank you :pray: