You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pyrogram的copy_message函数移除消息中的各类链接

移除Telegram消息链接后复制到目标频道(Pyrogram实现)

由于copy_message方法会原样复制消息的所有内容(包括链接),无法直接修改消息内容,因此需要先获取原始消息的文本和格式实体,移除链接相关内容后,再重新发送到目标频道。

实现步骤

  1. 监听/获取原始频道消息:通过Pyrogram的消息监听或历史记录获取方法,拿到原始消息对象。
  2. 处理消息内容:
    • 删除消息文本中直接显示的URL(对应UrlEntity类型的实体)。
    • 保留文本但移除内嵌链接(对应TextLinkEntity类型的实体,只保留文字,去掉链接属性)。
    • 调整剩余格式实体的偏移量(因为删除URL后文本长度变化,避免格式错位)。
  3. 发送处理后的消息:使用send_message方法将处理后的内容发送到目标频道。

完整代码示例

from pyrogram import Client, filters
from pyrogram.types import Message, entities

# 初始化客户端
app = Client("my_bot_account")

# 替换为实际的原始频道和目标频道ID
SOURCE_CHANNEL = -1001234567890
TARGET_CHANNEL = -1000987654321

def process_message_links(message: Message):
    # 获取消息文本或媒体标题
    new_content = message.text or message.caption
    new_entities = []
    
    if not new_content:
        return new_content, new_entities
    
    # 收集所有需要删除的URL片段位置
    url_segments = []
    for ent in message.entities or []:
        if isinstance(ent, entities.UrlEntity):
            url_segments.append((ent.offset, ent.offset + ent.length))
    
    # 从后往前删除URL,避免索引偏移混乱
    url_segments.sort(reverse=True, key=lambda x: x[0])
    offset_diff = 0
    for start, end in url_segments:
        new_content = new_content[:start - offset_diff] + new_content[end - offset_diff:]
        offset_diff += end - start
    
    # 过滤链接实体并调整剩余实体的偏移量
    for ent in message.entities or []:
        if isinstance(ent, (entities.UrlEntity, entities.TextLinkEntity)):
            continue
        
        adjusted_ent = ent.copy()
        adjusted_ent.offset -= offset_diff
        new_entities.append(adjusted_ent)
    
    return new_content, new_entities

# 监听原始频道的新消息
@app.on_message(filters.chat(SOURCE_CHANNEL))
async def forward_processed_message(client, message: Message):
    processed_text, processed_entities = process_message_links(message)
    
    # 发送处理后的消息到目标频道
    await client.send_message(
        chat_id=TARGET_CHANNEL,
        text=processed_text,
        entities=processed_entities,
        # 可选:保留原消息的其他属性
        reply_markup=message.reply_markup,
        disable_notification=message.disable_notification
    )

if __name__ == "__main__":
    app.run()

代码说明

  • process_message_links函数:核心处理逻辑,负责清理URL文本、过滤链接实体,并调整剩余格式实体的位置,确保加粗、斜体等格式不受影响。
  • 媒体消息处理:如果原始消息包含图片、视频等媒体,send_message会自动处理媒体内容,只需传递处理后的标题(caption)和对应实体即可。
  • 替代copy_message:因为copy_message是直接复制消息的原始结构,无法修改内容,所以必须通过重新发送的方式实现需求。

内容的提问来源于stack exchange,提问作者dyrb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:22:32