Python Telegram Bot
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()