Skip to content

Commit

Permalink
Fix the result check in send_message example
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-akhmetov committed Jun 21, 2023
1 parent ce8c640 commit ca2eec2
Showing 1 changed file with 33 additions and 12 deletions.
45 changes: 33 additions & 12 deletions examples/send_message.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import argparse
import threading

from utils import setup_logging
from telegram.client import Telegram
Expand Down Expand Up @@ -34,26 +35,46 @@

# if this is the first run, library needs to preload all chats
# otherwise the message will not be sent
result = tg.get_chats()

get_chats_result = tg.get_chats()
# `tdlib` is asynchronous, so `python-telegram` always returns you an `AsyncResult` object.
# You can wait for a result with the blocking `wait` method.
result.wait()
get_chats_result.wait()

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

result = tg.send_message(
send_message_result = tg.send_message(
chat_id=args.chat_id,
text=args.text,
)
send_message_result.wait()

result.wait()
if result.error:
print(f'send message error: {result.error_info}')
else:
print(f'message has been sent: {result.update}')
if send_message_result.error:
print(f'Failed to send the message: {send_message_result.error_info}')

# When python-telegram sends a message to tdlib,
# it does not send it immediately. When the message is sent, tdlib sends an updateMessageSendSucceeded event.

message_has_been_sent = threading.Event()

# The handler is called when the tdlib sends updateMessageSendSucceeded event
def update_message_send_succeeded_handler(update):
print(f'Received updateMessageSendSucceeded: {update}')
# When we sent the message, it got a temporary id. The server assigns permanent id to the message
# when it receives it, and tdlib sends the updateMessageSendSucceeded event with the new id.
#
# Check that this event is for the message we sent.
if update['old_message_id'] == send_message_result.update['id']:
message_id = update['message']['id']
message_has_been_sent.set()

# When the event is received, the handler is called.
tg.add_update_handler('updateMessageSendSucceeded', update_message_send_succeeded_handler)

# Wait for the message to be sent
message_has_been_sent.wait(timeout=60)
print(f'Message has been sent.')

tg.stop()

0 comments on commit ca2eec2

Please sign in to comment.