【问题标题】:How to get Message object from MessageService object in Telethon如何从 Telethon 中的 MessageService 对象获取 Message 对象
【发布时间】:2018-11-25 13:31:34
【问题描述】:

我收到TypeError: 'MessageService' object is not iterable

首先,我正在使用返回telethon.sync._SyncGen 生成器对象的iter_messages client 方法保存来自频道的最后10 条消息。 然后我遍历这个生成器并尝试通过clientsend_message方法将每条消息(msg)发送给用户(username),该方法可以采用str或telethonMessage对象作为消息参数。

但是,我的 msg 对象不是 Message 类的实例,而是 MessageService 类 (https://lonamiwebs.github.io/Telethon/constructors/message_service.html),我认为这是我收到错误的原因。

message_objects = client.iter_messages(channel_name, limit=10)

for msg in message_objects:
    client.send_message(username, msg)

我的问题是如何获取Message 对象而不是MessageService 以避免错误并使client.send_message() 正常工作?

【问题讨论】:

    标签: telegram telethon


    【解决方案1】:

    MessageService 对象是 Telegram 的消息,例如“有人加入了此群组”或“频道照片已更改”。 iter_messages 将这些消息与其他消息一起返回,但您无法发送这些消息。正如您在自己链接的文档中看到的那样,MessageService 对象内没有真正的消息。只有一个MessageAction

    您可以在循环中跳过此类消息,我检查他们的type()hasattr(msg, 'message')。普通消息有message 字段,这是您要发送的文本。如果你想send_message(不转发),我觉得你的代码应该改成:

    client.send_message(username, getattr(msg, 'message', '...'))
    

    【讨论】:

    • 谢谢!这正是我一直在寻找的。如果我需要将这些消息发送或转发到私人频道,最好的方法是什么?
    • 对于私人频道,您应该手动实例化一个InputChannel 对象。当您提供@username 时,这就是 Telethon 在公共频道的幕后工作。 InputChannel 有 2 个强制参数:idaccess_hash。您可以拨打GetAllChatsRequest获取您帐户的所有聊天的完整列表,并在其中找到特定的私人频道。
    • 给将来遇到此答案的任何人的说明:MessageService 对象现在具有消息属性(可能来自 Telethon 而不是 Telegram),因此您需要检查 msg.message is not None 或坚持类型检查。
    猜你喜欢
    • 2010-11-17
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2021-01-25
    • 2021-04-08
    • 2020-09-23
    • 2012-07-18
    相关资源
    最近更新 更多