Search code examples
pythonpython-3.xtelegramtelegram-botpython-telegram-bot

Transform URL appearance and send it by Telegram bot


I'm using a Telegram Bot to send informations from python script.

My function to send message to my Telegram Bot is :

def telegram_bot_sendtext(bot_message):

    bot_token = 'token'
    bot_chatID = 'id'
    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)

    return response.json()

One of the informations is a variable called "URL", which contains URL, for example, this one : https://www.sezane.com/fr/product/collection-printemps-all-0804/robe-will?cou_Id=859

I have two questions :

  1. When I'm using other variables, everything OK. However, sending URL variable, nothing happens and I don't receive any message
  2. How can I do to receive the link as "link with short name" and not as entire link ? For example, receive "Google" instead of "www.google.com" ?

Solution

  • 1) The markdown parseMode requires a valid markdown syntax, I guess the _ in your example url starts a Markdown italic text which is never closed, Telegram returns a error and the message will not be send. Use parse_mode: HTML to disable this. (There are no _ elements in html parsemode)

    2) Both markDown and HTML parsemode provide options to add a hyperlink to the message;

    HTML

    <a href="https://www.google.com/">Google</a>
    

    MarkDown

    [Google](https://www.google.com/)
    
    telegram_bot_sendtext("Please press this [link](https://www.sezane.com/fr/product/collection-printemps-all-0804/robe-will?cou_Id=859)")
    

    For more information, please take a look at there documentation.