Unparalleled suite of productivity-boosting Web APIs & cloud-based micro-service applications for developers and companies of any size.


Create a Telegram Bot that converts your original url in a message to a short link for better tracking

A beginners guide to creating a Python Telegram bot and implementing url shortener APIs


In this roundup example you will learn how to create a Telegram bot and integrate APILayer’s url shortening API service (a link shortening service that takes your long urls and converts them to shortened links that point to your destination url and provided you with advanced analytics that you can reference later).

Link management for Telegram

Short urls are useful for companies that need custom branded domains in short links or a link management platform that can provide advanced analytics for click-throughs on urls that they have posted to social media platforms where they might not own domain, e.g. an affiliate promotion. To shorten urls or generate branded links is one way to send more links in less space.

What you will learn

  • Why you might want to use url shortening services and what link shorteners do
  • Why it is especially useful to use short urls in your Telegram messages (Once you are familiar with using a shortener api in a Telegram bot you might consider using the shortener api to do detailed analytics of the links you send to other social media platforms and part of your deep links and links management strategy).
  • You will be provided with all the code you need to create a Telegram bot with an inbuilt automation provided by a shortener API, which not only makes your links shorter but gives you access to many features. This tutorial will teach you how to edit the Python code at the end of this article to create a Telegram bot that can send messages to Telegram users.
  • You will be provided with a piece of code at the end of this tutorial to retrieve the analytics of links where the bot has shortened urls of websites. APILayer’s URL shortening service code can be used in any project that requires data analytics from user clicks. This service is especially useful for messaging apps like Telegram, where you don’t want to be pasting really long tracking URLs that distract from the content of your message.


Build trust by adding Telegram to your business channels

Your company may already be on Twitter and other social media platforms and use a variety of messaging services. Why would your company need one more?

Why do people prefer Telegram to WhatsApp?

It is free and has many features that are similar. Many Telegram users are uncomfortable with Facebook’s expansion into acquiring WhatsApp. As one Medium writer explains freaks, geeks cult prefer Telegram than WhatsApp. Using Telegram so customers can message you with or receive updates on their preferred messenger builds trust, and extends your business to another domain of users on the internet who might not use your business otherwise.

It just makes good business sense to support more internet communication channels that potential customers prefer. Since being founded in 2013 Telegram has achieved 580 million active monthly users.


What is Telegram?

Telegram is a cloud-based instant messaging and voice-over IP service. Telegram clients exist for both mobile (Android, iOS, Windows Phone, Ubuntu Touch) and desktop systems (Windows, macOS, Linux). Users can send messages and exchange photos, videos, stickers, audio and files of any type. Telegram also provides optional end-to-end-encrypted messaging.


Telegram an emerging messaging service

Telegram has been used in a number of high-profile protests and political campaigns, including the 2017–2018 Iranian protests, the Catalan independence referendum, the 2017–2018 Russian anti-corruption protests and the 2018 Venezuelan presidential crisis. Telegram’s growth as a trusted communication tool outside of Facebook controlled Messenger and WhatsApp, and heavily censored Chinese messenger service WeChat.

A great way for your company to begin to explore the potential of audience engagement on Telegram is to create a Telegram bot that can message groups of people that follow your business using Telegram. We will show you how to create a Telegram bot that converts long urls in messages into a short link so that the link doesn’t distract from your message. The short link when clicked will go to your destination url, this is very easy to do with our url shortener api.

Creating a link management system with a link shortener api

Advanced analytics of your links

However like any business channel you may be interested in the statistics and metrics of how people interact with the URLs sent in your Telegram messages. One way to achieve this is by shortening any URLs you send in a Telegram message with a URL shortener.


How does a URL shortener work?

URL shorteners help with data analytics by providing a way to track clicks and other data points. This can be useful for understanding how people interact with links, what content is most popular, and other insights. A URL shortener takes a URL that can sometimes be a very long URL and converts it to a shorter URL which you can use for data analysis.

e.g. It converts https://www.youtube.com/ to https://p1.rs/7mk39.

With another piece of code you can get the API service to return statistics about users who have clicked on the URL. The statistical information includes their operating system, device, browser, geographic location, and language. Example output of users who have clicked on your shortened URL:

{“os”: {“version”: {“10”: 1}, “family”: {“Windows”: 1}}, “device”: {“type”: {“pc”: 1}, “family”: {“Other”: 1}}, “browser”: {“family”: {“Chrome”: 1}, “version”: {“106.0.0”: 1}}, “geo”: {“city”: {“Ballaghaderreen”: 1}, “country_name”: {“Ireland”: 1}, “region”: {“Roscommon”: 1}}, “language”: {“en-US”: 1}, “country_code”: {“IE”: 1}}

Setting up a Telegram bot and getting an API Key


1. Download and install the Telegram app on your device.

2. Open the Telegram app and search for @Botfather.

3. Tap on the Botfather chat and type /start.

4. Botfather will reply with a list of commands. Type /newbot to create a new bot.

5. Botfather will ask you for a name for your bot. Choose a name and type it in.

6. Botfather will ask you for a username for your bot. Choose a username and type it in. It must end in “bot”, e.g. my_bot or mybot.

7. Botfather will now generate an access token for your new bot. Copy this token and keep it safe, we will need it later.


Congratulations, your new bot is now created! You can now access it by tapping on the bot’s username in the Telegram app. You will now need to copy the API access code and paste it into your Python code.


