I'm trying to send a telegram message using telethon when I get a trigger from a button.
My telethon methods work fine when triggered by events like the NewMessage event, but how do I send a message (client.send_message(user, msg)
) with other triggers (i.e. button is pressed, telethon sends a message)?
Currently all I'm getting are these errors:
RuntimeError: There is no current event loop in thread 'Thread-1'.
RuntimeWarning: coroutine 'send_to' was never awaited
Here's a simplified version of my code:
with client:
client.start()
while True:
if (button):
await client.send_message(int(chat),msg)
client.run_until_disconnected()
edit:
In hindsight, my actual original question was oversimplified. I wasn't using a button, but voice commands, either way, a non-telegram trigger. With the help of the Telegram chat group @TelethonChat the answer was to use:
import asyncio
loop = asyncio.new_event_loop()
async def send_to(chat, msg):
await client.send_message(chat, msg)
def mainfunc():
if (trigger):
loop.create_task(send_to(chat, msg))
You would need to use events to do that. the event for clicking on a button is events.CallbackQuery
link is here
An example code would be as follow :
from telethon import events
from telethon.tl.custom import Button
@client.on(events.CallbackQuery)
async def handler(event):
await event.answer('You clicked {}!'.format(event.data))
client.send_message(chat, 'Pick one', buttons=[
[Button.inline('Left'), Button.inline('Right')]]
])
you can find more examples here: https://telethon.readthedocs.io/en/latest/extra/examples/telegram-client.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With