telegram-bot-grammy について
grammY と TypeScript で Cloudflare Workers 上の Telegram ボットを開発するためのスキルです。プロジェクト設定、D1 のデータ管理、テスト、開発・本番環境へのデプロイを扱います。
主な機能
- 01grammY と TypeScript のプロジェクト設定
- 02Cloudflare Workers のランタイム設定
- 03Drizzle ORM と Cloudflare D1
- 04Vitest によるテストと Biome による検査
- 05GitHub Actions による複数環境へのデプロイ
活用シーン
- 01Telegram ボットプロジェクトの開始
- 02Cloudflare D1 でのボットデータ管理
- 03デプロイ前の変更のテスト
- 04開発環境と本番環境への個別デプロイ
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ pbnicad/ telegram-bot-grammy-skill --skill telegram-bot-grammyインストール後、Claude Code で/telegram-bot-grammyを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
README.md.gitignoreassets/biome.jsonpre-commitvitest.config.tspackage.jsondrizzle.config.tstsconfig.jsonwrangler.tomlassets/.github/workflows/ci.ymlassets/migrations/0001_init.sqlassets/src/index.tsassets/src/db/schema.tsassets/test/bot.test.ts詳細
Telegram ボット開発スキル(grammY + Cloudflare Workers)
技術スタック
| コンポーネント | 技術 |
|---|---|
| フレームワーク | grammY |
| 言語 | TypeScript |
| ランタイム | Cloudflare Workers |
| ORM | Drizzle ORM |
| データベース | Cloudflare D1 (SQLite) |
| テスト | Vitest |
| リンティング | Biome |
| パッケージマネージャー | pnpm |
| Git フック | Husky + lint-staged |
| CI/CD | GitHub Actions(複数環境) |
環境設定
| ブランチ | 環境 | Worker 名 | データベース |
|---|---|---|---|
dev | 開発 | my-telegram-bot-dev | telegram-bot-db-dev |
main | 本番 | my-telegram-bot | telegram-bot-db |
プロジェクトの初期化
1. プロジェクトを作成する
pnpm create cloudflare@latest my-telegram-bot
# Select: "Hello World" Worker, TypeScript: Yes, Git: Yes, Deploy: No
cd my-telegram-bot
2. 依存関係をインストールする
# Core dependencies
pnpm add grammy drizzle-orm
# Dev dependencies
pnpm add -D drizzle-kit vitest @vitest/coverage-v8 @biomejs/biome husky lint-staged
3. Drizzle 設定を作成する(drizzle.config.ts)
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "./src/db/schema.ts",
out: "./migrations",
dialect: "sqlite",
});
4. データベーススキーマを定義する(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. wrangler.toml を設定する(複数環境)
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. D1 データベースを作成する
# 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. データベースのマイグレーション
# 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. Git フックを設定する
pnpm exec husky init
.husky/pre-commit:
pnpm exec lint-staged
pnpm test
コード構成
エントリーファイル(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
ワークフローの概要
| ブランチ | トリガー | 対象環境 |
|---|---|---|
dev | プッシュ | 開発(my-telegram-bot-dev) |
main | プッシュ | 本番(my-telegram-bot) |
| PR | - | テストのみ、デプロイなし |
.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 の設定
シークレット(Settings -> Secrets and variables -> Actions):
CLOUDFLARE_API_TOKEN: Cloudflare API トークン
環境(Settings -> Environments):
development: 保護ルールは任意production: 必須レビュアーの設定を推奨
デプロイ
手動デプロイ
# Deploy to development
pnpm exec wrangler deploy --env dev
# Deploy to production
pnpm exec wrangler deploy --env production
シークレットを設定する
# Development
pnpm exec wrangler secret put BOT_TOKEN --env dev
# Production
pnpm exec wrangler secret put BOT_TOKEN --env production
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/"
参考資料
コメント
Markdown 対応