Learn to build your first bot in Telegram with Python (2024)

/ #Bots
Learn to build your first bot in Telegram with Python (1)
Dzaky Widya Putra
Learn to build your first bot in Telegram with Python (2)

Imagine this, there is a message bot that will send you a random cute dog image whenever you want, sounds cool right? Let’s make one!

For this tutorial, we are going to use Python 3, python-telegram-bot, and public API RandomDog.

At the end of this tutorial, you will have a stress relieving bot that will send you cute dog images every time you need it, yay!

Getting started

Before we start to write the program, we need to generate a token for our bot. The token is needed to access the Telegram API, and install the necessary dependencies.

1. Create a new bot in BotFather

If you want to make a bot in Telegram, you have to “register” your bot first before using it. When we “register” our bot, we will get the token to access the Telegram API.

Go to the BotFather (if you open it in desktop, make sure you have the Telegram app), then create new bot by sending the /newbot command. Follow the steps until you get the username and token for your bot. You can go to your bot by accessing this URL: https://telegram.me/YOUR_BOT_USERNAME and your token should looks like this.

704418931:AAEtcZ*************

2. Install the library

Since we are going to use a library for this tutorial, install it using this command.

pip3 install python-telegram-bot

If the library is successfully installed, then we are good to go.

Write the program

Let’s make our first bot. This bot should return a dog image when we send the /bop command. To be able to do this, we can use the public API from RandomDog to help us generate random dog images.

The workflow of our bot is as simple as this:

access the API -> get the image URL -> send the image

1. Import the libraries

First, import all the libraries we need.

from telegram.ext import Updater, CommandHandlerimport requestsimport re

2. Access the API and get the image URL

Let’s create a function to get the URL. Using the requests library, we can access the API and get the json data.

contents = requests.get('https://random.dog/woof.json').json()

You can check the json data by accessing that URL: https://random.dog/woof.json in your browser. You will see something like this on your screen:

{“url":"https://random.dog/*****.JPG"}

Get the image URL since we need that parameter to be able to send the image.

image_url = contents['url']

Wrap this code into a function called get_url() .

def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url

3. Send the image

To send a message/image we need two parameters, the image URL and the recipient’s ID — this can be group ID or user ID.

We can get the image URL by calling our get_url() function.

url = get_url()

Get the recipient’s ID using this code:

chat_id = update.message.chat_id

After we get the image URL and the recipient’s ID, it’s time to send the message, which is an image.

bot.send_photo(chat_id=chat_id, photo=url)

Wrap that code in a function called bop , and make sure your code looks like this:

def bop(bot, update): url = get_url() chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url)

4. Main program

Lastly, create another function called main to run our program. Don’t forget to change YOUR_TOKEN with the token that we generated earlier in this tutorial.

def main(): updater = Updater('YOUR_TOKEN') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main()

At the end your code should look like this:

from telegram.ext import Updater, InlineQueryHandler, CommandHandlerimport requestsimport redef get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return urldef bop(bot, update): url = get_url() chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url)def main(): updater = Updater('YOUR_TOKEN') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle()if __name__ == '__main__': main()

5. Run the program

Awesome! You finished your first program. Now let’s check if it works. Save the file, name it main.py , then run it using this command.

python3 main.py

Go to your telegram bot by accessing this URL: https://telegram.me/YOUR_BOT_USERNAME. Send the /bop command. If everything runs perfectly the bot will reply with a random dog image. Cute right?

Learn to build your first bot in Telegram with Python (3)

Handling errors

Great! Now you have a bot that will send you a cute dog image whenever you want.

There is more! The RandomDog API not only generates images, but also videos and GIFs. If we access the API and we get a video or GIF, there is an error and the bot won’t send it to you.

Let’s fix this so the bot will only send a message with an image attachment. If we get a video or GIF then we will call the API again until we get an image.

1. Match the file extension using regex

We are going to use a regex to solve this problem.

To distinguish an image from video or GIF, we can take a look at the file extension. We only need the last part of our URL.

https://random.dog/*****.JPG

We need to define, first, what file extensions are allowed in our program.

allowed_extension = ['jpg','jpeg','png']

Then use the regex to extract the file extension from the URL.

file_extension = re.search("([^.]*)$",url).group(1).lower()

Using that code, make a function called get_image_url() to iterate the URL until we get the file extension that we want (jpg,jpeg,png).

def get_image_url(): allowed_extension = ['jpg','jpeg','png'] file_extension = '' while file_extension not in allowed_extension: url = get_url() file_extension = re.search("([^.]*)$",url).group(1).lower() return url

2. Modify your code

Great! Now for the last part, replace the url = get_url() line in the bop() function with url = get_image_url() , and your code should look like this:

from telegram.ext import Updater, InlineQueryHandler, CommandHandlerimport requestsimport redef get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return urldef get_image_url(): allowed_extension = ['jpg','jpeg','png'] file_extension = '' while file_extension not in allowed_extension: url = get_url() file_extension = re.search("([^.]*)$",url).group(1).lower() return urldef bop(bot, update): url = get_image_url() chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url)def main(): updater = Updater('YOUR_TOKEN') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle()if __name__ == '__main__': main()

Nice! Everything should run perfectly. You can also check out my GitHub account to get the code.

