Serverless Telegram bot on Swifty

Vladimir Porokhov

Introduction

In this article, I’ll show you how to create simple Telegram bot on webhooks written in Python 3 and deploy it to Swifty. To create such bot we need only little Python knowledge, Telegram account and… Swifty!

Register your bot

First of all you need to register your bot on Telegram. To create new bot you need to contact with another bot called @BotFather. Install Telegram, open this link https://telegram.me/BotFather and start the conversation. Type /newbot to start creating your bot.

/newbot

After that you need to answer a few questions: provide bot display name and username. Once your bot is created, you will be provided with the access token and URL. Save both – we will need them for our function.

Create bot function

We are going to use our own Swifty.Cloud for this guide. Register and go to Swifty.Dashboard and create your bot function:

  1. Click Functions > New Function. Switch to From repo (Templates) tab and select default repository https://github.com/swiftycloud/swifty.demo if it is not selected by default. You will see templates available from our public repository on GitHub.
  2. Please select Simple Telegram Chatbot (python) function, click Next, enter the name for your function swifty_bot and click Create.
  3. Click Triggers > Add Trigger > REST API (URL). Copy the newly created URL.

Next you need to create Telegram account to store Telegram token:

  1. Click Accounts > Create account. Use the type Telegram API, name SWIFTYBOT and token that you got from Telegram.
  2. Click Functions >swifty_bot > Access > Add. Select Accounts and theSWIFTYBOT account.

Please be aware that the name SWIFTYBOT is part of the function’s code here:

BASE_URL = "https://api.telegram.org/bot{}".format(os.getenv('ACC_TELEGRAMSWIFTYBOT_TOKEN'))

ACC_TELEGRAMSWIFTYBOT_TOKEN – is the name of the environment variable we use to get access to the token. Here:

  • ACC – type of middleware;
  • TELEGRAM – type of account;
  • SWIFTYBOT – name of your account;
  • TOKEN – type of property. All characters must be in uppercase.

If you want to use name MYOWNBOT for your account, your variable should look like ACC_TELEGRAMMYOWNBOT_TOKEN.

Your function should looks like:

import json
import os
import sys
import requests

BASE_URL = "https://api.telegram.org/bot{}".format(os.getenv('ACC_TELEGRAMSWIFTYBOT_TOKEN'))

def Main(req):
    try:
        data = json.loads(req.body.encode())
        message = str(data["message"]["text"])
        chat_id = data["message"]["chat"]["id"]
        first_name = data["message"]["chat"]["first_name"]

        response = "Please /start, {}".format(first_name)

        if "start" in message:
            response = "Hello {}! Type /help to get list of actions.".format(first_name)
            
        if "help" in message:
            response = "/about - get information about Swifty"
            
        if "about" in message:
            response = ("Swifty is the serverless platform that allows startups, developers and enterprises to develop and run application backend with minimal time-to-market, costs and without infrastructure management.\n"
            			"Start creating your backend at\n"
                       	"https://swifty.cloud")

        data = {"text": response.encode("utf8"), "chat_id": chat_id}
        url = BASE_URL + "/sendMessage"
        requests.post(url, data)

    except Exception as e:
        print(e)

    return {"statusCode": 200}, None

Connect your function with the bot

Now you need to add REST API (URL) you created on previous step to your Telegram bot. You need to call telegram API to register your API URL for that.

curl -XPOST https://api.telegram.org/botYOUR_ACCESS_TOKEN/setWebhook?url=YOUR_API_URL

If you did everything correct, you will receive message like this:

{
  "ok": true,
  "result": true,
  "description": "Webhook was set"
}

That is it! Your bot is ready!

Test your bot

Go to Telegram and find your bot by name. Your bot has the following command:

/start - to start conversation
/help - to get the list of available actions
/about - to get information about Swifty

Need more? Change your swifty_test_bot function according to your needs.

Enjoy!

Share this post

Share on facebook
Share on twitter
Share on email
Share on print