如何在Telegram机器人输出中实现特定文本加粗显示?
解决Telegram Bot中Markdown加粗不生效的问题
问题原因
Telegram Bot API默认不会自动解析Markdown格式文本,必须显式指定消息的parse_mode参数,否则用*包裹的文本只会原样显示,无法渲染为加粗样式。
解决方案
1. 统一为目标字段添加*包裹
先修改get_profile_context函数,把所有需要加粗的参数都用*包裹:
def get_profile_context(site_name): """Find the profile context based on the site name, case-insensitive.""" site_name = site_name.lower() site_info = site_data[site_data['site_name'].str.lower() == site_name] if not site_info.empty: row = site_info.iloc[0] # 为所有需要加粗的字段添加*包裹 context = ( f"- Enodeb ID: *{row['enodeb_id']}*\n" f"- Site ID: *{row['site_id']}*\n" f"- MC: *{row['mc']}*\n" f"- TAC: *{row['tac']}*\n" f"- Region: *{row['region']}*\n" f"- Regency: *{row['regency']}*\n" f"- Antenna Height: *{row['antenna_height']}*\n" f"- Azimuth: *{row['azimuth']}*\n" ) print(context) global context_global context_global = context return context else: return "Site name not found."
2. 指定消息解析模式
在调用edit_message_text时添加parse_mode='MarkdownV2'参数,让Telegram识别并渲染Markdown格式:
async def button(update: Update, context: ContextTypes.DEFAULT_TYPE): query = update.callback_query await query.answer() if query.data == 'profile_site': profile_context = get_profile_context(status["site_name"]) # 添加parse_mode参数,启用MarkdownV2解析 await query.edit_message_text( text=f"Profile of site '*{status['site_name']}*':\n{profile_context}", parse_mode='MarkdownV2' ) keyboard = [ [InlineKeyboardButton("Back to Menu", callback_data='back_to_menu'), InlineKeyboardButton("Back to Start", callback_data='start')] ] reply_markup = InlineKeyboardMarkup(keyboard) await query.message.reply_text("What would you like to do next?", reply_markup=reply_markup)
3. 处理特殊字符(可选)
如果参数中包含_、*、[等Telegram MarkdownV2特殊字符(比如示例中的3_0),需要转义后再拼接,否则消息会发送失败。可以添加辅助转义函数:
def escape_markdown_v2(text): """转义Telegram MarkdownV2的特殊字符""" special_chars = r'_*[]()~`>#+-=|{}.!' return ''.join(f'\\{c}' if c in special_chars else c for c in str(text))
然后在拼接文本时调用该函数:
context = ( f"- Enodeb ID: *{escape_markdown_v2(row['enodeb_id'])}*\n" f"- Site ID: *{escape_markdown_v2(row['site_id'])}*\n" f"- MC: *{escape_markdown_v2(row['mc'])}*\n" f"- TAC: *{escape_markdown_v2(row['tac'])}*\n" f"- Region: *{escape_markdown_v2(row['region'])}*\n" f"- Regency: *{escape_markdown_v2(row['regency'])}*\n" f"- Antenna Height: *{escape_markdown_v2(row['antenna_height'])}*\n" f"- Azimuth: *{escape_markdown_v2(row['azimuth'])}*\n" )
效果验证
修改后,Telegram消息会正确渲染出加粗效果:
Profile of site'--':
- Enodeb ID: 0000
- Site ID: 000000
- MC: MC
- TAC: 00
- Region: NORTH CENTRAL
- Regency: city
- Antenna Height: 61
- Azimuth: 3_0
内容的提问来源于stack exchange,提问作者zulfa novita
相关产品推荐
相关产品推荐

