error 400 when sending request from python to telegram
Asked Answered
K

2

1

I got a 400 error while sending a request from python to telegram.

Here is the code:

bot_message = message
bot_token = 'xxx'
bot_chatID = 'xxx'
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message
response = requests.get(send_text)

Here's the message that caused error :

sharashahira 2021-01-25 10:37:50 @CIMB_Assists Mana ni kata sampai pkul 4;45pm. Sampai sekaranf error. Boikot cimb clicks app😒

It got "emote" , so I got 400 when send to telegram.

This is the error

{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Can't find end of the entity starting at byte offset 17"}
Kokoschka answered 26/1, 2021 at 3:36 Comment(1)
I believe you need to do a POST using requests.post() not requests.get(). There is also a python wrapper for bots that might be useful.Holarctic
T
0

Can't find end of the entity starting at byte offset 17"

This error is caused by a MarkDown error caused by: @CIMB_Assists

The _ starts an underline syntax, but is never closed. Telegram can't send those messages.

There are 2 ways to fix this;

  1. Remove the MarkDown, send the message as HTML:

    '&parse_mode=HTML&text=' + bot_message
    
  2. Remove the _ from the message

    sharashahira 2021-01-25 10:37:50 @CIMBAssists Mana ni kata sampai pkul 4;45pm. Sampai sekaranf error. Boikot cimb clicks app😒
    
Twana answered 26/1, 2021 at 12:20 Comment(0)
C
2

You should add escaping to use markdown format with this character.

The list of characters you must escape is ('_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!')

To add a specific for Telegram escaping you can just use PlainText from telegram-text:

from telegram_text import PlainText

element = PlainText("_text_to_escape_")
escaped_text = element.to_markdown()
escaped_text
'\\_text\\_to\\_escape\\_'
Corn answered 26/1, 2021 at 3:36 Comment(0)
T
0

Can't find end of the entity starting at byte offset 17"

This error is caused by a MarkDown error caused by: @CIMB_Assists

The _ starts an underline syntax, but is never closed. Telegram can't send those messages.

There are 2 ways to fix this;

  1. Remove the MarkDown, send the message as HTML:

    '&parse_mode=HTML&text=' + bot_message
    
  2. Remove the _ from the message

    sharashahira 2021-01-25 10:37:50 @CIMBAssists Mana ni kata sampai pkul 4;45pm. Sampai sekaranf error. Boikot cimb clicks app😒
    
Twana answered 26/1, 2021 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.