How to Create and Deploy a Telegram Bot? – Best Telegram

How to Create and Deploy a Telegram Bot?

Introduction or Why You Should Try a Bot

Note: the code samples may be displayed improperly because of markdown. I recommend to continue reading the original article on our blog to make sure all the examples are displayed properly.

Nuances of Telegram Bot Development

  • bottle — for our server; a simple and lightweight WSGI micro web-framework
  • requests — for sending requests to telegram. request lib does not need to be overrepresented. It is universally used throughout the world in a variety of projects.
    Note: you have to install these tools on your computer. We will need them later. For that, open your bash console and install it via pip
pip install bottle requests
  • ngrok – this is an app which provides us with public URLs for our interaction with Telegram WebHook throughout the development phase (look for info on WebHook below). It is useful, as Telegram will not be able to make a connection with our local server because we cannot specify our local address in the Telegram API configuration.
    You should download ngrok from the official site and put the installed app in the folder with the project.

How About to Create Your First Bot?

  • your TOKEN
  • telegram api URL — https://api.telegram.org/bot
  • link on documentation
{"ok":true,"result":[{"update_id":523349956,
"message":{"message_id":51,"from":{"id":303262877,"first_name":"YourName"},"chat":{"id":303262877,"first_name":"YourName","type":"private"},"date":1486829360,"text":"Hello"}}]}
/sendMessage?chat_id=303262877&text=test

WebHook

  • receiving data in real time
  • receiving data and passing it on
  • processing data and giving something in return

Coding Part

from bottle import run, post@post('/')  # our python function based endpoint
def main():
returnif __name__ == '__main__':
run(host='localhost', port=8080, debug=True)
python bot.py
./ngrok http 8080
  • Note: to find ngrok URL, you have to launch ngrok. Then, on the screen similar to the one below, you’ll find URL (it is highlighted on our screenshot). This URL you use in the link for setting WebHook.
from bottle import run, post, request as bottle_request  # <--- we add bottle request@post('/')
def main():
data = bottle_request.json # <--- extract all request data
print(data)returnif __name__ == '__main__':
run(host='localhost', port=8080, debug=True)
{'update_id': <integer>, 'message': {'message_id': <integer>, 'from': {'id': <your telegram id>, 'is_bot': False, 'first_name': '<your telegram name>', 'last_name': '<...>', 'username': '<...>', 'language_code': 'en-En'}, 'chat': {'id': <integer chat id>, 'first_name': '<...>', 'last_name': '<...>', 'username': '<...>', 'type': 'private'}, 'date': 1535022558, 'text': '1'}}
from bottle import (  
run, post, response, request as bottle_request
)def get_chat_id(data):
"""
Method to extract chat id from telegram request.
"""
chat_id = data['message']['chat']['id']return chat_iddef get_message(data):
"""
Method to extract message id from telegram request.
"""
message_text = data['message']['text']
return message_textdef change_text_message(text):
"""
To turn our message backwards.
"""
return text[::-1]@post('/')
def main():
data = bottle_request.json
answer_data = prepare_data_for_answer(data)return response # status 200 OK by default
import requests  
from bottle import (
run, post, response, request as bottle_request
)BOT_URL = 'https://api.telegram.org/bot<YOUR_TOKEN>/' # <--- add your telegram token here; it should be like https://api.telegram.org/bot12345678:SOMErAn2dom/def get_chat_id(data):
"""
Method to extract chat id from telegram request.
"""
chat_id = data['message']['chat']['id']return chat_iddef get_message(data):
"""
Method to extract message id from telegram request.
"""
message_text = data['message']['text']return message_textdef send_message(prepared_data):
"""
Prepared data should be json which includes at least `chat_id` and `text`
"""
message_url = BOT_URL + 'sendMessage'
requests.post(message_url, json=prepared_data) # don't forget to make import requests libdef change_text_message(text):
"""
To enable turning our message inside out
"""
return text[::-1]def prepare_data_for_answer(data):
answer = change_text_message(get_message(data))json_data = {
"chat_id": get_chat_id(data),
"text": answer,
}return json_data@post('/')
def main():
data = bottle_request.jsonanswer_data = prepare_data_for_answer(data)
send_message(answer_data) # <--- function for sending answerreturn response # status 200 OK by defaultif __name__ == '__main__':
run(host='localhost', port=8080, debug=True)
import requests  
from bottle import Bottle, response, request as bottle_requestclass BotHandlerMixin:
BOT_URL = Nonedef get_chat_id(self, data):
"""
Method to extract chat id from telegram request.
"""
chat_id = data['message']['chat']['id']return chat_iddef get_message(self, data):
"""
Method to extract message id from telegram request.
"""
message_text = data['message']['text']return message_textdef send_message(self, prepared_data):
"""
Prepared data should be json which includes at least `chat_id` and `text`
"""
message_url = self.BOT_URL + 'sendMessage'
requests.post(message_url, json=prepared_data)class TelegramBot(BotHandlerMixin, Bottle):
BOT_URL = 'https://api.telegram.org/bot000000000:aaaaaaaaaaaaaaaaaaaaaaaaaa/'def __init__(self, *args, **kwargs):
super(TelegramBot, self).__init__()
self.route('/', callback=self.post_handler, method="POST")def change_text_message(self, text):
return text[::-1]def prepare_data_for_answer(self, data):
message = self.get_message(data)
answer = self.change_text_message(message)
chat_id = self.get_chat_id(data)
json_data = {
"chat_id": chat_id,
"text": answer,
}return json_datadef post_handler(self):
data = bottle_request.json
answer_data = self.prepare_data_for_answer(data)
self.send_message(answer_data)return responseif __name__ == '__main__':
app = TelegramBot()
app.run(host='localhost', port=8080)

If you find this post useful, please tap ? button below 🙂

Ten articles before and after

Airdrop: How to Use the Yetucoin Telegram Bot – Best Telegram

The Telegram That Saved the World – Best Telegram

Building A Telegram Bot With NodeJS – Best Telegram

Why I told my friends to stop using WhatsApp and Telegram – Best Telegram

data-rh=”true”>WE HIT 30,000 MEMBERS ON OUR TELEGRAM COMMUNITY – Shopaneum – Medium – Best Telegram

How to create a Telegram bot, and send messages with Python – Best Telegram

Announcing Coolomat Market Telegram Airdrop – Best Telegram

Top 3 Telegram Channels for Crypto Traders [Crypto Signals 2022] – Best Telegram

7 Bots Every Telegram Channel Owner Should Know About – Best Telegram

Sending a message to a Telegram channel the easy way – Best Telegram