【问题标题】:Sending public channel reply Telegram messages with Telethon使用 Telethon 发送公共频道回复 Telegram 消息
【发布时间】:2021-11-30 13:05:44
【问题描述】:

我正在与 Telethon 合作,能够成功发送消息以及提取其他成员发送的公共频道消息,但我想知道是否有办法通过 sendmessage 回复已发布的消息。发送的回复将附加到原始帖子中。

from telethon.sync import TelegramClient


def messages(api_id, api_hash, phone, channel_name, message_content, 
destination_channel_id):
    client = TelegramClient(phone, api_id, api_hash)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))
    destination_channel_username = channel_name
    entity = client.get_entity(destination_channel_username)
    client.send_message(entity, message_content)
    client.disconnect()

def channel_chat(api_id, api_hash, phone, chat):
    client = TelegramClient(phone, api_id, api_hash)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))
    for message in client.iter_messages(chat, from_user='me', reverse=True):
        return message
        quit()
    client.disconnect()

if __name__ == "__main__":

    api_id = "api_id"
    api_hash = "api_hash"
    phone = "phone)
    chat = "channel_name"

    last_message = channel_chat(api_id, api_hash, phone, chat)
    if last_message:
        print("ID{} - {}".format(last_message.id, last_message.message))
        messages(api_id, api_hash, phone, chat, 'Thank you', last_message.id)

【问题讨论】:

    标签: telegram telegram-bot telethon


    【解决方案1】:

    您可以使用send_messagereply_to 参数来回复特定消息:

    client.send_message(entity, message_content, reply_to=msg_id_of_destination_channel)
    

    只要您尝试回复的消息存在于发送新消息的聊天中,这将起作用。如果您只有源通道的消息 ID,您可能需要定义一个 dict 来映射两个通道之间所有消息的标识符。

    附带说明,这是一项非常昂贵的操作:

    entity = client.get_entity(destination_channel_username)
    

    您应该考虑使用get_input_entity,并缓存结果。

    【讨论】:

    • 非常感谢,成功了!!!
    • 如果解决了您的问题,请务必将答案标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-17
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多