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

  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

Is it hard to make a Telegram bot? ›

Thankfully, Telegram provides a bot for us to easily obtain bot tokens: Head over to BotFather and type /newbot . You will be prompted with a series of questions such as the bot name and handle. Follow through with the creation process and you'll be greeted with a bot token at the end of the steps.

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 creating a telegram bot free? ›

GPT4free offers an amazing opportunity to create your own Telegram bot using the free GPT4free library for Python. In this article, we'll walk through the steps to set up the bot, connect it to your Telegram account, and run it on a Linux Ubuntu server. Let's get started!

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.

Can Telegram bots make money? ›

Leveraging Affiliate Marketing Programs

Through affiliate programs, bot creators can promote products or services within their bot's functionalities, earning a commission for each sale or lead generated through their referral link.

Can Telegram bots be hacked? ›

Another concern when using Telegram bots is the possibility of data breaches. If a bot is hacked, personal information can be exposed, including chat logs, messages, and user information.

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.

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.

Which bot is best for Telegram? ›

What Are The Best Telegram Chatbots?
  • Feed Reader Bot. ...
  • Zoom Bot. ...
  • Eddy Travels Bot. ...
  • GetMedia Bot. ...
  • Skeddy Bot. ...
  • Spotify Downloader Bot. ...
  • Botfather. ...
  • Trello bot. If you've ever used this famous task management app, you'll be happy to know that it has a bot version that you can integrate with Telegram.
Feb 1, 2024

How to automate a Telegram bot? ›

Choose your bot. Go to the Bot Structure tab and choose a trigger. This flow starts after a user subscribes to your chatbot by clicking the Start button. To subscribe, users can follow your chatbot link (https://t.me/username), type in your bot's @username in Telegram, or use a website widget.

How to host a Python Telegram bot? ›

Creating a Procfile and requirements. txt
  1. Navigate to the directory containing the bot.py file and enter the virtual environment.
  2. Create a file named Procfile (with no file extension).
  3. Open Procfile , enter web: python3 bot.py , and save the file.

Top Articles
50 Disney Graduation Cap Ideas That Are A Dream Come True
25 Gorg Graduation Cap Ideas That Will Steal The Show - Life Prettified
Buenasado Bluewater
Gma Deals And Steals December 5 2022
Stolen Touches Neva Altaj Read Online Free
404-459-1280
What Is the Z-Track Injection Method?
Saratoga Hills Single-Family Homes for Sale
Cold War Brainpop Answers
Craigslist Tuscarawas Pets
Thomas Funeral Home Sparta Nc
Wat is 7x7? De gouden regel voor uw PowerPoint-presentatie
Booty Chaser Bingo Locations In Minnesota
Mid-Autumn Festival 2024: The Best Lantern Displays and Carnivals in Hong Kong 
Ttw Cut Content
Meet Scores Online 2022
When Is Hobby Lobby Opening In Olean Ny
2406982423
My Big Fat Greek Wedding 3 Showtimes Near Regal Ukiah
Metoprolol  (Kapspargo Sprinkle, Lopressor) | Davis’s Drug Guide
Clay County Tax Collector Auto Middleburg Photos
Wwba Baseball
Cherry Crush Webtoon Summary
Genova Nail Spa Pearland Photos
Satta King Peshawar
Deerc De22 Drone Manual Pdf
Think Up Elar Level 5 Answer Key Pdf
Log in or sign up to view
Statek i zarządzanie załogą w Assassin's Creed Odyssey - Assassin's Creed Odyssey - poradnik do gry | GRYOnline.pl
Kathy Carrack
Dfw Rainfall Last 72 Hours
Raileydiesel
Petco Clinic Hours
Madden 23 Browns Theme Team
Bullmastiff vs English Mastiff: How Are They Different?
Bdo Obsidian Blackstar
Juicy Deal D-Art
Terraria Cement Mixer
Miracle Child Brandon Lake Chords
Cars for Sale by Owner in San Francisco, CA
Mychart Mountainstarhealth
When is the next full moon? September's Harvest Moon is also super
AI Packgod Roast Generator [100% Free, No Login Required]
Left Periprosthetic Femur Fracture Icd 10
Hotels Near William Woollett Jr Aquatics Center
Flow Free 9X9 Level 4
Tax Guidelines for Uber Eats Delivery Partners
Craigslist Pets Olympia
Pizza Mia Belvidere Nj Menu
Live TV | Halifax | CBC Gem
Sammyflood
Unblocked Games 76 Bitlife
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 6662

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.