python - Telethon:对 Telegram 的自动回复停止工作。怎么修?
问题描述
我正在使用以下教程:https ://medium.com/@jiayu./automatic-replies-for-telegram-85075f28321
因此,我的代码是:
import time
from telethon import TelegramClient, events
# sample API_ID from https://github.com/telegramdesktop/tdesktop/blob/f98fdeab3fb2ba6f55daf8481595f879729d1b84/Telegram/SourceFiles/config.h#L220
# or use your own
api_id = XXXX
api_hash = 'XXXXXXX'
# fill in your own details here
phone = 'XXXXX'
session_file = '/path/to/session/file' # use your username if unsure
password = 'YOUR_PASSWORD' # if you have two-step verification enabled
# content of the automatic reply
message = "This message is autogenerated.\nApologies, I am unavailable at the moment. Feel free to call me for anything urgent."
count = 1
if __name__ == '__main__':
# Create the client and connect
# use sequential_updates=True to respond to messages one at a time
client = TelegramClient(session_file, api_id, api_hash, sequential_updates=True)
@client.on(events.NewMessage(incoming=True))
async def handle_new_message(event):
if event.is_private: # only auto-reply to private chats
from_ = await event.client.get_entity(event.from_id) # this lookup will be cached by telethon
if not from_.bot: # don't auto-reply to bots
print(count, time.asctime(), '-', event.message) # optionally log time and message
# print( '-', time.asctime()) # optionally log time and message
count += 1 # incrementing the count
time.sleep(1) # pause for 1 second to rate-limit automatic replies
await event.respond(message)
print(time.asctime(), '-', 'Auto-replying...')
client.start(phone, password)
client.run_until_disconnected()
print(time.asctime(), '-', 'Stopped!')
该代码在我第一次运行时运行良好。然后我停止了它,更改了消息,它不再起作用了。它以“自动回复...”消息启动,但不回复 Telegram 上的消息。重新启动计算机或删除会话文件没有帮助。
这与 Telegram 阻止连接有关吗?
编辑:有时它可以正常工作并且可以完美运行。有时它根本不起作用:(
解决方案
将代码中的任何地方的from_替换为sender_,即 3 次。
重大变化
Message.from_id 现在是 Peer,而不是 int!如果您想要标记的发件人 ID(很像旧行为),请将 .from_id 的所有使用替换为 .sender_id。这将大部分工作,但当然在旧版本和新版本中,您必须考虑这个发件人可能不再是用户的事实。 https://docs.telethon.dev/en/stable/misc/changelog.html?highlight=from_id#id14
推荐阅读
- code-documentation - YARD doc - how to document a class type focusing on its parent class
- ruby - 代码没有检查 ruby 中的第二个 elsif 条件
- c# - 如何在 ASP.NET MVC 中使用会话 ID 获取会话详细信息
- javascript - 如何在通过“最佳位置”编辑进行内联编辑时删除 html 标签
- c++ - logb() 和 ilogb() 有什么区别?
- javascript - 如何检查文件下载是否在 Chrome 中完成?
- javascript - 如何调用嵌套在表格单元格中的textarea属性?
- mysql - Map.prototype.forEach 不迭代 Map
- parsing - 如何使用 Graph-API、3rd-party API 或解析读出喜欢或评论我的帖子的 instagram 帐户名称 (2019)?
- openedx - 如何在 open edx 中解决此证书的问题