forked from xmtplabs/xmtp-agent-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
67 lines (53 loc) · 2.04 KB
/
Copy pathindex.ts
File metadata and controls
67 lines (53 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { Agent, getTestUrl } from "@xmtp/agent-sdk";
import { loadEnvFile } from "../../utils/general";
loadEnvFile();
const messageQueue: string[] = [];
console.log("Starting XMTP Dual Client Agent...");
// Receiving client - listens for messages
const receivingClient = await Agent.createFromEnv({
env: process.env.XMTP_ENV as "local" | "dev" | "production",
dbPath: (inboxId) =>
process.env.RAILWAY_VOLUME_MOUNT_PATH ??
"." + `/${process.env.XMTP_ENV}-${inboxId.slice(0, 8)}-receiving.db3`,
});
receivingClient.on("text", async (ctx) => {
const message = ctx.message.content;
const sender = await ctx.getSenderAddress();
console.log(`📨 Received: "${message}" from ${sender}`);
messageQueue.push(message);
});
receivingClient.on("start", () => {
console.log(`Agent started. Waiting for messages...`);
console.log(`Address: ${receivingClient.address}`);
console.log(`🔗${getTestUrl(receivingClient.client)}`);
});
// Sending client - processes the queue
const sendingClient = await Agent.createFromEnv({
env: process.env.XMTP_ENV as "local" | "dev" | "production",
dbPath: (inboxId) =>
process.env.RAILWAY_VOLUME_MOUNT_PATH ??
"." + `/${process.env.XMTP_ENV}-${inboxId.slice(0, 8)}-sending.db3`,
});
// Process queue every 2 seconds
setInterval(async () => {
if (messageQueue.length === 0) return;
const message = messageQueue.shift();
if (!message) return;
try {
// Get all conversations and send to the most recent one
await sendingClient.client.conversations.sync();
const conversations = await sendingClient.client.conversations.list();
if (conversations.length > 0) {
const latestConv = conversations[0];
await latestConv.sendText(
"Sending client: " + message + " at " + new Date().toISOString(),
);
console.log(`📤 Sent: "${message}"`);
}
} catch (error) {
console.error(`❌ Error sending message:`, error);
}
}, 2000);
// Start both clients
await Promise.all([receivingClient.start(), sendingClient.start()]);
console.log("✅ Both clients running!");