telegram-bot-grammy

Telegram Bot development skill using grammY framework, TypeScript, Drizzle ORM, Vitest testing, Biome linting, deployed to Cloudflare Workers with D1 database. Use cases: (1) Creating new Telegram Bot projects (2) Adding commands or features to existing Bots (3) Configuring Cloudflare Workers deployment (4) Setting up Drizzle + D1 database integration (5) Writing Bot test cases (6) Configuring Git hooks and GitHub Actions CI/CD

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "telegram-bot-grammy" with this command: npx skills add pbnicad/telegram-bot-grammy-skill/pbnicad-telegram-bot-grammy-skill-telegram-bot-grammy

Telegram Bot Development Skill (grammY + Cloudflare Workers)

Tech Stack

ComponentTechnology
FrameworkgrammY
LanguageTypeScript
RuntimeCloudflare Workers
ORMDrizzle ORM
DatabaseCloudflare D1 (SQLite)
TestingVitest
LintingBiome
Package Managerpnpm
Git HooksHusky + lint-staged
CI/CDGitHub Actions (multi-environment)

Environment Configuration

BranchEnvironmentWorker NameDatabase
devdevelopmentmy-telegram-bot-devtelegram-bot-db-dev
mainproductionmy-telegram-bottelegram-bot-db

Project Initialization

1. Create Project

pnpm create cloudflare@latest my-telegram-bot
# Select: "Hello World" Worker, TypeScript: Yes, Git: Yes, Deploy: No

cd my-telegram-bot

2. Install Dependencies

# Core dependencies
pnpm add grammy drizzle-orm

# Dev dependencies
pnpm add -D drizzle-kit vitest @vitest/coverage-v8 @biomejs/biome husky lint-staged

3. Create Drizzle Config (drizzle.config.ts)

import { defineConfig } from "drizzle-kit";

export default defineConfig({
  schema: "./src/db/schema.ts",
  out: "./migrations",
  dialect: "sqlite",
});

4. Define Database Schema (src/db/schema.ts)

import { relations, sql } from "drizzle-orm";
import { integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";

export const users = sqliteTable(
  "users",
  {
    id: integer("id").primaryKey({ autoIncrement: true }),
    telegramId: text("telegram_id").notNull(),
    username: text("username"),
    firstName: text("first_name"),
    createdAt: text("created_at").notNull().default(sql`CURRENT_TIMESTAMP`),
    updatedAt: text("updated_at").notNull().default(sql`CURRENT_TIMESTAMP`),
  },
  (table) => [uniqueIndex("users_telegram_id_unique").on(table.telegramId)]
);

export const settings = sqliteTable(
  "settings",
  {
    id: integer("id").primaryKey({ autoIncrement: true }),
    userId: integer("user_id")
      .notNull()
      .references(() => users.id, { onDelete: "cascade" }),
    key: text("key").notNull(),
    value: text("value"),
  },
  (table) => [uniqueIndex("settings_user_id_key_unique").on(table.userId, table.key)]
);

export const usersRelations = relations(users, ({ many }) => ({
  settings: many(settings),
}));

5. Configure wrangler.toml (Multi-Environment)

name = "my-telegram-bot"
main = "src/index.ts"
compatibility_date = "2024-01-01"
compatibility_flags = ["nodejs_compat"]

[env.dev]
name = "my-telegram-bot-dev"

[env.dev.vars]
BOT_INFO = """{ "id": 123456789, "is_bot": true, "first_name": "MyBotDev", "username": "my_bot_dev" }"""

[[env.dev.d1_databases]]
binding = "DB"
database_name = "telegram-bot-db-dev"
database_id = "<DEV_DATABASE_ID>"

[env.production]
name = "my-telegram-bot"

[env.production.vars]
BOT_INFO = """{ "id": 987654321, "is_bot": true, "first_name": "MyBot", "username": "my_bot" }"""

[[env.production.d1_databases]]
binding = "DB"
database_name = "telegram-bot-db"
database_id = "<PRODUCTION_DATABASE_ID>"

6. Create D1 Databases

# Create development database
pnpm exec wrangler d1 create telegram-bot-db-dev

# Create production database
pnpm exec wrangler d1 create telegram-bot-db

# Copy database_id to wrangler.toml

7. Database Migrations

# Create migration file
pnpm exec wrangler d1 migrations create telegram-bot-db-dev init

# Generate SQL files from Drizzle schema
pnpm exec drizzle-kit generate

# Apply to development
pnpm exec wrangler d1 migrations apply telegram-bot-db-dev --local
pnpm exec wrangler d1 migrations apply telegram-bot-db-dev --remote

# Apply to production
pnpm exec wrangler d1 migrations apply telegram-bot-db --remote

8. Configure Git Hooks

pnpm exec husky init

.husky/pre-commit:

pnpm exec lint-staged
pnpm test

Code Structure

Entry File (src/index.ts)

import { drizzle } from "drizzle-orm/d1";
import { sql } from "drizzle-orm";
import { Bot, webhookCallback } from "grammy";
import { users } from "./db/schema";

export interface Env {
  BOT_TOKEN: string;
  BOT_INFO: string;
  DB: D1Database;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const db = drizzle(env.DB);

    const bot = new Bot(env.BOT_TOKEN, {
      botInfo: JSON.parse(env.BOT_INFO),
    });

    bot.command("start", async (ctx) => {
      const user = ctx.from;
      if (user) {
        await db
          .insert(users)
          .values({
            telegramId: String(user.id),
            username: user.username ?? null,
            firstName: user.first_name ?? null,
          })
          .onConflictDoUpdate({
            target: users.telegramId,
            set: {
              username: user.username ?? null,
              firstName: user.first_name ?? null,
              updatedAt: sql`CURRENT_TIMESTAMP`,
            },
          });
      }
      await ctx.reply("Welcome to the Bot!");
    });

    return webhookCallback(bot, "cloudflare-mod")(request);
  },
};

