How To Create A Telegram Bot, The Low-Code Way (2023)

Telegram was the 6th most downloaded app in 2022 with 310 million downloads, according to Forbes. With Telegram bots, you can leverage the app's popularity to channel users to your own products and services or bring more life to your online communities: Telegram bots can send automated messages, engage with users via commands, and provide information or services to group members. They can be created by anyone and integrated with any platform―as long as you know how!

In the following article, we'll use Rowy as a low-code backend platform to create a Telegram bot. We'll cover the basics of Telegram bots, how to create a Telegram bot, and how to deploy your bot without having to deal with servers.

Why Telegram Bots?

Telegram is a popular platform, but it also offers incredible opportunities for makers:

  • To automate tasks - Telegram bots can perform programmable tasks with a simple command line interface. You can connect to any service or platform via API.
  • To increase community engagement - Bots can send Telegram polls, quizzes or games, or quickstart discussions to energize communities. Combined with tools like OpenAI and knowledge databases, they can talk to customers without needing someone always available.
  • To reach more people - Telegram bots can easily scale to hundreds of users. Telegram is available on many devices, so you can use Telegram bots wherever you are.

Last but not least, as you read on, you'll notice creating a Telegram bot is much easier than developing one on Slack or Discord in terms of installation steps.

5 Steps To Create A Telegram Bot

1. Register Your Bot On Telegram

A Telegram bot is simply a software program that receives Telegram events as HTTP requests and sends requests back to the Telegram Bot API. To do that, we first need to register the bot with Telegram to get an API token.

To create a new Telegram bot, use the search bar to find the BotFather bot―the Telegram bot that takes care of managing bots (meta, I know)―and send it the command /newbot:

the botfather Telegram bot - 0.jpg

After picking a name and a username for your bot, the BotFather gives you an API token. This token is used to authenticate your bot and is required for all API requests.

creating a Telegram bot - 1.jpg

In this example, we'll call our bot RowyAI, and it'll be a useful bot that transfers incoming messages to OpenAI's GPT-3 and sends the output back to the sender.

2. Receive Telegram Messages

First, we need to receive Telegram messages. We'll use Rowy - a lowcode backend platform where you can create instant webhooks URL and store the incoming data on a table UI. Create an account if you do not have one already here.

On Rowy, create a table and add two columns - one to store the incoming message, and another to store the corresponding telegramChatId to remember where to send the answer:

telegram table on Rowy - 2.jpg

Then, we simply create a Rowy webhook by clicking the webhook icon in the top right corner of the table and Add Webhook -> Basic. You can already notice Rowy automatically generates a webhook URL we can tell Telegram to send events to:

creating a webhook on Rowy - 3.jpg

We just need to add the code logic in the webhook's settings to store the incoming message. Telegram's API documentation tells us that the message is stored in the body of the request:

adding webhook logic on Rowy - 4.jpg

Let's go through the webhook's code:

const basicParser: Parser = async({req, db, ref, logging}) => {
  const { message } = req.body;
  return {
    message: message.text,
    telegramChatId: message.chat.id
  }
}

The webhook function comes with several parameters, but we're only interested in the incoming request parameter, req. We take apart the message object and return the new row to be stored in our Rowy table. Now, every time we receive a new message, the webhook will store it in our table.

Before it works, we must tell Telegram our webhook is ready by sending a POST request to the setWebhook endpoint of the Telegram API. We can use a simple curl command to do that:

curl -X POST "https://api.telegram.org/bot<API_TOKEN>/setWebhook?url=<WEBHOOK_URL>"

Then, send a message to your bot on Telegram:

sending a message to the Telegram bot - 5.jpg

And you'll see the message stored in your Rowy table:

the message stored in the Rowy table - 6.jpg

We can receive and store messages, but what about sending a response? Let's use OpenAI's GPT-3 to generate an answer.

3. Send Telegram Messages

We create a third response column as a derivative column to run code. A derivative column derives its values from other columns. In this case, it'll get triggered whenever we receive a new message. The derivative column will query a response from GPT-3, send it back to the Telegram user, and store the result in the corresponding row in Rowy.

First, we need to transfer the incoming message to GPT-3:

const response = await fetch("https://api.openai.com/v1/completions", {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${rowy.secrets.OPENAI_API_KEY}`
    },
    body: JSON.stringify({
        model: "text-davinci-003",
        prompt: row.message,
        temperature: 0.7,
        max_tokens: 256,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
    }),
}).then(res => res.json())

We will store the output in the table. To send the message, we need to call the sendMessage endpoint of the Telegram API:

await fetch(`https://api.telegram.org/bot${rowy.secrets.TELEGRAM_API_TOKEN}/sendMessage`, {
    method: 'POST',
    body: JSON.stringify({
        chat_id: row.telegramChatId,
        text: response.choices[0].text
    }),
})

And the final derivative code will look like this:

const derivative:Derivative = async ({ row })=>{
    const response = await fetch("https://api.openai.com/v1/completions", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${rowy.secrets.OPENAI_API_KEY}}`
        },
        body: JSON.stringify({
            model: "text-davinci-003",
            prompt: row.message,
            temperature: 0.7,
            max_tokens: 256,
            top_p: 1,
            frequency_penalty: 0,
            presence_penalty: 0
        }),
    }).then(res => res.json())

  const answer = response.choices[0].text

  await fetch(`https://api.telegram.org/bot${rowy.secrets.TELEGRAM_API_TOKEN}/sendMessage`, {
        method: 'POST',
        body: JSON.stringify({
            chat_id: row.telegramChatId,
            text: answer
        }),
    })

  return answer
}

The bot will now answer your wildest questions:

the Telegram bot answering questions - 7.jpg

4. Deploy Your Bot To Production

Now that we have a working bot, we can deploy it to production. Rowy will automatically deploy your bot to a web server and make it available 24/7 without you having to do anything. You can use share your bot's Telegram URL with others and they'll be able to interact with it.

Join Us On Discord

As you can see, it's very easy to create a Telegram bot with Rowy. You can use Rowy to create any kind of bot, from a simple chatbot to a complex AI-powered bot. Telegram bots are much simpler to create than Discord or Slack bots in terms of installation steps, so they are great to quickly automate tasks in a conversational way.

If you have any question about using Rowy for your use cases, join our community on Discord!

Get started with Rowy in minutes

Continue reading

Browse all