본문 바로가기
Python

[Python] Using Telegram Bot API

by llHoYall 2022. 5. 13.

Let's make a telegram chatbot using Python.

Creating ChatBot

Let's assume that you are using Telegram.

If you add BotFather, you can see it below.

If you scroll the menu, you can see the all available commands.

Let's select the "Create a new bot" menu (/newbot command).

Now, give the name of the bot and username.

Then, the telegram will give you the API key.

The token looks like this.

123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

Using Telegram Bot API

Most of the Telegram's methods can be used in the below format.

https://api.telegram.org/bot<TOKEN>/METHOD

Focus on the prefix bot.

If you have the above token, it has to be "bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11".

For example, let's get the ID.

import requests

TELEGRAM_TOKEN = "bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
TELEGRAM_URL = "https://api.telegram.org"

response = requests.get(f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/getMe")
print(response.json()['result']['id'])

As you already know, this is just an example.

You must use your own token.

requests module should be installed before running this example.

Receiving Message

We can simply get messages using the getUpdates method.

response = requests.get(f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/getUpdates")
print(response.json())

Send a message to your bot first, and run this example.

Then, you can get detailed information about that message.

Use this format to request with parameters.

response = requests.get(f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/getUpdates")
offset = response.json()['result'][-1]['update_id'] + 1
response = requests.get(
  f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/getUpdates?offset={offset}&timeout=10"
)
print(response.json()['result'][-1]['message']['text'])

Send a message quickly right after running this example.

The received messages are stacked up until sending a message.

You can selectively get with the offset parameter what you want to get from these messages.

And bot will be waiting during the timeout parameter if there are no messages. Its unit is seconds.

 

https://core.telegram.org/bots/api#getting-updates

Please refer to the above page for more detailed Telegram's API for getting updates.

Sending Message

Now, let's send a message using the sendMessage method to the user.

response = requests.get(f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/getUpdates")
chat_id =  response.json()['result'][-1]['message']['from']['id']
message = parse.quote("Hello")
response = requests.get(
  f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/sendMessage?chat_id={chat_id}&text={message}"
)

You can watch it on Telegram messenger.

 

In this example, send the text message with a custom keyboard.

response = requests.get(f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/getUpdates")
chat_id =  response.json()['result'][-1]['message']['from']['id']
message = parse.quote("Hello")
keyboard = {
    "keyboard": [
        [{"text": "Btn 11"}, {"text": "Btn 12"}],
        [{"text": "Btn 21"}, {"text": "Btn 22"}],
    ]
}
keyboard = parse.quote(json.dumps(keyboard))
response = requests.get(
    f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/sendMessage?chat_id={chat_id}&text={message}&reply_markup={keyboard}"
)

We use the reply_markup parameter for providing a custom keyboard to the user.

You will see this keyboard.

But, These custom keyboards can only be used in the application.

It doesn't work on the web version.

 

Now, let's send images.

response = requests.get(f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/getUpdates")
chat_id =  response.json()['result'][-1]['message']['from']['id']

with open(IMAGE_FILENAME, "rb") as f:
    response = requests.post(
        f"{TELEGRAM_URL}/{TELEGRAM_TOKEN}/sendPhoto?chat_id={chat_id}",
        files={"photo": f}
    )

In this case, we need to use HTTP's POST method.

You should replace the IMAGE_FILENAME with your image file name.

 

This reference will help you.

https://core.telegram.org/bots/api#available-methods

Telegram Bot Example

Now, you can make a bot with the above methods using thread.

Here are some sample bots.

You can easily understand it now.

'Python' 카테고리의 다른 글

[Python] KivyMD를 사용하여 GUI application 만들기  (0) 2022.09.09
[Python] Using PostgreSQL  (0) 2022.05.19
[Python] Usage of .env  (0) 2022.04.23
[Python] Pandas Course on Kaggle - 6  (0) 2022.01.22
[Python] Pandas Course on Kaggle - 5  (0) 2022.01.21

댓글