Telegram Bot API是否有识别转发消息的属性?链接消息处理问题
Telegram转发消息机器人的问题解决
1. 修复纯链接消息不触发的问题
Telegram Bot API里不存在link这个内容类型,纯链接属于文本消息范畴。你需要把content_types参数里的"link"替换成"text",修改后的装饰器代码如下:
@bot.message_handler(content_types=["video", "photo", "audio", "text"])
2. 判断是否为转发消息
要识别转发的消息,直接检查消息对象的forward_date属性即可:如果该属性不为None,说明这条消息是从其他聊天/频道/群组转发过来的。处理函数可以这样写:
def send_welcome(message): if message.forward_date is not None: bot.reply_to(message, "got it")
3. 进阶:只处理含链接的转发文本消息
如果需要仅响应包含链接的转发文本消息(而非所有转发文本),可以用正则表达式匹配文本中的链接:
import re @bot.message_handler(content_types=["video", "photo", "audio", "text"]) def send_welcome(message): # 先确认是转发消息 if message.forward_date is not None: # 媒体类型直接回复 if message.content_type in ["video", "photo", "audio"]: bot.reply_to(message, "got it") # 文本类型需检查是否包含链接 elif message.content_type == "text": url_regex = re.compile(r"https?://\S+") if url_regex.search(message.text): bot.reply_to(message, "got it")
内容的提问来源于stack exchange,提问作者Riley Zhuo
相关产品推荐
相关产品推荐

