skip to Main Content

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


  1. try:
        while True:
            # Set the thread sleep time
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        observer.join()
    

    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

    Login or Signup to reply.
  2. class MyEventHandler(FileSystemEventHandler):
        def on_modified(self, event):
            # client.send_message('me', 'myself!')
            print("Tyu")
    
    
    def main():
        try:
            client.send_message('me', 'Hello to myself!')
            while True:
                c = MyEventHandler(path='/Users/Apple/Desktop/', recursive=True)
                c.on_modified("event")
                time.sleep(1)
        except KeyboardInterrupt:
            print("Errors")
    
    
    with client:
        client.loop.run_until_complete(main())
    

    Try something like this, it will do on_modified function and than delay for 1 second

    Login or Signup to reply.
  3. 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:

    • disconnect in the end of the function, so the connection is free on the next function call. This is not obvious, but you may skip the line with client.disconnect() and follow the error to understand what you need to free / why you need to disconnect.
    • login for first time with a phone number.
    • import asyncio

    Here is the full code:

    from telethon.sync import TelegramClient
    from watchdog.events import FileSystemEventHandler
    from watchdog.observers import Observer
    import time
    
    import asyncio
    
    api_id = ...
    api_hash = "..."
    phone = "..." 
    
    
    class MyEventHandler(FileSystemEventHandler):
            def on_modified(self, event):
                session_name = "watchdog"
    
                asyncio.set_event_loop(asyncio.new_event_loop())
                client = TelegramClient(session_name, api_id, api_hash)
                if not client.is_connected():
                    client.connect()
                if not client.is_user_authorized():
                    client.send_code_request(phone)
                    client.sign_in(phone, input('Enter the code: '))
    
                try:
                    client.send_message('me', "Hi to myself")
                except Exception as e:
                    print("Error:", e)
    
                client.disconnect()
     
    def main():
        observer = Observer()
        observer.schedule(MyEventHandler(), path='/Users/Apple/Desktop/', recursive=True)
    
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
              observer.stop()
              observer.join()
     
    if __name__ == '__main__':
        main()
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search