Issue
The goal I'm trying to achieve is to send a command (e.g. /price) and get the response (price stats) from the bot and then quit to save resources. The message can only be received on-demand since the bot only responds when a command is sent.
So far, I've only gotten halfway there successfully by sending the command but receiving the response has been a head-scratcher. Here's my attempt so far, I'm open to any suggestions, please advise on the simplest way to achieve the receiving part. Thanks much!
with TelegramClient('Anon', tg_API_ID, tg_API_Hash) as client:
client(functions.messages.StartBotRequest(bot = '@Bot', peer = '@myHandle', start_param = '/price'))
client.start()
session = os.environ.get('TG_SESSION', 'printer')
@client.on(events.NewMessage(chats = '@Bot'))
async def my_event_handler(event):
text = event.raw_text
print(text)
client.loop.run_until_complete(main())
Here's a good resource if it helps: https://tl.telethon.dev/methods/messages/index.html
Solution
In Telethon V1, with client
also calls start
, so adding it again is redundant.
It's probably a good idea to define the handler before starting the bot, in case the message arrives "in-between".
You can call disconnect
from the handler to disconnect the client, and run_until_disconnected
to behave like loop.run_until_complete
, but it runs the event loop until disconnection occurs instead.
The following should work, assuming telethon.sync
was imported:
text_found = None
with TelegramClient('Anon', tg_API_ID, tg_API_Hash) as client:
@client.on(events.NewMessage(chats = '@Bot'))
async def my_event_handler(event):
global text_found
text_found = event.raw_text
await client.disconnect()
client(functions.messages.StartBotRequest(bot = '@Bot', peer = '@myHandle', start_param = '/price'))
client.run_until_disconnected()
print(text_found)
If telethon.sync
was not imported, you must use asyncio
, async
and await
:
import asyncio
async def main():
text_found = None
async with TelegramClient('Anon', tg_API_ID, tg_API_Hash) as client:
@client.on(events.NewMessage(chats = '@Bot'))
async def my_event_handler(event):
nonlocal text_found
text_found = event.raw_text
await client.disconnect()
await client(functions.messages.StartBotRequest(bot = '@Bot', peer = '@myHandle', start_param = '/price'))
await client.run_until_disconnected()
return text_found
text_found = asyncio.run(main())
print(text_found)
Answered By - Lonami
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.