Build a Telegram Chatbot in Python

Nowadays there are many articles like ‘build a chatbot without any code’. But somebody still feels comfortable with codes. I’ll tell you here about to build a chatbot rapidly with BotHub.Studio.

Creating a Telegram Bot

Search @BotFather in telegram search box. Or use https://t.me/BotFather directly.

I’m the BotFather

Create a new bot by telling him /newbot command.

username should not be duplicated. Give it a creative and unique name. Keep the access token BotFather gave you to use later.

Connect to Chatbot

First, 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 next:

$ bothub configure

Create a project directory:

$ mkdir MyBot
$ cd MyBot
$ bothub init

A template code will be generated after init finished:

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

Primary template code, specifically bot.py contains an echo bot code which mimics a user message.

Now we use the telegram access token BotFather gave:

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

And deploy the project to server:

$ bothub deploy

Send a message to your chatbot and see it works well.

You can find your chatbot by searching @username in telegram search box or html link to https://t.me/<username>.