How to Create a Telegram Bot using Python (2024)

/ #Python
How to Create a Telegram Bot using Python (1)
Ashutosh Krishna
How to Create a Telegram Bot using Python (2)

Automated chatbots are quite useful for stimulating interactions. We can create chatbots for Slack, Discord, and other platforms.

In this article, I'll teach you how to build a Telegram chatbot that will tell you your horoscope. So, let’s get started!

How to Get Your Bot Token

To set up a new bot, you will need to talk to BotFather. No, he’s not a person – he’s also a bot, and he's the boss of all the Telegram bots.

  1. Search for @botfather in Telegram.
How to Create a Telegram Bot using Python (3)

2. Start a conversation with BotFather by clicking on the Start button.

How to Create a Telegram Bot using Python (4)

3. Type /newbot, and follow the prompts to set up a new bot. The BotFather will give you a token that you will use to authenticate your bot and grant it access to the Telegram API.

How to Create a Telegram Bot using Python (5)

Note: Make sure you store the token securely. Anyone with your token access can easily manipulate your bot.

How to Set Up Your Coding Environment

Let’s set up the coding environment. While there are various libraries available to create a Telegram bot, we’ll use the pyTelegramBotAPI library. It is a simple but extensible Python implementation for the Telegram Bot API with both synchronous and asynchronous capabilities.

Install the pyTelegramBotAPI library using pip:

pip install pyTelegramBotAPI

Next, open your favorite code editor and create a .env file to store your token as below:

export BOT_TOKEN=your-bot-token-here

After that, run the source .env command to read the environment variables from the .env file.

How to Create Your First Bot

All the API implementations are stored in a single class called TeleBot. It offers many ways to listen for incoming messages as well as functions like send_message(), send_document(), and others to send messages.

Create a new bot.py file and paste the following code there:

import osimport telebotBOT_TOKEN = os.environ.get('BOT_TOKEN')bot = telebot.TeleBot(BOT_TOKEN)

In the above code, we use the os library in order to read the environment variables stored in our system.

If you remember, we exported an environment variable called BOT_TOKEN in the previous step. The value of BOT_TOKEN is read in a variable called BOT_TOKEN. Further, we use the TeleBot class to create a bot instance and passed the BOT_TOKEN to it.

We then need to register message handlers. These message handlers contain filters that a message must pass. If a message passes the filter, the decorated function is called and the incoming message is supplied as an argument.

Let's define a message handler that handles incoming /start and /hello commands.

@bot.message_handler(commands=['start', 'hello'])def send_welcome(message): bot.reply_to(message, "Howdy, how are you doing?")

Any name is acceptable for a function that is decorated by a message handler, but it can only have one parameter (the message).

Let’s add another handler that echoes all incoming text messages back to the sender.

@bot.message_handler(func=lambda msg: True)def echo_all(message): bot.reply_to(message, message.text)

The above code uses a lambda expression to test a message. Since we need to echo all the messages, we always return True from the lambda function.

You now have a simple bot that responds to the /start and /hello commands with a static message and echoes all the other sent messages. Add the following to the end of your file to launch the bot:

bot.infinity_polling()

That’s it! We have a Telegram bot ready. Let’s run the Python file and go to Telegram to test the bot.

Search for the bot using its username if you’re unable to find it. You can test it by sending the commands like /hello and /start and other random texts.

How to Create a Telegram Bot using Python (6)

Note: All the message handlers are tested in the order in which they were declared in the source file.

For more information on using the pyTelegramBotAPI library, you can refer to their documentation.

How to Code the Horoscope Bot

Let’s shift our attention to building our Horoscope Bot now. We will use message chaining in the bot. The bot will first ask for your zodiac sign, and then the day, and then it will respond with the horoscope for that particular day.

Under the hood, the bot interacts with an API to get the horoscope data.

We are going to use the Horoscope API that I built in another tutorial. If you wish to learn how to build one, you can go through this tutorial. Make sure you explore the APIs here before getting started.

How to fetch the horoscope data

Let’s create a utility function to fetch the horoscope data for a particular day.

import requestsdef get_daily_horoscope(sign: str, day: str) -> dict: """Get daily horoscope for a zodiac sign. Keyword arguments: sign:str - Zodiac sign day:str - Date in format (YYYY-MM-DD) OR TODAY OR TOMORROW OR YESTERDAY Return:dict - JSON data """ url = "https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily" params = {"sign": sign, "day": day} response = requests.get(url, params) return response.json()

