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

如何解决Python向Telegram发送含#字符串被截断的问题

问题原因

#在URL中属于锚点标识符,直接拼接进GET请求的URL时,服务器会将#及其后续内容视为URL的锚点部分,不会作为text参数的内容传递给Telegram API,因此消息会被截断。

解决办法

方法一:使用requests的params参数自动编码(推荐)

让requests库自动处理URL参数的编码,它会把所有特殊字符(包括#、&等)转换成合法的URL编码格式,避免解析错误:

import requests
def sendTelegram(message):
    token = "********************"
    chat_id = "**********"
    url = f"https://api.telegram.org/bot{token}/sendMessage"
    params = {
        "chat_id": chat_id,
        "text": message
    }
    requests.get(url, params=params).json()

方法二:手动对消息内容进行URL编码

使用urllib.parse模块的quote_plus函数手动编码消息字符串,再拼接进URL:

import requests
from urllib.parse import quote_plus

def sendTelegram(message):
    token = "********************"
    chat_id = "**********"
    encoded_message = quote_plus(message)
    url = f"https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={encoded_message}"
    requests.get(url).json()

两种方法都能解决#导致的截断问题,优先推荐方法一,因为它能自动处理所有URL特殊字符,兼容性更强。

内容的提问来源于stack exchange,提问作者Spect

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:04:54