make telegram bot using python
Tags: bots, telegram, python
Published: 2022-04-08 04:02:21

## Hello everybody,😍
let's make a bot telegram ``python``

![heading](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mnmdq7bh45r44os02yxn.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.

![table of content](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ibu1or9510z1pdeq79v.png)
>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
- [windows,linux](https://desktop.telegram.org/)
- [mac os](https://macos.telegram.org/)
- [android](https://telegram.org/android)
- [IPhone](https://itunes.apple.com/app/telegram-messenger/id686449807)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5w65o9he8q2fjxgus2rh.png)

2. click start and choice ``/newbot``

>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 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v4obxs2wi7iaxtmpe1fy.gif)

<h3 id="add function to read folder">add function to read meme folder</h3>

```
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](https://drive.google.com/drive/folders/1hCtc99IlCZMHEIdOrK-MzJaXrG5q81O0)
#### 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:

![InlineKeyboards](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/033417ohtsggcfel8b2w.png)
 
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vy7jhmfegp0zkwx2hgcg.PNG)
### how to customize the board
![how to customize the board](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytn8g9dolazmvyx8jfub.png)

thanks for completing this article