In the above Python code, we created a function that accepts two string arguments – sign and day – and returns JSON data. We send a GET request on the API URL and pass sign and day as the query parameters.

If you test the function, you will get an output similar to below:

{ "data":{ "date": "Dec 15, 2022", "horoscope_data": "Lie low during the day and try not to get caught up in the frivolous verbiage that dominates the waking hours. After sundown, feel free to speak your mind. You may notice that there is a sober tone and restrictive sensation today that leaves you feeling like you will never be able to break free from your current situation. Don't get caught in this negative mindset." }, "status": 200, "success": true}

Note: You can explore more about the requests library in Python in this tutorial.

How to add a message handler

Now that we have a function that returns the horoscope data, let’s create a message handler in our bot that asks for the zodiac sign of the user.

@bot.message_handler(commands=['horoscope'])def sign_handler(message): text = "What's your zodiac sign?\nChoose one: *Aries*, *Taurus*, *Gemini*, *Cancer,* *Leo*, *Virgo*, *Libra*, *Scorpio*, *Sagittarius*, *Capricorn*, *Aquarius*, and *Pisces*." sent_msg = bot.send_message(message.chat.id, text, parse_mode="Markdown") bot.register_next_step_handler(sent_msg, day_handler)

The above function is a bit different from the other functions we defined earlier. The bot’s horoscope functionality will be invoked by the /horoscope command. We are sending a text message to the user, but notice that we have set the parse_mode to Markdown while sending the message.

Since we’ll use message chaining, we used the register_next_step_handler() method. This method accepts two parameters: the message sent by the user and the callback function which should be called after the message. Thus, we pass the sent_msg variable and a new day_handler function that we’ll define next.

Let’s define the day_handler() function that accepts the message.

def day_handler(message): sign = message.text text = "What day do you want to know?\nChoose one: *TODAY*, *TOMORROW*, *YESTERDAY*, or a date in format YYYY-MM-DD." sent_msg = bot.send_message( message.chat.id, text, parse_mode="Markdown") bot.register_next_step_handler( sent_msg, fetch_horoscope, sign.capitalize())

We fetch the zodiac sign from the message.text attribute. Similar to the previous function, it also asks the day for which you want to know the horoscope.

In the end, we use the same register_next_step_handler() method and pass the sent_msg, the fetch_horoscope callback function, and the sign.

Let’s now define the fetch_horoscope() function that accepts the message and the sign.

def fetch_horoscope(message, sign): day = message.text horoscope = get_daily_horoscope(sign, day) data = horoscope["data"] horoscope_message = f'*Horoscope:* {data["horoscope_data"]}\\n*Sign:* {sign}\\n*Day:* {data["date"]}' bot.send_message(message.chat.id, "Here's your horoscope!") bot.send_message(message.chat.id, horoscope_message, parse_mode="Markdown")

This is the final function where we get the sign from the function parameter and the day from the message.text attribute.

Next, we fetch the horoscope using the get_daily_horoscope() function and construct our message. In the end, we send the message with the horoscope data.

Bot Demo

Once you run the Python file, you can test this functionality. Here’s the demo:

Recommended Next Steps

As of now, the bot stops working as soon as we stop our Python application. In order to make it run always, you can deploy the bot on platforms like Heroku, Render, and so on.

Here's a link to the GitHub repo for this project - feel free to check it out.

You can also add more functionalities to the bot by exploring the Telegram APIs.

Thanks for reading! You can follow me on Twitter.

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

How to Create a Telegram Bot using Python (7)
Ashutosh Krishna

Application Developer at Thoughtworks India

If you read this far, thank the author to show them you care.

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

How to Create a Telegram Bot using Python (2024)

FAQs

How to create a simple Telegram bot in Python? ›

Contents
  1. Step #0: A little bit of Telegram Bot API theory.
  2. Step #1: Implement the exchange rates requests.
  3. Step #2: Create a Telegram bot using @BotFather.
  4. Step #3: Configure and initialize the bot.
  5. Step #4: Write the /start command handler.
  6. Step #5: Create the /help command handler.
  7. Step #6: Add the /exchange command handler.

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.

Is it hard to make a Telegram bot? ›

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 that replies? ›

How to create a Telegram bot that replies?
  1. Go to Telegram and talk to the Botfather.
  2. Create a New Bot using “/newbot” command.
  3. Give a Name for your Telegram Bot.
  4. Choose a Username for your Telegram Bot.
  5. Generate and use the Telegram API Token.
  6. Create a free Manychat account and connect it to Telegram.
  7. Create your chatbot flow.
