0% found this document useful (0 votes)
206 views6 pages

Creating A Telegram Bot With Python - A Beginner's Guide

A full Guide for a bot in telegram build with python

Uploaded by

rbucha92
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)
206 views6 pages

Creating A Telegram Bot With Python - A Beginner's Guide

A full Guide for a bot in telegram build with python

Uploaded by

rbucha92
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/ 6

Creating a Telegram Bot with Python: A Beginner’s

Guide
This step-by-step tutorial assumes no prior experience. We’ll cover setting up a bot on Telegram, preparing
your Python environment, writing sample code, running locally, and deploying to the cloud. We’ll also
suggest a fun project idea and further learning resources.

1. Create a Telegram Bot Account (Get the API Token)


• Install Telegram on your phone or desktop and log in.
• Talk to BotFather: In Telegram, search for @BotFather (the official bot-creation bot). Start a chat
and send /newbot .
• Name your bot: BotFather will ask for a name (e.g. “MyDemoBot”) and then for a unique username
ending in “Bot” (e.g. “MyDemoBot”).
• Receive the token: BotFather will reply with a long HTTP API token (e.g. 483957...:AAFD... ).
Save this token securely – it’s essentially your bot’s password 1 .
• Test your bot: Try sending /start to your bot in Telegram. It won’t reply yet (it has no code), but
this confirms it exists.

Tip: Treat your bot token like a secret API key. Don’t share it or check it into public code
repositories.

2. Set Up Your Python Development Environment


• Install Python 3: Download and install Python 3 from python.org if not already installed.
• Create a project folder: Choose a location on your computer (e.g. ~/projects/telegram-bot )
and open a terminal/command prompt there.
• Create a virtual environment: Run python3 -m venv venv to make an isolated environment in
the venv/ folder.
• Activate the environment:
• On Windows: venv\Scripts\activate 2 .
• On macOS/Linux: source venv/bin/activate 2 .
After activation, your prompt should show (venv) indicating you’re inside the virtualenv.
• Install libraries: Use pip to install the Telegram bot library. For example, with the python-telegram-
bot library:

pip install --upgrade python-telegram-bot

(This uses the official Telegram bot library; you can find other libraries like Telepot or Telebot, but
python-telegram-bot is widely used 3 .)

1
Your environment is now isolated and ready. Any Python libraries you pip install (e.g. python-
telegram-bot , requests ) will go into this venv without affecting other projects.

3. Write Your First Bot Code (Echo Bot Example)


Create a new file bot.py in your project folder. We’ll write a simple echo bot: it will reply with the same
text you send. The code below uses python-telegram-bot with polling (long-polling mode):

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

TOKEN = 'YOUR_TOKEN_HERE' # Paste your BotFather token here

def start(update, context):


"""Handle /start command."""
context.bot.send_message(chat_id=update.effective_chat.id,
text="Hello! I am your bot.")

def echo(update, context):


"""Echo the user's text message."""
received = update.message.text
context.bot.send_message(chat_id=update.effective_chat.id, text=f"You said:
{received}")

def main():
# Create the Updater and pass it your bot's token.
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher

# Handle /start command


dp.add_handler(CommandHandler("start", start))
# Echo non-command text messages
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))

# Start the bot (begins polling Telegram for updates)


updater.start_polling()
updater.idle() # Keep the program running

if __name__ == '__main__':
main()

Explanation of key parts:


- We set TOKEN to the string from BotFather (keep quotes around it).
- The start function sends a welcome message when the user types /start .
- The echo function replies with the same text the user sent ( update.message.text ).
- We register handlers: CommandHandler("start", start) for the /start command, and
MessageHandler for all other text messages (not commands).

2
- Calling updater.start_polling() tells the bot to begin listening for new messages (long polling). Our
bot will repeat any message we send. This matches the basic echo bot example described in the docs 4 .

Note: This example uses polling. For production you might use webhooks, but polling is
simplest for beginners.

4. Creative Bot Project Idea


As a next step, customize your bot to do something fun or useful. For example, a Motivational Quote Bot:

import random

QUOTES = [
"Keep going – you're getting there!",
"Believe in yourself and all that you are.",
"Stay positive, work hard, make it happen."
]

def motivate(update, context):


quote = random.choice(QUOTES)
context.bot.send_message(chat_id=update.effective_chat.id, text=quote)

• Add a CommandHandler("motivate", motivate) so /motivate sends a random quote.


• You could schedule daily quotes or add more commands (e.g. /help ).
• Other ideas: a Weather Informer (use a weather API), a simple Task Manager (store tasks in a file
or Google Sheet), or a Trivia Bot.