Finally, congratulations for finishing this tutorial, plus you have a cool Telegram bot now.

Please leave a comment if you think there are any errors in my code or writing, because I’m still learning and I want to get better.

Thank you and good luck practicing! :)

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

Learn to build your first bot in Telegram with Python (4)
Dzaky Widya Putra

Data Engineer / Scientist with 1+ years of experience. Skilled in Python, Data Science, and Cloud Technology. Previously worked as a Software Engineer focused on Web Technologies.

If this article was helpful, .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

Learn to build your first bot in Telegram with Python (2024)

FAQs

Learn to build your first bot in Telegram with Python? ›

Building a chatbot on Telegram is fairly simple and requires few steps that take very little time to complete. The chatbot can be integrated in Telegram groups and channels, and it also works on its own. In this tutorial, we will be creating a Python Telegram bot that gives you an avatar image from Adorable Avatars.

How to create a Telegram bot in Python for beginners? ›

  1. Step 1: Set Up a Telegram Bot. Open Telegram and search for the “BotFather” user. ...
  2. Step 2: Install the `telebot` Library. To interact with the Telegram Bot API, we'll use the `telebot` library. ...
  3. Step 3: Create Your Telegram Bot. ...
  4. Step 4: Run Your Bot. ...
  5. Step 5: Interact with Your Bot.
Oct 17, 2023

How to build a Telegram bot from scratch? ›

Now that this is out of the way let's look at the step-by-step process of creating a Telegram bot.
  1. Step 1: Create an Account with Telegram and Chat with the Botfather. ...
  2. Step 2: Create a Name and Username to Get your Token. ...
  3. Step 3: Connect Your Bot to FlowXO. ...
  4. Step 4: Test Your Bot and Distribute.

Is making a Telegram bot easy? ›

Building a chatbot on Telegram is fairly simple and requires few steps that take very little time to complete. The chatbot can be integrated in Telegram groups and channels, and it also works on its own. In this tutorial, we will be creating a Python Telegram bot that gives you an avatar image from Adorable Avatars.

How much does it cost to build a Telegram bot? ›

💸 How much does it cost to build a chatbot? You can hire a developer to build your chatbot starting from $200, but remember that its "intelligence" influences the total price and the time required for creating it. With SendPulse, you can create an intelligent Telegram bot without any technical background and for free.

Which programming language is best for Telegram bot? ›

The simple yet effective Telegram Bot API makes it very easy to develop bots in a number of programming languages. Languages featured in the book include Node. js, Java, Rust, and Elixir.

Can I create Telegram bot without coding? ›

Is it necessary to have programming skills to create a Telegram Bot? No, you don't need programming skills to create a Telegram Bot without coding.

Can Telegram bots make money? ›

UPD 2024: Bots can now sell digital goods and services. For more details, see Telegram Stars and the updated Payments Documentation for digital and physical products. UPD 2021: For up-to-date information about Payments on Telegram, see Payments 2.0 and the Payments Documentation.

What are the disadvantages of Telegram bot? ›

Telegram chatbots are accessible, secure, and available on multiple platforms, making them versatile tools for businesses to reach their goals and engage with clients. However, chatbots have a few drawbacks, such as limitations in understanding complex queries and a need for more human empathy.

How to create a paid Telegram bot? ›

Step-by-step Guide on How to Create a Telegram Bot
  1. Step 1: Start a Chat with @BotFather. Firstly, open your Telegram application and search for "@BotFather" in the search bar at the top. ...
  2. Step 2: Creating a New Bot. ...
  3. Step 3: Customizing Your Bot. ...
  4. Step 4: Deploying and Testing Your Bot. ...
  5. Step 5: Building a Subscription Feature.
Sep 1, 2023

Is hosting Telegram bot free? ›

The standard environment has a free tier but the flexible environment doesn't. Both environments use a pay-as-you-go pricing model.

Is the Telegram bot API free? ›

The Bot API allows you to easily create programs that use Telegram messages for an interface. The Telegram API and TDLib allow you to build your own customized Telegram clients. You are welcome to use both APIs free of charge. You can also add Telegram Widgets to your website.

How to host a Python Telegram bot? ›

To deploy the Telegram bot, follow these six steps:
  1. Create the requirements. txt file. ...
  2. Create the Procfile. The Procfile is a text file that defines the command that should run on Heroku when the application starts. ...
  3. Create the Heroku app. ...
  4. Add the application buildpack. ...
  5. Modify the bot.py file. ...
  6. Deploy the application.
Jan 7, 2022

How to create Telegram bots with Python no nonsense guide? ›

Real World Application
  1. Technical task. 00:54.
  2. Generate access token. 00:31.
  3. Create database. 00:46.
  4. Creating the bot, part 1. 00:49.
  5. Creating the bot, part 2 (database api) 00:56.
  6. Check hometask. 5 questions.
  7. Creating the bot, part 3 (links processing) 02:18.
  8. Create the bot, part 4 (process 'top' requests) 01:28.

Where can I host Python Telegram bot for free? ›

- PythonAnywhere is a free hosting service that allows you to host your Python scripts on a server. - To run your bot on PythonAnywhere, you'll need to upload your code and install any required packages. - Alternatives to PythonAnywhere include Heroku, AWS, and Google Cloud.

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5882

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.