You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram API如何保留输入文本中的换行符?

Telegram sendMessage接口保留文本换行的解决方法

关键注意点

你之前的请求里包含了description字段——这是sendMessage接口不支持的参数,可能会干扰接口正常处理,建议先移除这个多余字段。以下是三种有效保留换行的方式:

  • 使用Markdown/MarkdownV2格式
    当parse_mode设为Markdown或MarkdownV2时,需要在换行位置添加两个空格加\n(单引号包裹JSON时直接写\n即可)。示例命令:

    curl -s "https://api.telegram.org/bot$botToken/sendMessage" \
    -H 'Content-Type: application/json' \
    -d '{ "parse_mode": "Markdown", "chat_id": "234567", "text": "第一行  \n第二行\n第三行" }'
    

    注意:MarkdownV2对特殊字符(如_、*)有强制转义要求,若文本包含这类符号需额外处理。

  • 使用HTML格式
    将parse_mode设为HTML,文本中的换行用<br>标签替代\n。示例命令:

    curl -s "https://api.telegram.org/bot$botToken/sendMessage" \
    -H 'Content-Type: application/json' \
    -d '{ "parse_mode": "HTML", "chat_id": "234567", "text": "第一行<br>第二行<br>第三行" }'
    
  • 不指定格式直接使用转义换行
    无需设置parse_mode,直接在text字段中使用JSON要求的转义换行符\\n;如果用单引号包裹JSON内容,也可以直接写\n(单引号不会转义内部字符)。示例:

    # 双引号转义写法
    curl -s "https://api.telegram.org/bot$botToken/sendMessage" \
    -H 'Content-Type: application/json' \
    -d "{ \"chat_id\": \"234567\", \"text\": \"第一行\\n第二行\\n第三行\" }"
    
    # 单引号直接写法
    curl -s "https://api.telegram.org/bot$botToken/sendMessage" \
    -H 'Content-Type: application/json' \
    -d '{ "chat_id": "234567", "text": "第一行\n第二行\n第三行" }'
    

内容的提问来源于stack exchange,提问作者Mévatlavé Kraspek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:20:38