0% found this document useful (0 votes)
156 views

Building A Telegram Bot in 2024 With Python - by Erich Hohenstein - Level Up Coding

Uploaded by

陳賢明
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
156 views

Building A Telegram Bot in 2024 With Python - by Erich Hohenstein - Level Up Coding

Uploaded by

陳賢明
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Open in app

38
Search

Get unlimited access to the best of Medium for less than $1/week. Become a member

Building a Telegram Bot in 2024 with Python


Erich Hohenstein · Follow
Published in Level Up Coding
5 min read · Jul 9, 2024

Listen Share More

Telegram Chatbot with Python 2024

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 1/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Look

These last few weeks I have been getting to know more about how to use Large
language models (LLMs) in my own projects.

I am currently working on a building a Financial Assistant powered by AI in order to


help me with my money and budget tracking.

For this, I have tried different approaches to make use of LLMs.

As you can see in this blog, I have found out that Ollama running Llama3 works
amazing in my Macbook Air M2.

Speed almost as fast as ChatGPT. Answers almost as good as ChatGPT.

thumbs up

So then next thing I want to do.

Is to learn how to make a Telegram Bot with Python.

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 2/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

1. Installations
This step is pretty simple. Just do:

pip install python-telegram-bot

2. The BotFather

The BotFather

Now we have to set up the BotFather.

This is the Bot manager that telegram has prepared for us to make our lives easier.

Just open Telegram and search for “BotFather”.

Follow these steps

1. Hit start

2. Tap or write /newbot

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 3/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

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.

Telegram API Token

5. Message /setdescription and send the description for your bot. This will be shown
when users first open the chat.

6. Message /setabouttext and then sent an “about” to be show in your profile.

Something I wanted to mention before continuing.

There is no need to know how to code to run the code provided.

It is pretty straight forward and you can make some modifications without knowing
how to code.

But if you would like to learn quickly Python.

I made a course using Google Colab Notebooks, so there is no need to install


anything.

Actually the course is more of a challenge.

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 4/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

A 10 day coding challenge.

For anybody to take up on coding with Python.

I worked it out to make it as simple as possible.

Explained in english with no complex terminology

Because I wanted to give everyone the chance to learn coding.

You can find the course here.

Let’s now continue!

3. main.py
Create a new Python file and paste the following code:

from typing import Final

# pip install python-telegram-bot


from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters,

print('Bot is now starting up...')

API_TOKEN: Final = 'YOUR TOKEN HERE'


BOT_HANDLE: Final = '@your_bot_handle'

# Command to start the bot


