grammY Telegram bot tested offline with handleUpdate and an API transformer: working versions (tested 2026-10-15)
Unit test a grammY bot with commands, sessions, inline keyboards and callback queries by feeding updates to bot.handleUpdate and capturing Bot API calls with an API transformer, no network.
passed4 passed · 0 failed2026-10-15 20:08 UTC- Status
- passed
- Last passed
- 2026-10-15 20:08 UTC
- Tests
- 4 / 4
- Language
- TypeScript
- Runtime
- node v22.23.3
pinned versions3
grammy@1.46.0@types/node@26.6.5tsx@4.23.15
run it
npm install --no-audit --no-fund --ignore-scripts=false npm test
test environment
node v22.23.3 linux 6.17.0-1022-azure x64 runner: github-actions 38799498972
The code
Exactly the files that passed. Your agent can pull them with get_recipe("grammy-bot-handle-update") (install), or see them on GitHub.
package.json
{
"name": "grammy-bot-handle-update",
"private": true,
"type": "module",
"scripts": {
"test": "node --import tsx --test test/*.test.ts"
},
"dependencies": {
"grammy": "1.46.0"
},
"devDependencies": {
"@types/node": "26.6.5",
"tsx": "4.23.15"
}
}
src/bot.ts
import { Bot, Context, session, type SessionFlavor } from "grammy";
type SessionData = { count: number };
export type MyContext = Context & SessionFlavor<SessionData>;
export function makeBot(token: string) {
// botInfo up front means no getMe network call at init.
const bot = new Bot<MyContext>(token, {
botInfo: {
id: 42, is_bot: true, first_name: "AIA Bot", username: "aia_test_bot",
can_join_groups: true, can_read_all_group_messages: false, supports_inline_queries: false,
can_connect_to_business: false, has_main_web_app: false,
},
});
bot.use(session({ initial: (): SessionData => ({ count: 0 }) }));
bot.command("start", (ctx) => ctx.reply(`Welcome, ${ctx.from?.first_name}!`));
bot.command("count", (ctx) => {
ctx.session.count++;
return ctx.reply(`Count: ${ctx.session.count}`);
});
bot.callbackQuery("enroll", async (ctx) => {
await ctx.answerCallbackQuery({ text: "Enrolled" });
await ctx.editMessageText("You're in for Nov 1st");
});
bot.on("message:text", (ctx) =>
ctx.reply("Pick one", { reply_markup: { inline_keyboard: [[{ text: "Enroll", callback_data: "enroll" }]] } }),
);
bot.catch((err) => { throw err.error; });
return bot;
}
test/bot.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import type { Update } from "grammy/types";
import { makeBot } from "../src/bot.ts";
type Call = { method: string; payload: Record<string, unknown> };
/** Intercept every Bot API call with an API transformer, so nothing hits api.telegram.org. */
function harness() {
const bot = makeBot("123:TEST");
const calls: Call[] = [];
bot.api.config.use(async (_prev, method, payload) => {
calls.push({ method, payload: payload as Record<string, unknown> });
const result = method === "sendMessage" ? { message_id: calls.length, date: 0, chat: { id: 1, type: "private" }, text: (payload as { text: string }).text } : true;
return { ok: true, result } as never;
});
return { bot, calls };
}
let uid = 0;
const chat = { id: 1001, type: "private" as const, first_name: "JP" };
const from = { id: 1001, is_bot: false, first_name: "JP" };
const msg = (text: string): Update => {
const isCmd = text.startsWith("/");
return {
update_id: ++uid,
message: {
message_id: uid, date: 1760000000, chat, from, text,
...(isCmd ? { entities: [{ type: "bot_command", offset: 0, length: text.split(" ")[0].length }] } : {}),
},
} as Update;
};
test("/start replies with name", async () => {
const { bot, calls } = harness();
await bot.handleUpdate(msg("/start"));
assert.deepEqual(calls.map((c) => [c.method, c.payload.chat_id, c.payload.text]), [["sendMessage", 1001, "Welcome, JP!"]]);
});
test("session state persists across updates", async () => {
const { bot, calls } = harness();
await bot.handleUpdate(msg("/count"));
await bot.handleUpdate(msg("/count"));
assert.deepEqual(calls.map((c) => c.payload.text), ["Count: 1", "Count: 2"]);
});
test("plain text gets an inline keyboard", async () => {
const { bot, calls } = harness();
await bot.handleUpdate(msg("hello"));
assert.deepEqual(calls[0].payload.reply_markup, { inline_keyboard: [[{ text: "Enroll", callback_data: "enroll" }]] });
});
test("callback query answers and edits", async () => {
const { bot, calls } = harness();
await bot.handleUpdate({
update_id: ++uid,
callback_query: { id: "cb1", from, chat_instance: "ci", data: "enroll", message: { message_id: 9, date: 0, chat, text: "Pick one" } },
} as Update);
assert.deepEqual(calls.map((c) => c.method), ["answerCallbackQuery", "editMessageText"]);
assert.equal(calls[0].payload.text, "Enrolled");
assert.equal(calls[1].payload.message_id, 9);
assert.equal(calls[1].payload.text, "You're in for Nov 1st");
});
Connect to ProvenPin
Add the free MCP server so your agent can pull this recipe and others like it. Same setup as the docs.
terminal
claude mcp add --transport http provenpin https://mcp.provenpin.com/mcp
~/.cursor/mcp.json
{ "mcpServers": { "provenpin": { "url": "https://mcp.provenpin.com/mcp" } } }.vscode/mcp.json
{ "servers": { "provenpin": { "type": "http", "url": "https://mcp.provenpin.com/mcp" } } }~/.codeium/windsurf/mcp_config.json
{ "mcpServers": { "provenpin": { "serverUrl": "https://mcp.provenpin.com/mcp" } } }MCP settings
{ "mcpServers": { "provenpin": { "type": "streamableHttp", "url": "https://mcp.provenpin.com/mcp" } } }Any other MCP client: Streamable HTTP at https://mcp.provenpin.com/mcp. No API key, no signup.