1
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?

CloudflareWorkersでLinebotを作成する

Posted at

はじめに

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を動かすとうまく動くはずです

あとはデプロイし、サーバでの確認をするだけです!

1
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
1
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?