I’m building a bot for Telegram that monitors file changes in a folder and sends notifications. The bot uses Telethon library and I’m having trouble with async operations.
When I test the bot, it connects fine and sends a welcome message in the start_bot() function:
telegram_client.send_message('me', 'Bot is running!')
I also have a file watcher class called FileWatcher that detects changes and shows a debug message:
print("File changed detected")
The problem happens when I try to send a telegram message from inside the file watcher. If I enable this line:
# telegram_client.send_message('me', 'File updated!')
I get runtime errors and both the message sending and console output stop working.
Here’s my complete code:
from telethon import TelegramClient
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import time
app_id = ****
app_secret = '****'
telegram_client = TelegramClient('session', app_id, app_secret)
class FileWatcher(FileSystemEventHandler):
def on_modified(self, event):
# telegram_client.send_message('me', 'File updated!')
print("File changed detected")
def start_bot():
telegram_client.send_message('me', 'Bot is running!')
watcher = Observer()
watcher.schedule(FileWatcher(), path='/home/user/Documents/', recursive=True)
watcher.start()
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
watcher.stop()
watcher.join()
with telegram_client:
telegram_client.loop.run_until_complete(start_bot())
if __name__ == '__main__':
start_bot()
The error message shows:
RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited
What am I doing wrong with the async handling?