使用Python将粗体文本解析为电报

问题描述 投票:0回答:1

我正在尝试使用 python 向我的电报频道发送一些粗体文本,但到目前为止我还没有成功,并且正在寻求一些帮助来做到这一点 我在 MarkdownV2 中使用这个函数

def escape_markdown_v2(text):
    special_chars = r"_[]()~`>#+|{}.!"
    for char in special_chars:
        text = text.replace(char, f'\\{char}')
   return text

这是为了创建消息

def create_match_message(home_team, away_team, match_date, match_time, stadium, tv_channels):
    # Format the text with MarkdownV2 syntax for bold text (wrap in `*`)
    message = (
        f"*{home_team} vs {away_team}*\n"
        f"*Date:* {match_date}\n"
        f"*Time:* {match_time}\n"
        f"*Venue:* {stadium}\n"
        f"*TV Channels:* {tv_channels}"
    )    
    escaped_message = escape_markdown_v2(message)
    return escaped_message

最后将消息发送给 tg

def send_telegram_message(group_id, topic_id, message):
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    payload = {
        "chat_id": group_id,
        "text": message,
        "reply_to_message_id": topic_id,
        "parse_mode": "MarkdownV2"  
    }
    response = requests.post(url, json=payload)
    if response.status_code != 200:
        print(f"Error sending message: {response.status_code}, Response: {response.text}")
    else:
        print("Message sent successfully!")

但不幸的是它的输出是这样的......

*Oxford Utd vs Hull*
*Date:* 2024-11-05
*Time:* 19:45:00
*Venue:* The Kassam Stadium
*TV Channels:* Sky Sports\+

任何帮助将不胜感激。

python
1个回答
0
投票

您需要在通过负载发送的消息中转义特殊字符。

这里是 MarkdownV2 的样式指南:https://core.telegram.org/bots/api#markdownv2-style

也就是说,您需要转义换行符中的斜杠。

© www.soinside.com 2019 - 2024. All rights reserved.