Build your first telegram bot in python

Apoorva Kumar Vandagadde
2 min readJun 9, 2021

What are Telegram bots..?

Bots are simply Telegram accounts operated by software — not people — and they’ll often have AI features. They can do anything — teach, play, search, broadcast, remind, connect, integrate with other services, or even pass commands to the Internet of Things.

Getting Started

We will build a password generator bot in python.

Before we start to build a bot. We need to create/register a bot in the telegram.

Create a chatbot with Bot Father

  • Go to @BotFather
  • Send the /newbot command .which leads to create a new bot.
  • Set the name and username for your bot.
  • BotFather will send the Bot API token.
ScreenShot : Create/Register a chatbot with bot father

Creating bot environment

  • Create Virtual Environment
python3 -m venv .venv
  • Activate Virtual Environment

For Linux :

source .venv/bin/activate

For Windows:

.venv\Scripts\Activate
  • Install required Libraries

Libraries we need for our bot -

pyTelegramBotAPI: A simple, but extensible Python implementation for the Telegram Bot API.

pip install pyTelegramBotAPI

Write a program for bot

  • Import Require Libaries
import telebot
import string
from random
  • Create an instance of the TeleBot class
bot = telebot.TeleBot("TOKEN")

Note: Replace TOKEN with your own API token.

  • Define a message handler that handles incoming /start command
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message,f"Hello,{message.chat.username}")
  • Define another message handler that handles /genrate_password command

When users send this command to bot. The bot will send Generated password string

@bot.message_handler(commands=['genrate_password'])
def genrate_password(message):
characters = string.ascii_letters + string.punctuation + string.digits#Generate random charecter password = "".join(random.choice(characters) for x in range(random.randint(8, 16)))
bot.send_message(message.chat.id,f"Genarated Password {password}")
  • Start the bot using polling
bot.polling()
  • Our code file looks like
import telebot
import string
from random
bot = telebot.TeleBot("TOKEN")@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message,f"Hello,{message.chat.username}")
@bot.message_handler(commands=['genrate_password'])
def genrate_password(message):
characters = string.ascii_letters + string.punctuation + string.digits#Generate random charecterpassword = "".join(random.choice(characters) for x in range(random.randint(8, 16)))bot.send_message(message.chat.id,f"Genarated Password {password}")bot.polling()
  • Run the code
python filename.py

I hope you enjoy building your first Telegram bot.

--

--

Apoorva Kumar Vandagadde
0 Followers

Self-taught Developer and freelancer with expertise in Python, Databases, Data Analysis, Chatbots, Web Backend devlopement and API .