如何使用Python+Telethon在转发Telegram消息前编辑内容?
使用Telethon转发Telegram消息并编辑内容
问题描述
使用Python的Telethon库实现Telegram频道/机器人之间的新消息转发,需要在转发前编辑消息内容(删除部分文本),同时想知道:消息内容动态变化但都包含特定关键词时,能否基于关键词删除其前后的内容?
当前代码
from telethon import TelegramClient, events import asyncio api_id = 99999999 api_hash = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' my_channel_id = -10000000000000 channels = [-1000000000000] client = TelegramClient('myGrab', api_id, api_hash) print("GRAB - Started") @client.on(events.NewMessage(chats=channels)) async def my_event_handler(event): if event.message: await client.send_message(my_channel_id, event.message) client.start() client.run_until_disconnected()
原始消息示例
The Button LTDSH 11 has matched with a live Match Adelaide United ||(4) V NE MetroStars(1) 🇦🇺 Australia :- Npl South Australian ⏱ Elapsed Time: 55' ⚽️ Score: 1 - 1 Home Shots: on:off Target: 3:1 Away Shots: on:off Target: 2:7 Home Possession: 37% Away Possession: 63% Home Dangerous Attacks: 30 Away Dangerous Attacks: 39 📈AP1 (H:A): 27:33 Form (H:A): LLDLD:WWDWW Home Corners: 2 Away Corners: 5 Last 10mins Shots on Target Home:Away 1 : 0 💰Odds (H:D:A) Starting 5.50 : 4.75 : 1.40 Live 8.50 : 4.33 : 1.33
期望编辑后的格式
The Button LTDSH 11 has matched with a live Match Adelaide United ||(4) V NE MetroStars(1) 🇦🇺 Australia :- Npl South Australian ⏱ Elapsed Time: 55' ⚽️ Score: 1 - 1 💰Odds (H:D:A) Live 8.50 : 4.33 : 1.33
解决方案
针对示例需求的代码修改
要编辑消息内容,不能直接转发event.message,需要提取文本内容处理后再发送。以下是适配示例需求的修改代码:
from telethon import TelegramClient, events api_id = 99999999 api_hash = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' my_channel_id = -10000000000000 channels = [-1000000000000] client = TelegramClient('myGrab', api_id, api_hash) print("GRAB - Started") @client.on(events.NewMessage(chats=channels)) async def my_event_handler(event): if event.message and event.message.text: original_text = event.message.text # 处理标题换行,合并成一行 title_fixed = original_text.split("⚽️ Score:")[0].replace("\na live Match", " a live Match") # 提取到Score行的完整内容 first_section = title_fixed + "⚽️ Score:" + original_text.split("⚽️ Score:")[1].split("\n\n")[0] # 提取Odds部分,只保留Live赔率行 odds_section = original_text.split("💰Odds (H:D:A)")[1] live_odds = next(line for line in odds_section.split("\n") if line.strip().startswith("Live")) # 拼接最终文本 processed_text = f"{first_section}\n\n💰Odds (H:D:A)\n{live_odds}" await client.send_message(my_channel_id, processed_text) client.start() client.run_until_disconnected()
基于关键词的通用处理方案
如果消息内容动态变化,但固定包含特定关键词(比如示例中的⚽️ Score:和💰Odds (H:D:A)),可以用关键词分割文本,精准保留需要的部分,代码如下:
from telethon import TelegramClient, events api_id = 99999999 api_hash = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' my_channel_id = -10000000000000 channels = [-1000000000000] client = TelegramClient('myGrab', api_id, api_hash) print("GRAB - Started") @client.on(events.NewMessage(chats=channels)) async def my_event_handler(event): if event.message and event.message.text: original_text = event.message.text # 定义固定存在的关键词 score_key = "⚽️ Score:" odds_key = "💰Odds (H:D:A)" # 提取从开头到Score行的内容 score_part = original_text.split(score_key)[1].split("\n")[0] first_section = original_text.split(score_key)[0] + score_key + score_part # 提取Odds部分中的Live行 odds_part = original_text.split(odds_key)[1] live_line = next(line for line in odds_part.split("\n") if line.strip().startswith("Live")) # 拼接最终文本 processed_text = f"{first_section}\n\n{odds_key}\n{live_line}" await client.send_message(my_channel_id, processed_text) client.start() client.run_until_disconnected()
这种方法无需关注中间动态变化的内容,只要关键词存在,就能准确截取需要保留的部分,适配不同的消息内容。
内容的提问来源于stack exchange,提问作者Marcello Gabrielli
相关产品推荐
相关产品推荐

