Building a Telegram Bot with Supabase Edge Functions

Building a Telegram Bot with Supabase Edge Functions

Are you ready to create your own Telegram bot powered by Supabase Edge Functions? This step-by-step guide will walk you through the process, from setting up your Supabase project to deploying your bot. By the end of this tutorial, you'll have a fully functional Telegram bot that responds to messages.

Prerequisites

Before we begin, make sure you have the following tools and accounts set up:

  1. Supabase Account: Sign up for a Supabase account and create a new project from the Supabase Dashboard.

  2. Visual Studio Code (VS Code): We'll use VS Code for code editing.

  3. Docker Desktop: Download and install Docker Desktop to create Docker images for Supabase Edge Functions.

  4. Node.js: Ensure you have Node.js installed on your machine.

Now, let's dive into creating your Telegram bot.

Setting Up Supabase

  1. Create a New Project: Log in to your Supabase account, click on your project, and navigate to "Edge functions" in the sidebar. Here, you'll find the commands needed to deploy your project later.

  2. Initialize Supabase: Open your project in VS Code and run the following commands in your project directory:

npm install supabase
npx supabase functions new telegram-bot
npx supabase init

This will set up your Supabase project and create a directory called telegram-bot for your bot.

  1. Start Supabase: Open Docker Desktop and run in VS Code:
npx supabase start

This command will automatically create Docker images for Supabase.

  1. Configure VS Code: If you see an error in index.ts, install the Deno VS Code plugin. Open the supabase.code-workspace file generated by npx supabase init and click "Open Workspace" in VS Code. Any errors should now be resolved.

Creating a Telegram Bot

  1. Create a Telegram Bot: Open the Telegram app, search for "BotFather," and start a chat with it. Type /start to initiate the conversation, and then use the /newbot command to create a new bot. You'll be prompted to provide a name and a username for your bot. Afterwards, BotFather will give you a Bot Token—make sure to save it.

  2. Create a .env File: Inside your telegram-bot directory, create a .env file and add your bot token:

BOT_TOKEN=your_token

Replace your_token with the token you received from BotFather.

  1. Install the Telegram Bot Framework: Install the grammY framework using the following command:
npm install grammy
  1. Update index.ts: Replace the existing code in your index.ts file with the following:
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { Bot, webhookCallback } from "https://deno.land/x/grammy/mod.ts";

const bot = new Bot(Deno.env.get("BOT_TOKEN"));

bot.command("start", (ctx) => ctx.reply("Welcome! Up and running."));
bot.on("message", (ctx) => ctx.reply("Got another message!"));

const handleUpdate = webhookCallback(bot, 'std/http')

serve(async (req) => {
  try {
    const url = new URL(req.url)
    if (url.searchParams.get('secret') !== Deno.env.get('FUNCTION_SECRET'))
      return new Response('not allowed', { status: 405 })

    return await handleUpdate(req)
  } catch (err) {
    console.error(err)
  }
})
  1. Run Locally: Start your bot locally with the following command:
npx supabase functions serve --no-verify-jwt --env-file ./supabase/functions/telegram-bot/.env

Make sure to use the correct path to your .env file.

  1. Set Up ngrok: Install ngrok using the following command:
npm install ngrok
  1. Run ngrok: run the following command in a separate terminal (do not close the previous one):
ngrok http 54321
  1. Configure Telegram Webhook: Take the ngrok link (e.g., https://1a6f-188-25-187-223.ngrok.io) and use it to set up your Telegram bot webhook:
https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/setWebhook?url=https://<PROJECT_REFERENCE>.functions.supabase.co/telegram-bot?secret=<FUNCTION_SECRET>

Replace <TELEGRAM_BOT_TOKEN>, <PROJECT_REFERENCE>, and <FUNCTION_SECRET> with your bot token, project reference, and a secret of your choice, respectively.

  1. Verify Webhook: Access the webhook URL to ensure it's set up correctly. You should receive a JSON response:
{
   "ok":true,
   "result":true,
   "description":"Webhook was set"
}

Deploying Your Bot

  1. Deploy to Supabase: In your Supabase project's Edge Functions section, you'll find a deploy command that looks like this:
npx supabase functions deploy telegram-bot --no-verify-jwt --project-ref **************************

Replace ************************** with your project reference. Don't forget to add --no-verify-jwt.

  1. Set Supabase Secrets: Run the following command to set your Supabase secrets:
npx supabase secrets set --env-file ./supabase/functions/telegram-bot/.env --project-ref **************************
  1. Set webhook with the project's URL: Access the webhook link with your project's URL that can be found on the project dashboard.
https://api.telegram.org/bot6481337995:AAGZMIcCOFuw1v0fMmYuDchrb36Nag7n0wQ/setWebhook?url=https://**************************.supabase.co/functions/v1/telegram-bot/?secret=telegrambot

That's it! You've successfully created a Telegram bot using Supabase Edge Functions. Your bot is now deployed and ready to interact with users. You can further customize your bot's behaviour by adding more commands and responses to the index.ts file. Enjoy building and experimenting with your new bot!