How to make a telegram bot using Python

How to make a telegram bot using Python

Β·

4 min read

Hello everyone, πŸ₯°

let's make a bot telegram python 🐍

Mr.google .gif

What will I make today?

Python is used in this article to create a telegram bot that sends meme images.

Additionally, the article will demonstrate how to integrate an inline keyboard to simplify the experience.

Here is the table of contents. Mr.google .png

before this GitHub repository code


First, if you don't have an account on the telegram you should make an account (it's very simple)

telegram side (steps)

download telegram

log-in or register

this video can help you to login or register

make bot via BothFather

after login at telegram

  1. search about BothFather image.png

  2. click start and choice /newbot

    • choice your name like meme_bot

      It must end in bot. Like this, for example: memeBot or meme_bot.

  3. after you create a new bot.telegram will send you API_TOKEN

    Please keep it and never give it to anyone


code side

create environment


install python library

pip install python-telegram-bot

If you can't install this library check this video


write the first line to send hello wold

it's not line is some of lines 🀣 I didn't want to lie you, but this little lines of codeπŸ˜‰

from telegram.ext import Updater , CommandHandler,CallbackContext
from telegram.update import Update
API_TOKEN="put your API here"
updater = Updater(API_TOKEN, use_context=True)
def start(update: Update, context: CallbackContext):
    update.message.reply_text("hello world")

updater.dispatcher.add_handler(CommandHandler("start", start))
updater.start_polling()

API_TOKEN to control your bot and start to write code

Updater Its purpose is to receive the updates from Telegram and to deliver them to said dispatcher. It also runs in a separate thread, so the user can interact with the bot, for example on the command line

update Object contains info on events occurred. & This object represents an incoming update.

start this function to send hello world when user click start command

The output from the above code

Untitled design.gif

add function to read meme folder

import os
def readFolder():

    yourpath = "file path"
    lis=[]

    for root, dirs, files in os.walk(yourpath, topdown=False):
        for name in files:
            lis.append(os.path.join(root, name))
    return lis[1]
print(readFolder())

add random function to select random image from folder

import os
import random
def readFolder():

    random_=random.randint(0,total image)
    yourpath = "file path"
    lis=[]
    for root, dirs, files in os.walk(yourpath, topdown=False):
        for name in files:
            lis.append(os.path.join(root, name))
    return lis[random_]
print(readFolder())

meme side

now we should add meme image i will make folder and make function to read file from this folder.

2. download it

3. go to this [paragraph](#add function to read folder) to add function to read folder

send meme via bot

now we will writing code to send meme let's go😊

import random
import os
from telegram.chataction import ChatAction
from time import sleep
from telegram.ext import Updater,CommandHandler,CallbackQueryHandler,CallbackContext,MessageHandler,Filters
from telegram.update import Update
from telegram.ext.updater import Updater

yourpath = "file path"
lis=[]

for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        lis.append(os.path.join(root, name))
print("loading.....") 
API_KEY='API_KEY'

def start_commend(update: Update, context: CallbackContext):
    """
    message to handle any "Option [0-9]" Regrex.
    """
    context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
    chat_id = update.message.chat_id
    sleep(1)
    n=random.randint(0,3)
    file=lis[n]

    context.bot.send_photo(chat_id, photo=open(file, 'rb'))

def main():
    updaters=Updater(API_KEY,use_context=True)
    dp=updaters.dispatcher
    dp.add_handler(CommandHandler("start",start_commend))
    updaters.start_polling()
    updaters.idle()
main()
context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.UPLOAD_PHOTO)

**line 22** to add action in chat "Uploading photo"

add InlineKeyboard

what the inline keyboard

Sometimes, you would prefer not to send messages to the chat. When your user changes settings or flips through results, for example. When this happens, you can use InlineKeyboards that are integrated directly into the messages they belong to.

Instead, inline keyboards support buttons that work behind the scenes: callback buttons, URL buttons and switch to inline buttons.

example: image.png

add a inline keyboard function

import random
import os
from telegram.chataction import ChatAction
from time import sleep
from telegram.ext import Updater,CommandHandler,CallbackQueryHandler,CallbackContext,MessageHandler,Filters
from telegram import ReplyKeyboardMarkup,ReplyKeyboardRemove
from telegram.update import Update
from telegram.ext.updater import Updater
from telegram.replykeyboardremove import ReplyKeyboardRemove

yourpath = file_path
lis=[]

for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        lis.append(os.path.join(root, name))
print("loading.....") 
API_KEY=API_KEY


def start_commend(update: Update, context: CallbackContext):
    kd_layout=[["send generate meme"]]
    kbds = ReplyKeyboardMarkup(kd_layout)
    update.message.reply_text(text="""press on "send generate meme" """, reply_markup=kbds)
def echo(update: Update, context: CallbackContext):
    """
    message to handle any "Option [0-9]" Regrex.
    """
    context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
    chat_id = update.message.chat_id
    sleep(1)
    n=random.randint(0,3)
    sleep(1)
    file=lis[n]
    if update.message.text=="send generate meme":

        context.bot.send_photo(chat_id, photo=open(file, 'rb'))

def main():
    updaters=Updater(API_KEY,use_context=True)
    dp=updaters.dispatcher
    dp.add_handler(CommandHandler("start",start_commend))
    dp.add_handler(MessageHandler(Filters.regex(r"."), echo))
    updaters.start_polling()
    updaters.idle()
main()

kd_layout this variable to add inline keyboard called send generate meme to make another inline keyboard you can make array like 2D array in python

index : 0 ,have first option index : 1 , have second option in inline keyboard on this approach

example : kbd_layout = [['reaction', 'video'], ['image', 'joke'],['random']]

result:

Capture.PNG

how to customize the board

Copy of Mr.google (1920 Γ— 1080 px).png thanks for complete this article

Β