skip to Main Content

I’ve made a telegram bot which logs critical errors in our telegram chat.
This bot has been used in another symfony application (4.4), and worked fine.

But now I’m trying to use it in a Symfony 3.4 project and upon generating an error, telegram responds with:

resulted in a `400 Bad Request` response:
{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Can't find end of the entity starting at  (truncated...)

However, changing the parse_mode from Markdown to HTML fixes the issue, but I’m trying to wrap my head around it why this could be.

This is the string I’m trying to send:

$message = "$user just had an error at: $pathn`$error`n$file:$line";

This is the function which sends the request:

/**
 * @param $method
 * @param $headers
 * @param $body
 * @return mixed|ResponseInterface
 * @throws GuzzleException
 */
public function APIMethod($method, $headers, $body)
{
    $client = new Client();
    $uri = 'https://api.telegram.org/bot' . $this->telegramToken . '/' . $method;

    return $client->request('POST', $uri, [
        'headers' => $headers,
        'form_params' => $body,
    ]);
}

/**
 * @param $telegramId
 * @param $text
 * @return mixed|ResponseInterface
 * @throws GuzzleException
 */
public function sendNotification($telegramId, $text)
{
    try {
        return $this->APImethod('sendMessage', [
            'Content-Type' => 'application/x-www-form-urlencoded',
            'Accept' => 'application/json',
        ], [
            'chat_id' => $telegramId,
            'parse_mode' => 'Markdown',
            'text' => $text,
            'disable_web_page_preview' => true,
        ]);
    } catch (Exception $exception) {
        return $exception->getMessage();
    }
}

Thanks in advance

4

Answers


  1. The problem is very likely the content of one your variables ($user, $path, $file, $line) inside your message, which creates an invalid markdown string.
    Maybe you have an opening markdown symbol without the corresponding closing one. Like * or _.

    If this doesn’t help, please post here the exact message, with variables replaced, so we can spot markdown errors.

    Login or Signup to reply.
  2. This happends when your final string have _ or @ or & (when the endpoint has some rules with the string).

    Login or Signup to reply.
  3. If you just want to send plain text and don’t need Markdown or HTML, just remove the parse_mode parameter altogether. It will send the message as plain text and you won’t have to worry about any special characters (other than URL encoding the message text).

    Login or Signup to reply.
  4. Try using "MarkdownV2" in parse_mode instead of "Markdown".
    It should work on any telegram api library (also make sure you’ve closed the special characters too)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search