I’m doing a Telegram bot which in case of a file change on the desktop sends a message to Telegram.
Telethon is an asynchronous library, but I ruled out the asynchronous library and am waiting. The program connects to the telegram server and sends a one-time test message to the main()
function.
client.send_message('me', 'Hello to myself!')
as well as a function in the MyEventHandler
class that runs when a file changes and displays a test message on the console
print("Tyu")
But if you uncomment the line
#client.send_message('me', 'myself!')
then errors are displayed and client.send_message (“I”, “I!”)
and printing (“Ty”)
fail.
Can anyone help understanding what’s the matter?
Console output:
RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited
client.send_message('me', 'Hello to myself!')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Program code:
from telethon import TelegramClient
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import time
api_id = ****
api_hash = '****'
client = TelegramClient('New', api_id, api_hash)
class MyEventHandler(FileSystemEventHandler):
def on_modified(self, event):
#client.send_message('me', 'myself!')
print("Tyu")
def main():
# Now you can use all client methods listed below, like for example...
client.send_message('me', 'Hello to myself!')
observer = Observer()
observer.schedule(MyEventHandler(), path='/Users/Apple/Desktop/', recursive=True)
# Start the observer
observer.start()
try:
while True:
# Set the thread sleep time
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
with client:
client.loop.run_until_complete(main())
if __name__ == '__main__':
main()
3
Answers
I guess the problem is with this block
Because you use while and it never break, it take one second rest and continue. You can place while at the top of you function
Try something like this, it will do on_modified function and than delay for 1 second
I have a solution, but I don’t know how it works (explanation why and how it works is very welcome!) Namely, I found a clue in answer to "RuntimeError: There is no current event loop in thread ‘Bot:chat_id:dispatcher’ in python-telegram-bot" that you need to use
asyncio.set_event_loop(asyncio.new_event_loop())
You would also need:
client.disconnect()
and follow the error to understand what you need to free / why you need to disconnect.asyncio
Here is the full code: