Start ChatOps with Telegram Chatbot

Jeongsoo Park
BotHub.Studio
Published in
3 min readAug 2, 2017

I’m going to build a ChatOps which manages DigitalOcean Droplets using DigitalOcean API. We’ll utilize a property feature of BotHub.Studio and Telegram keyboard. Extend it yourself to fit your own needs.

We will use python as a language and Telegram as a messenger platform and use a BotHub.Studio for host and run the code.

If you have no experience to build any chatbot before, I recommend reading Build a Telegram Chatbot with Python first.

Preparation

Digital Ocean

We need to generate an access token of Digital Ocean account. Login to DigitalOcean, go to API menu and click Generate New Token. Keep the access token to use later.

Telegram

Find @BotFather in telegram search box. Or you can meet him with https://t.me/BotFather link.

Create a new bot by telling him /newbot command. Keep the access token he gave you to use later.

BotHub.Studio

Create an account on BotHub.Studio which is a chatbot hosting service, and install CLI tool using the command below:

$ pip install bothub-cli

Run configure to connect to the service:

$ bothub configure

Create a project directory:

$ mkdir DigitalOceanBot
$ cd DigitalOceanBot
$ bothub init

A template code will be generated after init finished:

|-- bothub
| |-- bot.py
| `-- __init__.py
|-- bothub.yml
|-- requirements.txt
`-- tests

Connect a Telegram channel to the project:

$ bothub channel add telegram --api-key=<api-key>

The template project is an echo bot so you can check it works without any modification. Test whether your chatbot works by deploying it:

$ bothub deploy

Make it works with DigitalOcean

Create a bothub/doapi.py in the project directory and write a class below:

You can create, get a list, delete a droplet with DigitalOcean API. For convenience, I limited options to name, region, image, and size will only be 512mb.

Connect to Chatbot

Define Image, Region

Store some information for droplet creation to property.

$ bothub property set image ["14-04-x64","16-04-2-x64","16-10-x64","17-04-x64"]
$ bothub property set region ["nyc1","nyc3","sfo1","sfo2","sgp1"]

Register DigitalOcean access token

Telegram chatbot conversation starts with /start message. We’ll ask to input access token when we get the message. Open bothub/bot.py and write Bot.handle_message method.

‘Create Droplet’ and ‘List all Droplets’ menu will show on Telegram keyboard when the access token is confirmed.

Creating Droplet

Now we’ll create a droplet. (I omitted some part of the previous code for clear understanding. Attach below code to it.)

Retrieve Droplet List / Delete a Droplet

Add below to get Droplet list.

You can get the complete code on Github repository. And you can find a working chatbot with the code above on Telegram with username @Digital_Ocean_Bot, or https://t.me/Digital_Ocean_Bot.

References

--

--