看门狗并使用 Telethon 发送消息

问题描述 投票:0回答:2

我想用看门狗观察文件系统的变化,并另外通过 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 与 Telethon 结合使用,但无法修复它,因此我希望在这里获得一些有价值的提示。

python telethon python-watchdog
2个回答
1
投票

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

这只是意味着您没有为该线程创建循环

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

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

而且它有效。


0
投票

Telethon 是一个异步库,你必须等待该方法,例如:

async def main():
  await client.send_message('me', 'A file was created!')

然后在代码中像这样运行它:

asyncio.run(main())
© www.soinside.com 2019 - 2024. All rights reserved.