GitHub Actions CI/CD

Workflow Overview

BranchTriggerTarget Environment
devpushdevelopment (my-telegram-bot-dev)
mainpushproduction (my-telegram-bot)
PR-Tests only, no deployment

.github/workflows/ci.yml

name: CI/CD

on:
  push:
    branches: [main, dev]
  pull_request:
    branches: [main, dev]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - run: pnpm run lint
      - run: pnpm run test

  deploy-dev:
    needs: test
    if: github.ref == 'refs/heads/dev' && github.event_name == 'push'
    environment: development
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
      - run: pnpm install --frozen-lockfile
      - uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          environment: dev

  deploy-production:
    needs: test
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    environment: production
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
      - run: pnpm install --frozen-lockfile
      - uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          environment: production

GitHub Configuration

Secrets (Settings -> Secrets and variables -> Actions):

  • CLOUDFLARE_API_TOKEN: Cloudflare API Token

Environments (Settings -> Environments):

  • development: Optional protection rules
  • production: Recommend configuring Required reviewers

Deployment

Manual Deployment

# Deploy to development
pnpm exec wrangler deploy --env dev

# Deploy to production
pnpm exec wrangler deploy --env production

Set Secrets

# Development
pnpm exec wrangler secret put BOT_TOKEN --env dev

# Production
pnpm exec wrangler secret put BOT_TOKEN --env production

Set Webhook

# Development
curl "https://api.telegram.org/bot<DEV_TOKEN>/setWebhook?url=https://my-telegram-bot-dev.<subdomain>.workers.dev/"

# Production
curl "https://api.telegram.org/bot<PROD_TOKEN>/setWebhook?url=https://my-telegram-bot.<subdomain>.workers.dev/"

References

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Coding

openclaw-version-monitor

监控 OpenClaw GitHub 版本更新,获取最新版本发布说明,翻译成中文, 并推送到 Telegram 和 Feishu。用于:(1) 定时检查版本更新 (2) 推送版本更新通知 (3) 生成中文版发布说明

Archived SourceRecently Updated
Coding

ask-claude

Delegate a task to Claude Code CLI and immediately report the result back in chat. Supports persistent sessions with full context memory. Safe execution: no data exfiltration, no external calls, file operations confined to workspace. Use when the user asks to run Claude, delegate a coding task, continue a previous Claude session, or any task benefiting from Claude Code's tools (file editing, code analysis, bash, etc.).

Archived SourceRecently Updated
Coding

ai-dating

This skill enables dating and matchmaking workflows. Use it when a user asks to make friends, find a partner, run matchmaking, or provide dating preferences/profile updates. The skill should execute `dating-cli` commands to complete profile setup, task creation/update, match checking, contact reveal, and review.

Archived SourceRecently Updated
Coding

clawhub-rate-limited-publisher

Queue and publish local skills to ClawHub with a strict 5-per-hour cap using the local clawhub CLI and host scheduler.

Archived SourceRecently Updated