Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using waitUntil API instead of using Queues #1

Merged
merged 3 commits into from
May 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
English teacher LINE bot, who chats with us, provides an English writing topic and corrects our writing.

## Requirement
- Cloudflare's Workers Paid Plan to use Queues
- Cloudflare Workers Account
- LINE Developers Account

## How to Setup
### Prepare LINE Messaging API (WIP)
Expand All @@ -27,11 +28,6 @@ D1
- Change database_id in wrangler.toml
- Apply schema.sql: `npm exec -- wrangler d1 execute english-line-bot-db --file=./schema.sql`

Queues
```
npm exec -- wrangler queues create english-line-bot-queue
```

### Deploy
```
npm run deploy
Expand Down
53 changes: 19 additions & 34 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
import { TextEventMessage, WebhookEvent } from "@line/bot-sdk";
import { Env, Hono } from "hono";
import { Hono } from "hono";
import { Line } from "./line";
import { OpenAI } from "./openai";
import { Conversation } from "./tables";

type QueueBody = {
text: string;
replyToken: string;
};

type Bindings = {
DB: D1Database;
QUEUE: Queue<QueueBody>;
CHANNEL_ACCESS_TOKEN: string;
OPENAI_API_KEY: string;
};
Expand Down Expand Up @@ -40,7 +34,8 @@ app.post("/api/webhook", async (c) => {
const { replyToken } = event;
const { text } = event.message as TextEventMessage;

await c.env.QUEUE.send({ text, replyToken });
c.executionCtx.waitUntil(replyGeneratedMessage(c.env, text, replyToken));

return c.json({ message: "ok" });
});

Expand All @@ -50,6 +45,21 @@ app.post("/api/generate_message", async (c) => {
return c.json({ message: generatedMessage });
});

async function replyGeneratedMessage(env: Bindings, text: string, replyToken: string) {
try {
const generatedMessage = await generateMessageAndSaveHistory(text, env);
console.log(generatedMessage);

// Reply to the user
const lineClient = new Line(env.CHANNEL_ACCESS_TOKEN);
await lineClient.replyMessage(generatedMessage, replyToken);
} catch (err: unknown) {
if (err instanceof Error) console.error(err);
const lineClient = new Line(env.CHANNEL_ACCESS_TOKEN);
await lineClient.replyMessage("I am not feeling well right now.", replyToken);
}
}

async function generateMessageAndSaveHistory(text: string, env: Bindings) {
// Fetch 2 conversation from D1
const { results } = await env.DB.prepare(`select * from conversations order by id desc limit 15`).all<Conversation>();
Expand All @@ -68,29 +78,4 @@ async function generateMessageAndSaveHistory(text: string, env: Bindings) {
return generatedMessage;
}

async function handleQueue(message: Message<QueueBody>, env: Bindings) {
const { text, replyToken } = message.body;

try {
const generatedMessage = await generateMessageAndSaveHistory(text, env);

// Reply to the user
const lineClient = new Line(env.CHANNEL_ACCESS_TOKEN);
await lineClient.replyMessage(generatedMessage, replyToken);
} catch (err: unknown) {
if (err instanceof Error) console.error(err);
const lineClient = new Line(env.CHANNEL_ACCESS_TOKEN);
await lineClient.replyMessage("I am not feeling well right now.", replyToken);
}
}

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
return app.fetch(request, env, ctx);
},
async queue(batch: MessageBatch<QueueBody>, env: Bindings): Promise<void> {
for (const message of batch.messages) {
await handleQueue(message, env);
}
},
};
export default app;
11 changes: 1 addition & 10 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,4 @@ name = "english-line-bot"
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_id = "7dda7ad4-9d52-4ed3-90a6-5e649a7ff500"
database_name = "english-line-bot-db"

[[queues.producers]]
binding = "QUEUE"
queue = "english-line-bot-queue"

[[queues.consumers]]
max_batch_size = 1
max_batch_timeout = 30
queue = "english-line-bot-queue"
database_name = "english-line-bot-db"
Loading