8

I want to send an message via the Telegram API in a <pre> block or ``` (HTML or markdown parse mode, I have no preference).

The text is a long string with some line breaks. To make it easy to read I want to send it as code. The new lines are in the \n format, so the Telegram API can handle that.

But in the code block I can't see the newlines. I've used other bots that can send me some lines in a code block, so I'm reasobaly sure it's possible.

Can somebody help me with this?

This is the code that I'm currently using:

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

Where message is something like this:

-------------------------------------------- \n
------------ IMPORT RESULTS ---------------- \n
-------------------------------------------- \n
Product count: 12345 \n
Created: 1234 \n
Total time:  200 \n
-------------------------------------------- \n
Zachary Craig
  • 2,192
  • 4
  • 23
  • 34
NVO
  • 2,566
  • 5
  • 27
  • 57

3 Answers3

27

I got it working.

Instead of sending \n to Telegram, you need to send %0A.

NVO
  • 2,566
  • 5
  • 27
  • 57
4

I see you've found a solution but you might be better off using urlencode to encode your $message.

This should convert your newlines to %0A as well as converting any other illegal or potentially dangerous characters like &, # or ? if they appear in your message.

Azquelt
  • 1,380
  • 10
  • 15
0

@Azquilt is absolutely right, you must use 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);
Jekis
  • 4,274
  • 2
  • 36
  • 42