はじめに
CloudflareでLinebotを作成します。Linebotで作成する際におうむ返しのbotを作っていきます。
実装コード
プロジェクト作成
npm create cloudflare@latest
#:schema node_modules/wrangler/config-schema.json
name = "line-bot"
main = "src/index.ts"
compatibility_date = "2024-07-29"
[vars]
LINE_ACCESS_TOKEN = "XXXXXXXXXXXXX"
LINE_CHANNEL_SECRET = "XXXXXXX"
index.ts
import { Hono } from "hono";
interface Env {
LINE_ACCESS_TOKEN: string;
LINE_CHANNEL_SECRET: string;
}
const app = new Hono<{ Bindings: Env }>();
app.post("/callback", async (c) => {
const body = await c.req.json();
const events = body.events;
const lineAccessToken = c.env.LINE_ACCESS_TOKEN;
for (const event of events) {
if (event.type === "message" && event.message.type === "text") {
const replyToken = event.replyToken;
const messageText = event.message.text;
const replyMessage = {
replyToken: replyToken,
messages: [
{
type: "text",
text: messageText,
},
],
};
await fetch("https://api.line.me/v2/bot/message/reply", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${lineAccessToken}`,
},
body: JSON.stringify(replyMessage),
});
}
}
return c.text("ok");
});
export default app;
ローカル環境で確認する
ngrokを使うと便利なので、ngrokでトンネリングし対応していきます。
ngrok http port番号
→この状態でlinebotを動かすとうまく動くはずです
あとはデプロイし、サーバでの確認をするだけです!