How to create a Telegram Bot in Python in under 10 minutes – Telegram Group

How to create a Telegram Bot in Python in under 10 minutes

Let us build a Telegram Bot that echoes the messages that we send to it

Created By Pratyush Mishra

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.

  • 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 loggingfrom 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.

Ten articles before and after

Messaging Application Telegram Is Planning To Launch Paid Services In Year 2021 – Telegram Group

Why Telegram Ads will definitely fail? – Telegram Group

How to make Telegram more secure. With the large number of people moving… – Telegram Group

You Should Be Using Telegram instead of WhatsApp. Here is Why! – Telegram Group

Telegram Bot with Rails App – Telegram Group

data-rh=”true”>製作Telegram Bot每日接收最新科技新聞 – Frank Ye – Medium – Telegram Group

Telegram Bot Platform is dying. Once upon a time in June 2015, Telegram… – Telegram Group

Create Your Dream Telegram Sticker Pack – Telegram Group

The Best Telegram Channels You Must Follow in 2022 – Telegram Group

DialogFlow Integration with Telegram – Telegram Group