[英]Watchdog and sending messages with Telethon
I would like to observe file system changes with watchdog and additionally send a message via telethon with the following code:我想用看门狗观察文件系统的变化,并通过 Telethon 发送一条消息,代码如下:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from telethon import TelegramClient, sync, events
api_id = 0000000
api_hash = '*'
client = TelegramClient('Name', api_id, api_hash)
client.start()
class OnMyWatch:
# Set the directory on watch
watchDirectory = "/Users/UserID/Desktop/"
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.watchDirectory, recursive=True)
self.observer.start()
try:
while True:
time.sleep(5)
except:
self.observer.stop()
print("Observer Stopped")
self.observer.join()
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.event_type == 'created':
# Sending a message to myself
client.send_message('me', 'A file was created!'),
if __name__ == '__main__':
watch = OnMyWatch()
watch.run()
Unfortunately it throws the following error:不幸的是,它会引发以下错误:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/telethon/sync.py", line 35,
in syncified
loop = asyncio.get_event_loop()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 642,
in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-2'.*
I was trying to understand how to make use of Asyncio with Telethon but couldn't fix it so I'm seeking to get some valuable hints here.我试图了解如何在Telethon 中使用 Asyncio,但无法修复它,所以我想在这里获得一些有价值的提示。
I have met the same problem and from Asyncio with Telethon I saw我遇到了同样的问题,我看到了来自Telethon 的 Asyncio
It just means you didn't create a loop for that thread
这只是意味着您没有为该线程创建循环
So I have added two lines before client construction.所以我在客户端构建之前添加了两行。
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client = TelegramClient('Name', api_id, api_hash)
And it works.它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.