The possibilities are endless – use your Python skills and the Telegram Bot API to build something
interesting.

5. Run the Bot Locally


• Activate your virtualenv (if not already active).
• Run your bot script: In terminal, run python bot.py . You should see no errors and the program
will wait (e.g. Listening... ).
• Test in Telegram: On your phone or desktop, open the chat with your bot and send /start . The
bot should reply. Then send any text; it should echo it back. For example, sending “Hello” might yield
“You said: Hello”. As shown below, the echo bot repeats messages 4 :

3
Screenshot: In Telegram, our running bot replies “You said 'Hello'” when we send “Hello”.

• Leave the terminal open (the bot runs as long as the script is running). Press Ctrl+C to stop it.

6. Deploying Your Bot to the Cloud


To keep your bot running 24/7, deploy it to a server or cloud service. Here are two common options:

• PythonAnywhere:
• Create a free PythonAnywhere account. It provides an online console and scheduler.
• Upload your code (e.g. using the Files tab or git ) and install dependencies (run pip install --
user python-telegram-bot in a Bash console).
• You can run your bot by starting a console and executing python bot.py , or set up a Scheduled
Task to run it at startup. The PythonAnywhere blog tutorial walks through a similar process using
their web console 5 . (Note: Free accounts have some limits with webhooks, but polling bots can
work.)
• Heroku:
• Sign up for a free Heroku account and create a new app.
• In your code repo, add a file named Procfile (no extension) with:

web: python bot.py $PORT

This tells Heroku how to run your app 6 .


• Commit your code and push to Heroku (after installing the Heroku CLI):

heroku login
git init
heroku git:remote -a YourAppName

4
git add .
git commit -m "Deploy bot"
git push heroku master

• In the Heroku dashboard, under Settings → Config Vars, add TOKEN with your bot token value 7

8 (so you don’t hard-code it).

• Heroku will launch your bot. Because Heroku expects a web process, you can modify your code to
use updater.start_webhook(...) instead of polling, or use long polling on a worker dyno. The
details are beyond this intro, but the dev.to guide shows how 7 8 .

• Basic VPS or Other: If you have a VPS (e.g. AWS, DigitalOcean), you can simply install Python, clone
your bot code, and run it (perhaps via screen or a service manager so it stays alive). Ensure
Python and required libraries are installed on the server.

Each platform has its own setup steps, but the key is: upload your code, install dependencies (via pip or
requirements.txt ), and run the bot script. Use environment variables (like os.environ['TOKEN'] )
for configuration, not hard-coded secrets.

7. Next Steps & Learning Resources


• Explore the API docs: The official Telegram Bot API documentation is comprehensive; it’s always
worth reading to discover more methods and features 9 .
• Library docs: Check out the python-telegram-bot documentation for guides and examples (e.g. their
Examples include bots with keyboards, callbacks, etc.).
• Tutorials and courses: Sites like Real Python, freeCodeCamp, or YouTube have beginner-friendly
Python bot tutorials. Consider the Telegram Bots course on Telegram’s own FAQ or community blog
posts.
• Practice projects: Try building different bots (e.g. a bot that replies with jokes, fetches data from an
API, manages polls, etc.). Experiment with inline keyboards, reply buttons, and message handling.
• Community and code: Look at open-source bots on GitHub (search “telegram bot python”). Join the
python-telegram-bot Telegram group for help and ideas.

Keep experimenting! Building a simple bot is a great way to practice Python (virtual environments, HTTP
requests, JSON). Once comfortable, you can add databases, web frameworks, or even machine learning to
your bot’s functionality. Good luck and have fun coding your Telegram bot!

Sources: Telegram’s BotFather guide 1 , python-telegram-bot documentation 3 4 7 8 , Real Python


on virtual environments 2 . These were referenced to ensure accurate setup and deployment steps.

1 5 Building a simple Telegram bot using PythonAnywhere - PythonAnywhere News


https://blog.pythonanywhere.com/148/

2 Python Virtual Environments: A Primer – Real Python


https://realpython.com/python-virtual-environments-a-primer/

5
3 9 python-telegram-bot v22.1
https://docs.python-telegram-bot.org/en/stable/

4 echobot.py - python-telegram-bot v22.0


https://docs.python-telegram-bot.org/en/v22.0/examples.echobot.html

6 7 8 Deploying Python Telegram Bot On Heroku Without Using Flask - DEV Community
https://dev.to/dominickoech/deploying-python-telegram-bot-on-heroku-without-using-flask-kmm

You might also like