Preparation

Development

Why use pipenv?

1
$ pipenv install --three python-telegram-bot flask gunicorn requests

Parameter explaination:
–three use python3
python-telegram-bot Telegram Bot API wrapper.
flask Web framework. Using for building webhook API.
gunicorn Python WSGI HTTP server for UNIX. Using for deploying web server.
requests HTTP client library.

After installation, you should have this two file in your project directory:

1
2
3
Project Directory
├── Pipfile.lock
└── Pipfile

for your bot token:

1
$ touch config.ini

config.ini

1
2
3
[TELEGRAM]
ACCESS_TOKEN =
WEBHOOK_URL =

create your bot file.

1
$ touch main.py

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import configparser
import logging

import telegram
from flask import Flask, request
from telegram.ext import Dispatcher, MessageHandler, Filters

# Load data from config.ini file
config = configparser.ConfigParser()
config.read('config.ini')

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)

# Initial Flask app
app = Flask(__name__)

# Initial bot by Telegram access token
bot = telegram.Bot(token=(config['TELEGRAM']['ACCESS_TOKEN']))


@app.route('/hook', methods=['POST'])
def webhook_handler():
"""Set route /hook with POST method will trigger this method."""
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True), bot)

# Update dispatcher process that handler to process this message
dispatcher.process_update(update)
return 'ok'


def reply_handler(bot, update):
"""Reply message."""
text = update.message.text
update.message.reply_text(text)


# New a dispatcher for bot
dispatcher = Dispatcher(bot, None)

# Add handler for handling message, there are many kinds of message. For this handler, it particular handle text
# message.
dispatcher.add_handler(MessageHandler(Filters.text, reply_handler))

if __name__ == "__main__":
# Running server
app.run(debug=True)

Start hosting your bot

1
$ pipenv run python3 main.py

Testing Tool

Get ngrok here
What is ngrok?

1
$ ngrok http 5000

{token} = {webhook_url} = + “/hook”

https://api.telegram.org/bot{token}/setWebhook?url={webhook_url}

1
2
3
4
5
{
ok: true,
result: true,
description: "Webhook was set"
}

Now your bot should be online.

Deploy

Get a Heroku account

Install Heroku CLI

Write a file Procfile

1
web: gunicorn main:app --log-file -

Your project should look like this:

1
2
3
4
5
6
Project Directory
├── config.ini
├── main.py
├── Pipfile
├── Pipfile.lock
└── Procfile

Initialize git repository

1
$ git init

create new branch and switch to that branch

1
$ git checkout -b production

add repo folders into git

1
$ git add .

commit

1
$ git commit -m "Deploying to Heroku"

Log in Heroku account

1
$ heroku login

Add remote Heroku repository

1
$ heroku git:remote -a {your_heroku_app_name}

Push to Heroku repository

1
$ git push heroku HEAD:master

Reference

實戰篇-打造人性化 Telegram Bot
Python Telegram Bot 教學