How to use webhook
Telegram Bot API support two ways of getting updates: long-polling and webhook. GramIO works well with both.
Here is an example of using webhooks
Supported frameworks
Example
ts
import { Bot, webhookHandler } from "gramio";
import Fastify from "fastify";
const bot = new Bot(process.env.BOT_TOKEN as string);
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",
},
});
Use webhook only in production
Instead of use a tunnels, you can just use polling in development environment!
ts
const bot = new Bot(process.env.BOT_TOKEN);
await bot.start({
webhook:
process.env.NODE_ENV === "production"
? {
url: `${process.env.API_URL}/${process.env.BOT_TOKEN}`,
}
: undefined,
});
Local development with webhook
For local development with webhook, we recommend using unjs/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.BOT_TOKEN as string).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.updates.handleUpdate(req.body);
});
app.listen(80);