skip to Main Content

I wanted it to be automatically copied after sending this message when clicking on context.user_data["code"] So I used “ and parse_mode="MarkdownV2"

await context.bot.send_message(
    chat_id=CHANEL_ID, 
    text= f"{context.user_data['key']}nnCode:  `{context.user_data['code']}`nnMod:  {context.user_data['mod']}nnby: @{update.effective_user.username}",
    parse_mode='MarkdownV2'
    )

But if username of the user has _ like: @Jason_99, I get the following error. how to fix it?
telegram.error.BadRequest: Can't parse entities: can't find end of italic entity at byte offset 53

I tried to apply pars_mode to only part of the text. But I don’t know if it is possible or not. I did not find a way

2

Answers


  1. You’ll need to clean the username so there are no un-closed markdown entries.

    I’d replace _ with - like so:

    clean_username = update.effective_user.username.replace('_', '-')
    

    And then use it in your message:

    text= f"{context.user_data['key']}nnCode:  `{context.user_data['code']}`nnMod:  {context.user_data['mod']}nnby: @{clean_username}"
    

    The proper way to include a link to a user is to make a markdown link to the user ID:

    text=f"Hello user [user-a](tg://user?id=1234)"
    
    Login or Signup to reply.
  2. In Addition to 0stone0’s answer let me add, that python-telegram-bot comes with built-in functionality to escape text for markup processing: escape_markdown. That way you can use

    clean_username = escape_markdown(update.effective_user.username, version=2)
    

    which has two benefits:

    • the username is not displayed in an altered way, but in the original form
    • you don’t have to manuall replace all characters that need escaping (it’s more than just underscores)

    Disclaimer: I’m currently the maintainer of python-telegram-bot

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