【问题标题】:How to send Telegram Bold message using the Native API?如何使用 Native API 发送 Telegram Bold 消息?
【发布时间】:2021-07-06 06:16:20
【问题描述】:

我想使用原生 Python 请求发送 Telegram 消息,以便在使用 BOLD 时收到“名字”。我尝试过 HTML 和 Markdown 语法,但没有显示。

import json
import requests

# Telegram bot configurations
TELE_TOKEN='TOKEN'
URL = "https://api.telegram.org/bot{}/".format(TELE_TOKEN)

def send_message(text, chat_id):
    url = URL + "sendMessage?text={}&chat_id={}".format(text, chat_id)
    requests.get(url)

# AWS Lambda handler    
def lambda_handler(event, context):
    
    message = json.loads(event['body'])
    chat_id = message['message']['chat']['id']
    first_name = message['message']['chat']['first_name']
    text = message['message']['text']

    # How can the first name be in BOLD?
    reply = "Hello " + first_name + "! You have said:" + text
    
    send_message(reply, chat_id)
    

    return {
        'statusCode': 200
    }

【问题讨论】:

标签: python telegram-bot


【解决方案1】:

Telegram 支持 HTML 或 Markdown 格式。对于格式化,您必须将parse_mode 参数设置为HTMLMarkdown(旧版)或MarkdownV2

例如:要获得“bold text”的输出,您可以使用
text=<b>bold text</b>&parse_mode=HTML
text=*bold text*&parse_mode=Markdown
text=*bold text*&parse_mode=MarkdownV2

您可以简单地在您的代码 sn-p 中进行更改;

def send_message(text, chat_id):
    url = URL + "sendMessage?text={}&chat_id={}&parse_mode=MarkdownV2".format(text, chat_id)
    requests.get(url)

# AWS Lambda handler    
def lambda_handler(event, context):
    ...
    # How can the first name be in BOLD?
    reply = "Hello *" + first_name + "*! You have said:" + text
    ...

在此处阅读有关格式选项的更多信息:https://core.telegram.org/bots/api#formatting-options

【讨论】:

    猜你喜欢
    • 2014-08-11
    • 2023-03-23
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多