Skip to content

Webhook

Supported frameworks

Example

ts
import { Bot } from "gramio";
import Fastify from "fastify";

const bot = new Bot(process.env.TOKEN!);
const fastify = Fastify();

fastify.post("/telegram-webhook", webhookHandler(bot, "fastify"));

fastify.listen({ port: 3445, host: "::" });

bot.on("message", (context) => {
    return context.send("Fastify!");
});

bot.start({
    webhook: {
        url: "https://example.com:3445/telegram-webhook",
    },
});

Local development with webhook

For local development with webhook, we recommend using untun Logounjs/untun.

Untun is a tool for tunnel your local HTTP(s) server to the world!

IMPORTANT

Examples of starting with a specific framework are omitted. See this example.

via API

This method allows you to set a link to our tunnel directly in the script.

Install package:

bash
npm install untun
bash
yarn add untun
bash
pnpm install untun
bash
bun install untun

Start tunnel and set webhook:

ts
import { startTunnel } from "untun";

const tunnel = await startTunnel({ port: 3000 });

bot.start({
    webhook: {
        url: await tunnel.getURL(),
    },
});

via CLI

We are listening to port 3000 locally. Therefore, we open the tunnel like this:

bash
npx untun@latest tunnel http://localhost:3000
bash
yarn dlx untun@latest tunnel http://localhost:3000
bash
pnpm dlx untun@latest tunnel http://localhost:3000
bash
bunx untun@latest tunnel http://localhost:3000
bash
 Starting cloudflared tunnel to http://localhost:3000
 Waiting for tunnel URL...
 Tunnel ready at https://unjs-is-awesome.trycloudflare.com

Now we use this link when installing the webhook:

ts
bot.start({
    webhook: {
        url: "https://unjs-is-awesome.trycloudflare.com",
    },
});

Write you own updates handler

ts
// a non-existing framework for the example
import { App } from "some-http-framework";
import { Bot } from "gramio";

const bot = new Bot(process.env.TOKEN!).on("message", (context) =>
    context.send("Hello!")
);

// init is required. It is used for lazy-load plugins, and also receives information about the bot.
await bot.init();

const app = new App().post("/telegram", async (req) => {
    // req.body must be json equivalent to TelegramUpdate
    await bot.handleUpdate(req.body);
});

app.listen(80);