Answer the question
In order to leave comments, you need to log in
Telethon. How to improve the way a message is sent and a response is received?
I feel like I figured out a way to tame the car (oh yeah!) by punching through the gas tank, attaching the sticks, harnessing the horse, and off I go. Like a buzz, but something is not right.
The thing is that I do not understand async at all, so I did my best. I want to improve, I'm waiting for the advice of professionals
The task is to send messages to the bot and receive response messages (insert commands for the bot between messages, but this is not important)
def get_answer(self, vk_id, msgs, bot_name='aab137'):
api_id, api_hash = self.get_tg_api(vk_id, session_time=60)
client = telethon.TelegramClient('tg_sessions/' + str(api_id), api_id, api_hash)
async def get_answer(self, vk_id, msgs, bot_name):
await client.delete_dialog(bot_name, revoke=False)
msgs_number = self.get_msgs_number(vk_id)
for msg in msgs:
msgs_number += 1
cmds_before, cmds_after = self.config.get((msgs_number, 'before')), self.config.get((msgs_number, 'after'))
if cmds_before:
for cmd in cmds_before:
await client.send_message(bot_name, cmd)
await client.send_message(bot_name, msg)
if cmds_after:
for cmd in cmds_after:
await client.send_message(bot_name, cmd)
time.sleep(5)
ans = await client.get_messages(bot_name, None, from_user=bot_name)
ans = [msg.text for msg in ans]
return ans
with client:
ans = client.loop.run_until_complete(get_answer(self, vk_id, msgs, bot_name))
ans.reverse()
return ans
Answer the question
In order to leave comments, you need to log in
You use time.sleep(5), this method blocks the thread, use the asynchronous analog of sleep -- await asyncio.sleep(5). To make the code easier to read, use type annotations. Also, don't call 2 functions the same. You can break it into more functions and manipulate only them, so editing the code will become much easier. In newer versions of Python, f-strings are preferred.
The code is repeated:
for cmd in cmds_before:
await client.send_message(bot_name, cmd)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question