-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfarcaster.js
More file actions
175 lines (150 loc) · 5.37 KB
/
farcaster.js
File metadata and controls
175 lines (150 loc) · 5.37 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import WebSocket from 'ws';
import fetch from 'node-fetch';
import { v4 as uuidv4 } from 'uuid';
const API_BASE_URL = 'https://client.warpcast.com/v2';
const WS_URL = 'wss://ws.warpcast.com/stream';
export const formatMessage = (message) => {
if (message.serverTimestamp < 1739924345884) {
return false;
}
//console.log(message);
const name = message.senderContext?.displayName ||
message.senderContext?.username ||
'Unknown';
return {
role: `user`,
content: `${name}: ${message.message}`
};
};
class Farcaster {
constructor(agentFID, token) {
this.agentFID = agentFID;
this.token = token;
}
async #makeApiCall(endpoint, method, body) {
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
method,
headers: {
'authorization': `Bearer ${this.token}`,
'content-type': 'application/json; charset=utf-8'
},
body: JSON.stringify(body)
});
return await response.json();
} catch (error) {
console.error(`Error making API call to ${endpoint}:`, error);
throw error;
}
}
async createDirectCastGroup(name, participantFids = []) {
return this.#makeApiCall('/direct-cast-group', 'PUT', {
participantFids,
name
});
}
async addGroupMembers(conversationId, targetFids) {
return this.#makeApiCall('/direct-cast-group-membership', 'POST', {
conversationId,
targetFids,
action: 'add'
});
}
async promoteGroupMember(conversationId, targetFid) {
return this.#makeApiCall('/direct-cast-group-membership', 'POST', {
conversationId,
targetFid,
action: 'promote'
});
}
async removeGroupMember(conversationId, targetFid) {
return this.#makeApiCall('/direct-cast-group-membership', 'POST', {
conversationId,
targetFid,
action: 'remove'
});
}
async sendMessage(conversationId, recipientFids, message ) {
return this.#makeApiCall('/direct-cast-send', 'PUT', {
conversationId: conversationId,
message,
type: "text",
recipientFids,
messageId: uuidv4()
});
}
async sendCast(text, embeds = []) {
return this.#makeApiCall('/casts', 'POST', {
text,
embeds
});
}
connectToWarpcastStream() {
return new Promise((resolve, reject) => {
const ws = new WebSocket(WS_URL);
ws.on('open', () => {
console.log('Connected to Warpcast WebSocket stream');
// Send authentication message
const authMessage = {
messageType: "authenticate",
data: `Bearer ${this.token}`
};
ws.send(JSON.stringify(authMessage));
resolve(ws);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
reject(error);
});
ws.on('close', () => {
console.log('Disconnected from Warpcast WebSocket stream');
});
});
}
async getMessages(conversationId, cursor = null, allMessages = []) {
try {
let endpoint = `/direct-cast-conversation-messages?conversationId=${conversationId}&limit=50`;
if (cursor) {
endpoint += `&cursor=${cursor}`;
}
const response = await this.#makeApiCall(endpoint, 'GET');
const messages = response.result.messages.map(message => formatMessage(message)).filter(Boolean);
allMessages.push(...messages);
// If there's a next cursor, recursively fetch more messages
if (response.next && response.next.cursor) {
return this.getMessages(conversationId, response.next.cursor, allMessages);
}
return allMessages.reverse();
} catch (error) {
console.error('Error fetching messages:', error);
throw error;
}
}
async matchUsers(groupName, userFids, message) {
try {
// Create a new direct cast group
const groupResponse = await this.createDirectCastGroup(groupName, userFids);
const conversationId = groupResponse.result.conversationId;
// Promote the first member to admin
if (userFids.length > 0) {
await this.promoteGroupMember(conversationId, userFids[0]);
}
// Send a message to the group
await this.sendMessage(conversationId, userFids, message);
// Leave the group by removing self
await this.removeGroupMember(conversationId, this.agentFID);
return {
success: true,
conversationId,
message: 'Successfully created group, promoted member, sent message, and left group'
};
} catch (error) {
console.error('Error in matchUsers:', error);
return {
success: false,
error: error.message
};
}
}
}
export default Farcaster;