Jul 22, 2024

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.

Can I earn money from a Telegram bot? ›

Growing Your Telegram Bot Business

When it comes to advertising on Telegram, while there are no direct paid advertising options, you can engage in paid promotions on other channels, cross-promote to gain more followers, utilize promotion on different social media platforms, and list your bot in Telegram catalogs.

How to confuse a bot on Telegram? ›

However, some responses or nuances of human speech can throw the bot off the scent, and lead to a dead end.
  1. 1 - Tell the Chatbot to Reset or Start Over. ...
  2. 2 - Use Filler Language. ...
  3. 3 - Ask Whatever Is on the Display Button. ...
  4. 4 - Answering Outside the Pre-Selected Responses. ...
  5. 5 - Ask for Help or Assistance.

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 be malicious? ›

Phishing attacks via Telegram bots pose a serious threat to the security and privacy of users. Fraudsters use fake bots and manipulative tactics to try to steal personal information or spread malware. It is important to remain vigilant and take the necessary steps to protect yourself from this threat.

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

Why it's unbeatable? Because it's FREE! Yes - you read it right. If you want to use our bots - they are free, forever, with no limits.

Which bot is best for Telegram? ›

What Are The Best Telegram Chatbots?
  • Botpress. ...
  • Feed Reader Bot. ...
  • Zoom Bot. ...
  • Eddy Travels Bot. ...
  • GetMedia Bot. ...
  • Skeddy Bot. ...
  • Spotify Downloader Bot. ...
  • Botfather.
Feb 1, 2024

Can I trust Telegram bots? ›

What are the potential risks of using Telegram bots? Potential risks include scams, phishing attempts, malware, and unauthorized access to personal data. Stay vigilant, avoid interacting with unknown or suspicious bots, and report suspicious activities.

Can ChatGPT create a Telegram bot? ›

Integrate with ChatGPT, and provide questions about your company to which you want your bot to respond. Read more: How to connect ChatGPT from OpenAI to your chatbot. Once you create a Telegram bot and its scenario, you can add your chatbot link to your website or link it to smart pop-ups.

Can a Telegram bot owner see messages? ›

By default, all bots added to groups run in Privacy Mode and only see relevant messages and commands: Commands explicitly meant for them (e.g., /command@this_bot ). General commands (e.g. /start ) if the bot was the last bot to send a message to the group. Inline messages sent via the bot.

How to make an automated Telegram bot? ›

How to create a Telegram bot
  1. Open the Telegram app on your computer. To create a Telegram bot, you'll need to have the Telegram app installed on your computer. ...
  2. Connect to BotFather. ...
  3. Select the New Bot option. ...
  4. Add a bot name. ...
  5. Choose a username for your bot. ...
  6. Connect to BotFather. ...
  7. Choose your bot. ...
  8. Select the Edit Bot option.
Apr 19, 2023

How do you make a simple bot in Python? ›

How to Make a Chatbot in Python Step By Step [With Source Code]
  1. Prepare the Dependencies.
  2. Import Classes.
  3. Create and Train the Chatbot.
  4. Communicate with the Python Chatbot.
  5. Train your Python Chatbot with a Corpus of Data.
May 14, 2024

How to host a python-telegram-bot? ›

Deploy a Python Telegram Bot (Webhook Method) to Production in 5 Minutes
  1. Register the Bot.
  2. Set up.
  3. Create a Space for your Bot.
  4. Create the Capsule.
  5. Add Environment Variables.
  6. Setup Webhook.
  7. Chat with the Bot.
Jul 11, 2024

How can I create a free Telegram bot? ›

Let's get started!
  1. Step 1: Creating a Telegram Bot. Open Telegram and find the @BotFather bot. ...
  2. Step 2: Cloning the Code Repository. ...
  3. Step 3: Setting Up the Virtual Environment. ...
  4. Step 4: Configuring the Token and Clear Command. ...
  5. Step 5: Running the Bot. ...
  6. Step 6: Setting Up Autostart on the Server.
Jan 19, 2024

How to create a Telegram bot using Python 2024? ›

Follow these steps
  1. Hit start.
  2. Tap or write /newbot.
  3. Provide a name for the chatbot. It has to include the word “bot” in the name.
  4. Once the bot name is accepted, you will receive an API TOKEN. Save it.
Jul 8, 2024

References

Top Articles
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 5335

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.