async def initiate_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text('Greetings! I am your bot. How can I assist

# Command to provide help information


async def assist_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text('Here comes the help')

# Command for custom functionality


async def personalize_command(update: Update, context: ContextTypes.DEFAULT_TYP
await update.message.reply_text('This is a custom command, you can put what

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 5/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

def generate_response(user_input: str) -> str:


# Custom logic for response generation
normalized_input: str = user_input.lower()

if 'hi' in normalized_input:
return 'Hello!'

if 'how are you doing' in normalized_input:


return 'I am functioning properly!'

if 'i would like to subscribe' in normalized_input:


return 'Sure go ahead!'

return 'I didn’t catch that, could you please rephrase?'

async def process_message(update: Update, context: ContextTypes.DEFAULT_TYPE):


# Extract details of the incoming message
chat_type: str = update.message.chat.type
text: str = update.message.text

# Logging for troubleshooting


print(f'User ({update.message.chat.id}) in {chat_type}: "{text}"')

# Handle group messages only if bot is mentioned


if chat_type == 'group':
if BOT_HANDLE in text:
cleaned_text: str = text.replace(BOT_HANDLE, '').strip()
response: str = generate_response(cleaned_text)
else:
return # Ignore messages where bot is not mentioned in a group
else:
response: str = generate_response(text)

# Reply to the user


print('Bot response:', response)
await update.message.reply_text(response)

# Log errors
async def log_error(update: Update, context: ContextTypes.DEFAULT_TYPE):
print(f'Update {update} caused error {context.error}')

# Start the bot


if __name__ == '__main__':
app = Application.builder().token(API_TOKEN).build()

# Register command handlers


app.add_handler(CommandHandler('start', initiate_command))
app.add_handler(CommandHandler('help', assist_command))
app.add_handler(CommandHandler('custom', personalize_command))

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 6/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

# Register message handler


app.add_handler(MessageHandler(filters.TEXT, process_message))

# Register error handler


app.add_error_handler(log_error)

print('Starting polling...')
# Run the bot
app.run_polling(poll_interval=2)

4. BotFather II
Now, before running.

We need to set up the commands seen in the code: start and help.

Go back the botFather and type: /setcommands

It will ask you to provide the commands for your chatbot.

These are all the “shortcuts” that your telegram bot shows whenever the user types
“\”.

Reply the \setcommands with:

start — Start conversation

help — Help message

This is what will be show as hints for the user whenever they check the available
commands.

5. Run main.py
Run the main.py file.

Once is running, if you go to your telegram app and chat with your new bot you can
try the following commands:

\start and \help

You can also send it any of the following messages and get a reply:

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 7/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

hi

how are you doing

i would like to subscribe

6. Final comments
I was surprise how well prepared Telegram was for building chatbots.

Easy setup, no complex logins or keys or tokens.

Just a simple interaction with its chatbot.

Of course the chatbot example above is just a basic Telegram chatbot and it doesn’t
do much.

But in my following blogs, I will show how to integrate it with Ollama and Llama3 in
order to have an AI Chatbot right on Telegram.

Thanks for reading!

Python Telegram Chatbot AI Llm

Follow

Written by Erich Hohenstein


194 Followers · Writer for Level Up Coding

Data Scientist | Python | Pandas | Data Mining | Web Scraping | Machine Learning | Power BI | NLP | SQL |
Tableau | HTML/CSS | DAX | Flask | Physics

More from Erich Hohenstein and Level Up Coding


https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 8/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Erich Hohenstein in Level Up Coding

Everything you need to know about SQL for a job interview


So….recently I had a job interview and it didn’t well

Jun 14 68 8

Hayk Simonyan in Level Up Coding

STOP using Docker Desktop: Faster Alternative Nobody Uses


Ditch Docker Desktop and try this faster, lighter tool that will make your life easier!

Oct 9 2.1K 36

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 9/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Jayden Levitt in Level Up Coding

British Billionaire Warns: What's Coming Will Cause Global Meltdown.


See the world as it is and not how you'd like it to be.

Oct 18 2.1K 41

Erich Hohenstein in Level Up Coding

How to run a Private ChatGPT like AI on your Macbook


Installing Llama3 to run locally on your computer. A Free, Fast, and Private LLM

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 10/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Jun 29 51

See all from Erich Hohenstein

See all from Level Up Coding

Recommended from Medium

Kaushik N in The Useful Tech

5 Incredibly Useful Websites to try out


Here are a few useful and few interesting websites to try out. Starting off with a website offering
free documentaries and concluding with…

Oct 15 220 2

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 11/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Anoop Maurya in Generative AI

Unlock Any Open-Source LLM with Ollama:


Stuck behind a paywall? Read for Free!

Sep 8 149 1

Lists

Coding & Development


11 stories · 863 saves

Natural Language Processing


1772 stories · 1374 saves

Generative AI Recommended Reading


52 stories · 1452 saves

Predictive Modeling w/ Python


20 stories · 1614 saves

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 12/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Abdur Rahman in Stackademic

20 Python Scripts To Automate Your Daily Tasks


A must-have collection for every developer

Oct 7 769 5

Shivanshu Gupta

Opensource software that can make your life easy


Sometimes in a business, there are requirements to have certain things to be done, now these
things can be either coded from scratch or can…

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 13/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

Oct 8 174 2

C. L. Beard in The Orange Journal

13 Free Websites to Check Out This Week


Free tools to build your online presence and business

Oct 15 125 2

C. C. Python Programming

Automating E-commerce Operations with n8n and Python — A Real-


World Application
https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 14/15
2024/10/25 晚上9:38 Building a Telegram Bot in 2024 with Python | by Erich Hohenstein | Level Up Coding

n8n is a powerful, low-code automation tool that’s rapidly gaining traction among businesses
and developers. With more than 220 pre-built…

Sep 10 57

See more recommendations

https://levelup.gitconnected.com/building-a-telegram-bot-in-2024-with-python-17b483a7f6b9 15/15

You might also like