Telegram

Introduction

Hello, guys! My name is Eugene. And now I want to introduce you the world of Telegram bots using Dokkur.

This tutorial will show you how to create a simple echo-bot with WebHooks for Telegram on Python and deploy it to Dokkur in several minutes. These instructions will also give you enough information to make the most out of Dokkur.

We will create an extendable app, so if you want, you can add your own classes/routes. Despite the fact that the app executes only echo command, it contains a basis for a good scalability. It is reached by having separate storage for classes, resources and settings.

Attention! Because of its simplicity, the app is not covered with tests, and we strongly recommend that you use py.test for these purposes. If you need advice on working with tests for bots, email us, and we'll help you write a new bot, or to clean up existing one.

Note that in case you don’t want to copy code from here, please clone this GitHub repository.

So, let’s start!

Be sure that you already have:

  1. Dokkur account.
  2. SSH keys added to your account.
  3. Python version 2.7 installed locally - see the installation guides for OS X, Windows, and Linux.
  4. Setuptools and Pip installed locally. See the Python install guides above for installation instructions.
  5. Virtualenv installed locally. Accomplish this by running pip install virtualenv.
  6. A Telegram account.
  7. A banana milkshake to celebrate at the end (obligatorily!).

Register a bot in Telegram

For this purpose you should use @BotFather, the telegram's designated robot for registering and managing your bots. Simply start chatting with it and you will see all of your options. -- here we focus only on registering our new bot.

Simply type:

/newbot

You will be asked to provide a name and identifier for your bot. Once done, BotFather will give you a token which is what you need to configure in your server component later in this article.

Code a bot using Python

Create a requirements.txt file which contains these information:

certifi==2016.2.28 
falcon==1.0.0
future==0.15.2
gunicorn==19.3.0
peewee==2.8.1
python-mimeparse==1.5.2
python-telegram-bot==4.3.2
six==1.10.0
urllib3==1.16
wheel==0.24.0

We define our bot's dependencies, which you can then install by running
pip install -r requirements.txt

Now we should create a folder named app and there create two folders named classes and resources.

In app folder create a file settings.py and paste these lines:

import telegram
BOT_TOKEN = 'your_bot_token'
WEBHOOK_URL = 'your_dokkur_url/HOOK'
bot = telegram.Bot(token=BOT_TOKEN)

Instead of your_bot_token paste token, that BotFather gave you, when you registered your bot.

Instead of your_dokkur_url you will later paste Dokkur URL once you created an app in Dokkur.

We strictly recommend you to pass all the secret values through the environment variables, but not using the hardcoding. Please be careful with your secure data.

In classes folder create a file chat.py and paste these lines:

from ..settings import bot

class Chat(object):

def __init__(self, chat_id, text=''):
self.chat_id = chat_id
self.text = text

# main process method
def process(self):
bot.sendMessage(chat_id=self.chat_id, text=u"> {}".format(self.text))

Here we've created a Chat class which will operate with text, that our bot should echo.

Let's continue and create several files in resources folder: hook.py, main.py and set-webhook.py.

The hook.py file should contain the following lines:

import telegram
import json
import traceback
from ..classes import Chat

class HookResource(object):
def on_post(self, req, resp):
try:
body = req.stream.read()
body_decoded = body.decode("utf-8")
json_body = json.loads(body_decoded)

update = telegram.Update.de_json(json_body)

chat_id = update.message.chat.id
text = update.message.text

chat = Chat(chat_id, text)
chat.process()

except Exception as e:
traceback.print_exc()

In the main.py file let's put this:

import falcon

class MainResource(object):
def on_get(self, req, resp, **params):
resp.body = u'hi, i\'m a bot'
resp.status = falcon.HTTP_200
resp.content_type = 'text/html'

And finally in the set-webhook.py file let's paste these lines:

import falcon
from ..settings import WEBHOOK_URL, bot

class SetWebhookResource(object):
def __init__(self):
self.bot = bot

def on_get(self, req, resp, **params):
s = self.bot.setWebhook(WEBHOOK_URL)
if s:
resp.body = 'ok'
resp.status = falcon.HTTP_200
else:
resp.body = 'an error occured'
resp.status = falcon.HTTP_500

Great! Our classes and resources components are ready. Now we should create a file in app folder named main.py, that will import all the resources we created earlier.

import falcon
from resources import HookResource, SetWebhookResource, MainResource

api = falcon.API()
api.add_route('/', MainResource())
api.add_route('/HOOK', HookResource())
api.add_route('/set_webhook', SetWebhookResource())

Our bot is almost ready. Now we need to create a new app in Dokkur.

Create a new app in Dokkur

  1. Open website, go to Personal apps (left menu bar)
  2. Click ⨁ button to open New App interface
  3. Enter the app’s name (Caution! Use latin lowercase and numbers, e.g. myapp007), choose available and convenient instances for hosting, pick Custom App template and press Create App button.

Congrats! Your app has easily been created. All you need now is to deploy it. But we'll do in a bit later

Update WebHook URL

We've created a new app in Dokkur, so now we have a Dokkur URL to paste it instead of your_dokkur_url in the settings.py file.

Go to Dokkur Web, choose your app in Personal Apps list, go to Domains section, copy url and paste it to the settings.py file.

Set up Dokkur Toolbelt

In this step you will install the Dokkur Toolbelt that gives you you access to the Dokkur Command Line Interface (CLI).

After installation you can use dokkur login command to log in with your email and password you set when creating Dokkur account.

Deploy the Telegram bot to Dokkur

To deploy the bot to Dokkur you need to create a Procfile file with this line in it:

web: gunicorn app.main:api --workers 4

Add also add a runtime.txt file and write

python-2.7.10
to determine the version of Python.

To finally push our code to Dokkur we need to create a Git repository, but this can also be done in just 3 steps :

git init
git add .
git commit -m 'Initial commit.'

Then you need to do the following.

For deployment you will use web-interface and Dokkur Toolbelt. Follow these steps:

  1. Go to Settings page, copy the app git url from the Git URL section.
  2. Switch to Dokkur Toolbelt and execute this command:

    git remote add dokkur git_url
    Instead of git_url paste your app's git url.

  3. Push your app:
    git push dokkur master
    If you want to deploy another branch, run:
    git push dokkur yourbranch:master

Hell yeah! Your app is deployed! Open yourappname.dokkurapp.com in your browser.

If you have started to celebrate the success with the banana milkshake, then stop it! Don’t be in a hurry. We need to test the bot in Telegram.

Go to Telegram and your chat with BotFather. There you will find a link to your bot in Telegram. Open and play with it.

It should look like this.

Telegram Bot

Congrats! Now you can drink your banana milkshake!

Thank you for your attention. If you still have some questions, feel free to contact me at eugene@dokkur.com.