Very simple chat bot for Telegram for the little ones



    There are 100,500 ways and tools to create a simple serverless chat bot for telegrams. And our all the same will be easier, at least by the number of clicks in the interface. The bot itself will be written in Python, and will be executed on the serverless Swifty engine.

    As always in our guides, you will not need any special knowledge of python or other programming languages. You only need the ability to run something on the command line. If you are in Russia, then there is also a VPN on your computer, since you will need to reach the telegrams server.

    While everything is standard - register the bot


    To create a new bot, you need to ask another bot to do it. Open a telegram and find the @BotFather bot there or open the link . Next, type / newbot and follow the instructions of BotPapa. For the minimum configuration, you only need to give the bot a display name and username. After creating the bot, you will be given access token and URL. Save them somewhere.

    Bot


    First you need to register with Swifty, our server-based platform. You can do it here . Then go to the control panel and do the following:

    1. Click Functions -> New Function. Go to the From repo tab (Templates) and select the github.com/swiftycloud/swifty.demo repository , if it is not selected by default. This is our own repository in which we store function templates.
    2. Select the Simple Telegram Chatbot (python) template and click Next.
    3. Enter the name of your bot, for example, swifty_bot (hereinafter I will use this name to designate it) and click Create.

    In order for the telegram to call the bot function, you need to create an API link for it. Click the Triggers tab, click Add Trigger -> REST API (URL). Save the resulting link.

    Then, you need to give the bot function access to the access token that you received from the telegram. In Swifty there is a special entity - Account, which allows you to safely store any data, for example, login-password or tokens.

    1. Choose Accounts -> Create Account. Use the Telegram API type, the SWIFTYBOT name (in uppercase) and the token that you received from the telegram.
    2. Select Functions -> swifty_bot -> Access -> Add. Select Accounts and SWIFTYBOT account. Your function now has secure access to your access token.

    Update. Note! The SWIFTYBOT name for the account is written in the function code here:

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

    If you want to use a different account name, then you need to change it in the function code. For example, if your account name is MYOWNBOT, then your code will look like this:

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

    How is the variable name ACC_TELEGRAMMYOWNBOT_TOKEN formed, through which the function gets the account property, exactly like any other resource in Swifty? Here:

    • ACC - the identifier that you want to access a resource of type Account;
    • TELEGRAM - account type;
    • MYOWNBOT - account name;
    • TOKEN - account property;

    The code of the resulting function:

    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

    This is the simplest bot that can respond to the / start, / help and / about commands. You can also add any of your commands and expand its functionality as desired.

    We connect the function to the bot


    Now you need to tell the telegram which link is your bot. You need to open a command prompt and execute the following command in it. In this case, YOUR_API_URL must be replaced with the API link that you copied earlier, and YOUR_ACCESS_TOKEN with the token.

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


    If everything went well, then you will see something like the following:

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

    If you are in Russia, then everything will go well only if you have VPN enabled.

    You can check


    Find a bot in your telegram with your name and try to execute a couple of commands, for example, / start or / about. If everything works, congratulations. If not - complain here in the comments or in our slack channel .

    How this ready-made bot works can be viewed if we find it in the telegram of our bot named swifty_test_bot. Thank.

    Make your ideas come app, as they say in swifty.cloud .

    Also popular now: