make telegram bot using python

Hello everybody,😍

let’s make a bot telegram python

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 ke…


This content originally appeared on DEV Community and was authored by mohammed sharaki

Hello everybody,😍

let's make a bot telegram python

heading

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.

table of content

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
(https://www.youtube.com/watch?v=ie0j8Y2oPFs)

make bot via BothFather

after login at telegram

  1. search about BothFather

Image description

  1. click start and choice /newbot

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

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

Please keep it and never give it to anyone

Code Side

Create an environment

(https://www.youtube.com/watch?v=4jt9JPoIDpY)

install python library

pip install python-telegram-bot

If you can't install this library check this video

(https://www.youtube.com/watch?v=jnpC_Ib_lbc)

write the first line to send hello world

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

bot recording from telegram

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.

1. open this link from google drive it have +3000 meme image click here

2. download it

3. go to this paragraph 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:

InlineKeyboards

add a Inline Keyboards 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 the second option in inline keyboard on this approach

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

result:
inline keyboard

how to customize the board

how to customize the board

thanks for completing this article


This content originally appeared on DEV Community and was authored by mohammed sharaki


Print Share Comment Cite Upload Translate Updates
APA

mohammed sharaki | Sciencx (2022-04-08T04:02:21+00:00) make telegram bot using python. Retrieved from https://www.scien.cx/2022/04/08/make-telegram-bot-using-python/

MLA
" » make telegram bot using python." mohammed sharaki | Sciencx - Friday April 8, 2022, https://www.scien.cx/2022/04/08/make-telegram-bot-using-python/
HARVARD
mohammed sharaki | Sciencx Friday April 8, 2022 » make telegram bot using python., viewed ,<https://www.scien.cx/2022/04/08/make-telegram-bot-using-python/>
VANCOUVER
mohammed sharaki | Sciencx - » make telegram bot using python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/08/make-telegram-bot-using-python/
CHICAGO
" » make telegram bot using python." mohammed sharaki | Sciencx - Accessed . https://www.scien.cx/2022/04/08/make-telegram-bot-using-python/
IEEE
" » make telegram bot using python." mohammed sharaki | Sciencx [Online]. Available: https://www.scien.cx/2022/04/08/make-telegram-bot-using-python/. [Accessed: ]
rf:citation
» make telegram bot using python | mohammed sharaki | Sciencx | https://www.scien.cx/2022/04/08/make-telegram-bot-using-python/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.