2
2
3
3
This agent replies ` gm `
4
4
5
- > Try XMTP using [ xmtp.chat] ( https://xmtp.chat )
5
+ > Try XMTP using [ xmtp.chat] ( https://xmtp.chat ) and sending a message to ` gm.xmtp.eth `
6
6
7
7
![ ] ( /media/gm.png )
8
8
9
- ## Basic usage
9
+ ## Overview
10
10
11
11
``` tsx
12
- import { ContentTypeText } from " @xmtp/content-type-text" ;
13
12
import { Client , type XmtpEnv } from " @xmtp/node-sdk" ;
14
13
import { createSigner , getEncryptionKeyFromHex } from " @/helpers" ;
15
14
@@ -23,44 +22,44 @@ if (!ENCRYPTION_KEY) {
23
22
throw new Error (" ENCRYPTION_KEY must be set" );
24
23
}
25
24
25
+ /* Create the signer using viem and parse the encryption key for the local db */
26
26
const signer = createSigner (WALLET_KEY );
27
27
const encryptionKey = getEncryptionKeyFromHex (ENCRYPTION_KEY );
28
28
29
+ /* Set the environment to dev or production */
29
30
const env: XmtpEnv = " dev" ;
30
31
31
32
async function main() {
32
33
console .log (` Creating client on the '${env }' network... ` );
34
+ /* Initialize the xmtp client */
33
35
const client = await Client .create (signer , encryptionKey , { env });
34
36
35
37
console .log (" Syncing conversations..." );
38
+ /* Sync the conversations from the network to update the local db */
36
39
await client .conversations .sync ();
37
40
38
41
console .log (
39
42
` Agent initialized on ${client .accountAddress }\n Send a message on http://xmtp.chat/dm/${client .accountAddress }?env=${env } ` ,
40
43
);
41
44
42
45
console .log (" Waiting for messages..." );
46
+ /* Stream all messages from the network */
43
47
const stream = client .conversations .streamAllMessages ();
44
48
45
49
for await (const message of await stream ) {
50
+ /* Ignore messages from the same agent or non-text messages */
46
51
if (
47
- ! message ||
48
- ! message .contentType ||
49
- ! ContentTypeText .sameAs (message .contentType )
52
+ message ?.senderInboxId .toLowerCase () === client .inboxId .toLowerCase () ||
53
+ message ?.contentType ?.typeId !== " text"
50
54
) {
51
- console .log (" Invalid message, skipping" , message );
52
- continue ;
53
- }
54
-
55
- // Ignore own messages
56
- if (message .senderInboxId === client .inboxId ) {
57
55
continue ;
58
56
}
59
57
60
58
console .log (
61
59
` Received message: ${message .content as string } by ${message .senderInboxId } ` ,
62
60
);
63
61
62
+ /* Get the conversation by id */
64
63
const conversation = client .conversations .getConversationById (
65
64
message .conversationId ,
66
65
);
@@ -71,6 +70,7 @@ async function main() {
71
70
}
72
71
73
72
console .log (` Sending "gm" response... ` );
73
+ /* Send a message to the conversation */
74
74
await conversation .send (" gm" );
75
75
76
76
console .log (" Waiting for messages..." );
0 commit comments