Adding Telegram API key and message to your Python code

You hopefully found the first seven steps of setting up a Telegram Bot rather easy and you now have an API key for it. In this next step you just need to paste it into your Python code next to where it says telegram_api_key = between the inverted commas. The following step requires you to add the message containing any URLs  you want to send your Telegram bot users, next to where it says mystring = between the inverted commas.

Add your list of Telegram user contact ID numbers into the bot

For your bot to be able to work and contact people who use Telegram you will need them to send you their Telegram user ID number. If your Telegram users are not sure how to find their Telegram user id number, there is a very simple process that will help them find out. To be able to give you their Telegram user ID they can search for a Telegram bot called userinfobot and click ‘/start’ this bot will provide them details of their Telegram user ID number.

Now your Telegram users know how to find their IDs, you will need to process those with your Telegram bot Python code. Next to where it says telegram_userids_list = between the brackets write your list of user ids separated by commas.

What your bot users need to do

There is one last thing your Telegram bot users will need to do. Now you have listed people’s Telegram user id numbers into your bot, your bot is almost ready to begin contacting people. However, Telegram has a strict rule, your bot cannot contact people who haven’t started a Telegram conversation with your bot. Request that each contact on your list messages the bot. They have to find your bot on Telegram and click ‘Start’.

Once they have done this your bot can contact them.

Adding APILayer URL Shortener API Key to Your Bot

In order to shorten your Telegram message URLs, you must first add the API key from APILayer before running the Python code for this Telegram bot. Test your bot with a FREE URL shortener API key from:


Paste the API key next to short_url_api_key = between the inverted commas.

You are now set to go and run your Telegram bot!

Running the Python code

When you have completed all of the above steps you should be able to run the Python code and the bot will message Telegram users. For every Telegram user that the bot messages successfully there will be a success message that identifies the user id or users who have received the message from your bot.

This is an example of a Telegram message where the bot automatically shortened the URLs using the APILayer URL shortener API.

Edit the code at the end of this article to get started with sending and analyzing messages.

Telegram bot code to edit

To use the code below to send messages with automatically short urls to Telegram users you will need to edit it with:

  1. Your Telegram API Key from @Botfather), 
  2. API key from https://apilayer.com/marketplace/short_url-api (url shortener API)
  3. The message that you want to send to Telegram users containing your destination url (website) for the url shortener api to convert to a short link.
  4. Your list of Telegram users who have been instructed to message the bot

# import Python modules

import re

import requests

# Your API keys goes here


short_url_api_key = “YOUR API KEY FROM APILayer URL SHORTNER”


#Your telegram message containing all urls that you want shortened

#This could be a user input value

mystring = “””

From simple image optimisation APIs to more complex computer vision APIs,

APILayer’s Image APIs have what you need to interact with images in a million ways

Image to Text API https://apilayer.com/marketplace/image_to_text-api

Screenshotlayer https://screenshotlayer.com/?utm_source=apilayermarketplace&utm_medium=editorspick



#1 For this bot to work and be able to contact Telegram users, they must provide you with their user ID

#2 A telegram user can findout their userid by messaging userinfobot, check out this YouTube video tutorial

#  by TechJunkie https://youtu.be/W8ifn3ATpdA

#3 IMPORTANT NOTE! Every user you want your bot to be able to contact must have first messaged your bot to create a chat history

# https://stackoverflow.com/questions/41174831/telegram-bot-chat-not-found


#put your own list of Telegram user ids here

telegram_userids_list = [5716951251,76765]

#piece of code to shorten url using the APILayer URL shortening API

def shorten_url(url_to_be_shortened):

url = “https://api.apilayer.com/short_url/hash”

payload = url_to_be_shortened.encode(“utf-8”)

headers= {“apikey”: short_url_api_key}

response = requests.request(“POST”, url, headers=headers, data = payload)

status_code = response.status_code

result = response.text

result = eval(result)

return result[‘short_url’]

#iterate through mystring to check for urls and pass them to the url shortening function

for url in mystring.split():

if “https://” in url or “http://” in url:

mystring = mystring.replace(url, shorten_url(url))


telegram_message = mystring






token = telegram_api_key

method = ‘sendMessage’

for item in telegram_userids_list:

response = requests.post(

url=’https://api.telegram.org/bot{0}/{1}’.format(token, method),

data={‘chat_id’: item, ‘text’: telegram_message}






Analyze a short URL

To use the code below to analyze your short links you will need to edit it with the short link that you want to analyze and add your API key from APILayer https://apilayer.com/marketplace/short_url-api

import requests

# put the short URL you want to analyze here

analyze_url = “https://p1.rs/7mk39

last_slash_position = analyze_url.rfind(‘/’)

extracted_characters = analyze_url[last_slash_position + 1:]

API_url = “https://api.apilayer.com/short_url/stats/” + extracted_characters + “”

payload = {}

headers= {

“apikey”: “YOUR API KEY” # put your API key from APILayer


response = requests.request(“GET”, API_url, headers=headers, data = payload)

status_code = response.status_code

result = response.text



Related posts

The Best Free APIs to Use in 2024 for Your Business


App Store Search API: How To Optimize Your App's Visibility


What is an API? Understanding All the Key Factors


Easy Steps to Automate Data Security by Verifying New Phone Prospects with Zapier

Leave a Reply

Your email address will not be published. Required fields are marked *