LINE BOTとFirebase Functions with TypeScript

Node.js

TypeScript

Firebase

基本のコード

index.ts
import * as line from "@line/bot-sdk"; import * as functions from "firebase-functions"; // 環境変数の設定 const config = { channelAccessToken: "", channelSecret: "" }; const client = new line.Client(config); export const lineWebhook = functions .region("asia-northeast1") .https.onRequest(async (req, res) => { // LINE BOTからのアクセスかどうか確認 const signature = req.get("x-line-signature"); if ( !signature || !line.validateSignature(req.rawBody, config.channelSecret, signature) ) { throw new line.SignatureValidationFailed( "signature validation failed", signature ); } // eventをeventHander関数へ渡す Promise.all(req.body.events.map(eventHandler)) .then((result) => res.json(result)) .catch((err) => console.error(err)); }); // この関数に処理を実装 const eventHandler = async (event: line.WebhookEvent) => {}

コンテンツの取得

ユーザーがBOTに送信した画像などを受け取る関数を実装します。

index.ts
// message idを指定してbufferを取得 const getContentBuffer = (messageId: string): Promise<Buffer> => { return new Promise((resolve, reject) => { client.getMessageContent(messageId).then((stream) => { const content: Buffer[] = []; stream .on("data", (chunk) => { content.push(Buffer.from(chunk)); }) .on("error", reject) .on("end", () => { resolve(Buffer.concat(content)); }); }); }); }; // 使用例 const eventHandler = async (event: line.WebhookEvent) => { // message id を渡す const buffer = await getContentBuffer(event.message.id); }

ふっけ / ハックツ

@fukke0906

目次