Part 1: How to create a Telegram Bot in Python in under 10 minutes
In this short tutorial, I will walk you through the steps for creating your own Telegram bot in python right from scratch.
Let us build a Telegram Bot that echoes the messages that we send to it. In the next part, we will learn how to deploy the bot on websites like Heroku.
Step 1: Set up your Bot’s profile
To set up a new bot, start the conversation with BotFather (@BotFather).
BotFather will help us in creating the new bot.
- Search for @botfather in Telegram.
-
Start your conversation by pressing the Start button.
-
Create the bot by running /newbot command
-
Enter the Display Name and User Name for the bot.
-
BotFather will send you a message with the token
DISCLAIMER — Keep access token of the bot securely. Anyone with your token can manipulate this bot.
Step 2: Coding the bot
Open up the terminal and start by creating a new directory first.
mkdir echo-bot/
cd echo-bot/
We will be using pipenv virtual environment. Make sure that you have pipenv installed in your system.
Pipenv is a dependency manager for Python projects.
We will be using python-telegram-bot package for interacting with Telegram API. Install the package using the following command.
pipenv install python-telegram-bot
Create a new file bot.py and paste the following code in it.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
Replace “TOKEN” on line 56 with the token that you got from the BotFather earlier.
This code uses polling approach to check for messages and will reply to every message it receives with the same message. You can read more about how python-telegram-bot works here - Coding your first bot
Run the bot using
pipenv run python bot.py
Voilà! We’re done 😄
I bet this would have taken you less than 10 minutes to get started with your first bot.
See the 🤖 in action
Play with the bot here - EchoBot
I hope you enjoyed reading the article. Have any bot ideas to share? Comment below!
Checkout my other bots in action:
- BookQuoteBot 📚: Read the best quotes from famous books.
- SplitwizeBot: Uses Splitwise API to list, create and settle the expenses all within Telegram.
In which app I code like it
Nice but I got this error:
Traceback (most recent call last):
File “bot.py”, line 20, in <module>
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
ModuleNotFoundError: No module named ‘telegram’
Never mind, I’ve fixed it.
How did you fixed it, I am having the same error
Don’t run direct bot.py in cmd.
You should run the following commands:
pip install python-telegram-bot --upgrade
Then you should run bot.py by this command:
python bot.py