alexander-akhmetov/python-telegram

Error occurred when tg.stop()

Itzamna44 opened this issue · 1 comments

Hello.
I tried send message to bot.
it worked but with error on exit from program.
How to correctly exit from new_message_handler ?

Got error at line tg.stop():

Exception in thread Thread-2: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/a/Library/Python/3.9/lib/python/site-packages/telegram/worker.py", line 44, in _run_thread handler(update) File "/Users/a/telegram/client-rd-2.py", line 120, in new_message_handler tg.stop() File "/Users/a/Library/Python/3.9/lib/python/site-packages/telegram/client.py", line 162, in stop self.worker.stop() File "/Users/a/Library/Python/3.9/lib/python/site-packages/telegram/worker.py", line 49, in stop self._thread.join() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 1050, in join raise RuntimeError("cannot join current thread") RuntimeError: cannot join current thread

The code is:
`
from telegram.client import Telegram
import threading

chat_id_2 = "123456"

tg = Telegram(
api_id=123456,
api_hash='123456',
phone='123456',
database_encryption_key='123456',
)
tg.login()

get_chats_result = tg.get_chats()

get_chats_result.wait()

if get_chats_result.error:
print(f'get chats error: {get_chats_result.error_info}')
else:
print(f'chats: {get_chats_result.update}')

send_message_result = tg.send_message(
chat_id=chat_id_2,
text='text',
)
send_message_result.wait()

if send_message_result.error:
print(f'Failed to send the message: {send_message_result.error_info}')

message_has_been_sent = threading.Event()

def update_message_send_succeeded_handler(update):
print(f'Received updateMessageSendSucceeded: {update}')

if update['old_message_id'] == send_message_result.update['id']:
    message_id = update['message']['id']
    message_has_been_sent.set()

tg.add_update_handler('updateMessageSendSucceeded', update_message_send_succeeded_handler)

message_has_been_sent.wait(timeout=60)
print(f'Message has been sent.')

def new_message_handler(update):
message_content = update['message']['content']
message_text = message_content.get('text', {}).get('text', '').lower()
chat_id = update['message']['chat_id']
print(chat_id)

if chat_id == int(chat_id_2):
    print(f'received from {chat_id}')
    print(message_text)
    tg.stop()

tg.add_message_handler(new_message_handler)

tg.idle()
`

Hi, you need to call tg.stop() from the main thread, not from the new_message_handler function which is being executed in a separate thread.