2

I use the Telethon == 1.4.3 in my code:

import telepot
import threading
from telethon import TelegramClient
from flask import Flask, request
from telepot.loop import OrderedWebhook
from telepot.delegate import (
    per_chat_id, create_open, pave_event_space, include_callback_query_chat_id)

class Main_Class(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(Main_Class, self).__init__(*args, **kwargs)

    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        if content_type == 'text':
            client = TelegramClient('session_name', api_id, api_hash)
            client.connect()
            client.send_message('me', 'Hello World from Telethon!')            

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def pass_update():
    webhook.feed(request.data)
    return 'OK'
TOKEN = my_token
bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
        per_chat_id(types=['private']), create_open, Main_Class, timeout=100000),
])
webhook = OrderedWebhook(bot)

webhook.run_as_thread()

Since I also use the Flask, these two interfere with each other and I got the following error:

RuntimeError: There is no current event loop in thread 'Thread-1'

I imported asyncio and added the following lines to the code and the problem was solved

class Main_Class(telepot.helper.ChatHandler):
     ......
     loop = asyncio.new_event_loop()
     client = TelegramClient('session_name', api_id, api_hash,loop=loop)
     loop.run_until_complete(goo(loop,client))
     loop.close()
 .....

async def goo(loop,client):
      client.connect()
      await client.send_message('me', 'Hello World from Telethon!') 

The following error occurs despite the fact that I have already established a connection:

ConnectionError: Cannot send requests while disconnected
Amin
  • 23
  • 1
  • 9

1 Answers1

3

You should also wait for the connection to finish. Because it is done asynchronously.

async def goo(loop,client):
      await client.connect()
      await client.send_message('me', 'Hello World from Telethon!')

Read more, here.

Avi_av
  • 161
  • 1
  • 4
  • 1
    Thank you, when i add await to client.connect() ,connection established but i have another error: There is no current event loop in thread 'Thread-4' – Amin Jan 23 '19 at 21:45
  • Can i use asyncio.set_event_loop(loop) , to open an event loop for each thread? – Amin Jan 23 '19 at 22:20
  • My script awaits for client.connect() and it takes indefinitely, it just does not go further... So I have no problem with my Internet.. – Liker777 Aug 09 '22 at 07:23