【问题标题】:Telegram REST API, send newline in message text?Telegram REST API,在消息文本中发送换行符?
【发布时间】:2018-10-05 17:23:31
【问题描述】:

我想通过 Telegram API 在 <pre> 块或 ``` 中发送消息(HTML 或 Markdown 解析模式,我没有偏好)。

文本是一个带有一些换行符的长字符串。为了便于阅读,我想将其作为代码发送。新行采用 \n 格式,因此 Telegram API 可以处理。

但在代码块中我看不到换行符。我使用过其他机器人,它们可以在代码块中向我发送一些行,所以我很确定这是可能的。

有人可以帮我吗?

这是我目前正在使用的代码:

$url = "https://api.telegram.org/$telegram_apikey/sendMessage?chat_id=$telegram_chatid&parse_mode=Markdown&text=```" . $message ."```";
        $telegramResult = file_get_contents($url
);

消息是这样的:

-------------------------------------------- \n
------------ IMPORT RESULTS ---------------- \n
-------------------------------------------- \n
Product count: 12345 \n
Created: 1234 \n
Total time:  200 \n
-------------------------------------------- \n

【问题讨论】:

标签: php telegram telegram-bot


【解决方案1】:

我搞定了。

您需要发送%0A,而不是发送\n 到Telegram。

【讨论】:

  • 醒了!非常感谢!!
  • 在 python3 中也为我工作过,非常感谢。
【解决方案2】:

我知道您已经找到了解决方案,但您最好使用urlencode 对您的$message 进行编码。

这应该将您的换行符转换为%0A,并转换任何其他非法或潜在危险的字符,例如&、# 或?(如果它们出现在您的消息中)。

【讨论】:

    【解决方案3】:

    @Azquilt 绝对正确,一定要用urlencode

    $telegram_apikey = 'API_KEY';
    $telegram_chatid = 777;
    
    $product_count = 12345;
    $created = 1234;
    $total_time = 200;
    
    $message = <<<TEXT
    --------------------------------------------
    ------------ IMPORT RESULTS ----------------
    --------------------------------------------
    Product count: $product_count
    Created: $created
    Total time:  $total_time
    --------------------------------------------
    TEXT;
    
    $message = urlencode("```$message```");
    
    $url = "https://api.telegram.org/$telegram_apikey/sendMessage?chat_id=$telegram_chatid&parse_mode=Markdown&text=$message";
    $telegramResult = file_get_contents($url);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 2016-05-09
      • 2023-03-23
      • 1970-01-01
      • 2016-12-05
      相关资源
      最近更新 更多