【问题标题】:Python Telegram BotPython电报机器人
【发布时间】:2020-10-28 00:31:20
【问题描述】:

我正在做一个 Telegram 机器人,如果桌面上的文件发生更改,它会向 Telegram 发送消息。

Telethon 是一个异步库,但是我排除了异步库,正在等待。程序连接电报服务器并向main()函数发送一次性测试消息。

client.send_message('me', 'Hello to myself!')

以及MyEventHandler 类中的一个函数,该函数在文件更改时运行并在控制台上显示测试消息

print("Tyu")

但是如果你取消注释该行

#client.send_message('me', 'myself!')

然后显示错误,client.send_message (“I”, “I!”) 和打印 (“Ty”) 失败。

谁能帮助理解这是怎么回事?

控制台输出:

RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited
  client.send_message('me', 'Hello to myself!')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

程序代码:

from telethon import TelegramClient
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import time
api_id = ****
api_hash = '****'
 
client = TelegramClient('New', api_id, api_hash)
 
 
class MyEventHandler(FileSystemEventHandler):
       def on_modified(self, event):
           #client.send_message('me', 'myself!')
           print("Tyu")
 
def main():
    # Now you can use all client methods listed below, like for example...
    client.send_message('me', 'Hello to myself!')
    observer = Observer()
    observer.schedule(MyEventHandler(), path='/Users/Apple/Desktop/', recursive=True)
    # Start the observer
    observer.start()
    try:
        while True:
            # Set the thread sleep time
            time.sleep(1)
     except KeyboardInterrupt:
          observer.stop()
          observer.join()
 
with client:
     client.loop.run_until_complete(main())
 
if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python telegram-bot telethon


    【解决方案1】:
    try:
        while True:
            # Set the thread sleep time
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        observer.join()
    

    我想问题出在这个块上 因为你使用 while 并且它永远不会中断,所以它需要一秒钟的休息时间并继续。你可以在函数的顶部放置while

    【讨论】:

    【解决方案2】:
    class MyEventHandler(FileSystemEventHandler):
        def on_modified(self, event):
            # client.send_message('me', 'myself!')
            print("Tyu")
    
    
    def main():
        try:
            client.send_message('me', 'Hello to myself!')
            while True:
                c = MyEventHandler(path='/Users/Apple/Desktop/', recursive=True)
                c.on_modified("event")
                time.sleep(1)
        except KeyboardInterrupt:
            print("Errors")
    
    
    with client:
        client.loop.run_until_complete(main())
    

    试试这样,它会做 on_modified 功能,然后延迟 1 秒

    【讨论】:

      【解决方案3】:

      我有一个解决方案,但我不知道它是如何工作的(非常欢迎解释为什么以及如何工作!)也就是说,我在answer to "RuntimeError: There is no current event loop in thread 'Bot:chat_id:dispatcher' in python-telegram-bot" 中找到了你需要使用的线索

      asyncio.set_event_loop(asyncio.new_event_loop())

      您还需要:

      • 在函数结束时断开连接,因此在下一次函数调用时连接是空闲的。这并不明显,但您可以跳过client.disconnect() 的行并按照错误了解您需要释放什么/为什么需要断开连接。
      • 首次使用电话号码登录。
      • 导入asyncio

      这里是完整的代码:

      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()
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-18
        • 2022-01-01
        • 2021-02-21
        • 1970-01-01
        • 2017-09-11
        • 2020-09-25
        • 2018-02-27
        • 2023-03-17
        相关资源
        最近更新 更多