2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Linebotを作る(Step2: cloudflareで作成)

2
Posted at

はじめに

cloudflareでLinebotを作ってみる

技術スタック

  • Cloudflare Workers
  • TypeScript
  • Biome.js (リンター/フォーマッター)
  • LINE Messaging API

プロジェクトのセットアップ

1. プロジェクトの初期化

# プロジェクトの作成
npm create cloudflare@latest
# 依存関係のインストール
npm install

2. 必要なパッケージのインストール

npm install @line/bot-sdk
npm install --save-dev @biomejs/biome

アーキテクチャ設計

プロジェクトは以下のような構造で実装しています:

src/
├── line/           # LINE API関連
│   ├── client.ts   # LINE APIクライアント
│   └── types.ts    # 型定義
├── handlers/       # イベントハンドラー
│   └── messageHandler.ts
└── index.ts       # エントリーポイント

主要なコード

LINE APIクライアント (src/line/client.ts)

export class LineClient {
  private config: LineApiConfig;

  constructor(config: LineApiConfig) {
    this.config = config;
  }

  async replyMessage(replyToken: string, text: string): Promise<Response> {
    return fetch('https://api.line.me/v2/bot/message/reply', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.config.channelAccessToken}`,
      },
      body: JSON.stringify({
        replyToken: replyToken,
        messages: [{
          type: 'text',
          text: text,
        }],
      }),
    });
  }
}

メッセージハンドラー (src/handlers/messageHandler.ts)

export class MessageHandler {
  private lineClient: LineClient;

  constructor(lineClient: LineClient) {
    this.lineClient = lineClient;
  }

  async handleMessage(event: LineEvent): Promise<void> {
    if (
      event.type === "message" &&
      event.message?.type === "text" &&
      event.replyToken &&
      event.message.text
    ) {
      await this.handleTextMessage(event.replyToken, event.message.text);
    }
  }

  private async handleTextMessage(
    replyToken: string,
    text: string,
  ): Promise<void> {
    await this.lineClient.replyMessage(replyToken, text);
  }
}

デプロイ方法

  1. Cloudflareのアカウントを作成
  2. Workersのプロジェクトを作成
  3. 環境変数の設定:
    • LINE_CHANNEL_SECRET
    • LINE_CHANNEL_ACCESS_TOKEN
  4. デプロイコマンド:
    npm run deploy
    

LINE Developersでの設定

  1. LINE Developersコンソールでチャネルを作成
  2. Webhook URLを設定:
    https://your-worker-name.workers.dev
    
  3. Webhook送信を有効化

開発環境の整備

Biome.jsの設定

{
  "$schema": "https://biomejs.dev/schemas/1.5.3/schema.json",
  "formatter": {
    "enabled": true,
    "indentStyle": "tab",
    "indentWidth": 2,
    "lineWidth": 80
  }
}

開発時の環境変数 (.dev.vars)

LINE_CHANNEL_SECRET=your_channel_secret
LINE_CHANNEL_ACCESS_TOKEN=your_channel_access_token

まとめ

Cloudflare Workersでのエッジコンピューティングを活用することで、以下のメリットを得られました:

  1. 高速なレスポンス

    • 日本国内のユーザーに対して50ms以下の応答時間を実現
    • LINEプラットフォームの1秒ルール(タイムアウト)を余裕で満たす
    • コールドスタートの問題がほぼ発生しない
  2. 運用の簡素化

    • サーバーの管理が不要
    • 自動スケーリング
    • デプロイが簡単(npm run deployのみ)
  3. コスト効率

    • リクエスト数に応じた従量課金
    • 無料枠が十分(1日あたり100,000リクエストまで)
    • サーバー維持費が不要
  4. グローバル対応

    • 世界中のエッジロケーションで自動実行
    • 地理的な冗長性
    • DDoS保護が標準装備

また、TypeScriptとBiome.jsを採用することで:

  • 型安全性による堅牢なコード
  • 一貫したコードスタイル
  • 開発体験の向上
    を実現できました。

今後の展望

  1. メッセージタイプの拡張

    • 画像対応
    • 位置情報対応
    • テンプレートメッセージ対応
  2. 機能の追加

    • ユーザー情報の取得
    • リッチメニューの実装
    • Flex Messageの活用
  3. 運用面の強化

    • モニタリングの追加
    • エラーハンドリングの強化
    • テストカバレッジの向上

参考リンク

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?