微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

看门狗和使用 Telethon 发送消息

如何解决看门狗和使用 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()

不幸的是它抛出了以下错误

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'.*

我试图了解如何使用 Asyncio with Telethon 但无法修复它,所以我想在这里获得一些有价值的提示

解决方法

我遇到了同样的问题,从 Asyncio with Telethon 我看到了

这只是意味着你没有为那个线程创建一个循环

所以我在客户端构建之前添加了两行。

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client = TelegramClient('Name',api_id,api_hash)

它有效。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。