How to create a Telegram Bot in Python in under 10 minutes | by Proxlight | Medium – Telegram 安装

Haley

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.

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

69000 Seconds to Hours | Telegram

499 Minutes to Days | Telegram

1439 Minutes to Days | Telegram

520 Minutes to Days | Telegram

780 Minutes to Days | Telegram

10+ Telegram Channel for Korean Movies | Latest and Popular – TelegramTutor

Ek villain returns Telegram Channel

25+ Best Telegram Anime Channels Movies in 2022 – TelegramGuru

Radhe Shyam Movie Download Telegram Channel link

What does “last seen recently” mean in Telegram?

About Me

Pretium lorem primis senectus habitasse lectus donec ultricies tortor adipiscing fusce morbi volutpat pellentesque consectetur risus curae malesuada dignissim lacus convallis massa mauris.