-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxapi.ts
More file actions
287 lines (244 loc) · 8.18 KB
/
xapi.ts
File metadata and controls
287 lines (244 loc) · 8.18 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/**
* X (Twitter) API Client Service
* Handles all interactions with the X API for fetching mentions, posts, and posting replies
*/
import { XPost, XThread, Mention, XAPIConfig } from '../types/index.js';
export class XAPIClient {
private config: XAPIConfig;
private lastMentionId: string | null = null;
private simulationMode: boolean = false;
constructor(config: XAPIConfig) {
this.config = config;
this.simulationMode = !config.bearerToken;
if (this.simulationMode) {
console.log('⚠️ Running in simulation mode - X API calls will be mocked');
}
}
/**
* Fetch recent mentions of the authenticated user
*/
async fetchMentions(username: string): Promise<Mention[]> {
if (this.simulationMode) {
return this.simulateFetchMentions(username);
}
try {
// In a real implementation, this would call X API v2
// GET /2/users/:id/mentions
const response = await this.makeXAPIRequest(
`https://api.twitter.com/2/users/by/username/${username}`,
'GET'
);
if (!response || !response.data) {
console.warn('Invalid response from X API (user lookup)');
return [];
}
const userId = response.data.id;
if (!userId) {
throw new Error('Failed to get user ID from response');
}
const params = new URLSearchParams({
max_results: '10',
expansions: 'author_id',
'tweet.fields': 'created_at,conversation_id,in_reply_to_user_id,referenced_tweets',
});
if (this.lastMentionId) {
params.set('since_id', this.lastMentionId);
}
const mentionsUrl = `https://api.twitter.com/2/users/${userId}/mentions?${params.toString()}`;
const mentionsResponse = await this.makeXAPIRequest(mentionsUrl, 'GET');
if (!mentionsResponse || !Array.isArray(mentionsResponse.data)) {
console.warn('Invalid response from X API (mentions)');
return [];
}
const mentions = this.parseMentions(mentionsResponse.data);
// Track the newest mention ID for pagination on the next poll
if (mentionsResponse.data.length > 0) {
this.lastMentionId = mentionsResponse.data[0].id;
}
return mentions;
} catch (error) {
console.error('Error fetching mentions:', error);
return [];
}
}
/**
* Fetch a complete thread/conversation
*/
async fetchThread(conversationId: string): Promise<XThread | null> {
if (this.simulationMode) {
return this.simulateFetchThread(conversationId);
}
try {
// In a real implementation, this would use X API v2 search
// to get all tweets in a conversation
const response = await this.makeXAPIRequest(
`https://api.twitter.com/2/tweets/search/recent?query=conversation_id:${conversationId}&max_results=100&tweet.fields=created_at,author_id,conversation_id,referenced_tweets`,
'GET'
);
if (!response || !response.data) {
console.warn('Invalid response from X API (thread)');
return null;
}
if (!Array.isArray(response.data)) {
console.warn('Unexpected response shape from X API (thread): data is not an array');
return null;
}
return this.parseThread(response.data);
} catch (error) {
console.error('Error fetching thread:', error);
return null;
}
}
/**
* Post a reply to a tweet
*/
async postReply(inReplyToTweetId: string, text: string): Promise<boolean> {
if (this.simulationMode) {
return this.simulatePostReply(inReplyToTweetId, text);
}
try {
// In a real implementation, this would call X API v2
// POST /2/tweets
const response = await this.makeXAPIRequest(
'https://api.twitter.com/2/tweets',
'POST',
{
text,
reply: {
in_reply_to_tweet_id: inReplyToTweetId,
},
}
);
return !!response.data?.id;
} catch (error) {
console.error('Error posting reply:', error);
return false;
}
}
/**
* Search for tweets
*/
async searchTweets(query: string): Promise<XPost[]> {
if (this.simulationMode) {
return this.simulateSearchTweets(query);
}
try {
const response = await this.makeXAPIRequest(
`https://api.twitter.com/2/tweets/search/recent?query=${encodeURIComponent(query)}&max_results=10&tweet.fields=created_at,author_id,conversation_id`,
'GET'
);
return (response.data || []).map((tweet: any) => this.parsePost(tweet));
} catch (error) {
console.error('Error searching tweets:', error);
return [];
}
}
// Private helper methods
private async makeXAPIRequest(url: string, method: string, body?: any): Promise<any> {
const headers: Record<string, string> = {
'Authorization': `Bearer ${this.config.bearerToken}`,
'Content-Type': 'application/json',
};
const options: RequestInit = {
method,
headers,
};
if (body) {
options.body = JSON.stringify(body);
}
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`X API error: ${response.status} ${response.statusText}`);
}
return response.json();
}
private parseMentions(tweets: any[]): Mention[] {
return tweets.map((tweet) => ({
post: this.parsePost(tweet),
mentioned_at: new Date(tweet.created_at),
processed: false,
}));
}
private parsePost(tweet: any): XPost {
return {
id: tweet.id,
text: tweet.text,
author_id: tweet.author_id,
author_username: tweet.username || 'unknown',
created_at: tweet.created_at,
conversation_id: tweet.conversation_id,
in_reply_to_user_id: tweet.in_reply_to_user_id,
referenced_tweets: tweet.referenced_tweets,
};
}
private parseThread(tweets: { created_at: string; [key: string]: unknown }[]): XThread | null {
if (tweets.length === 0) return null;
const sorted = [...tweets].sort((a, b) =>
new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
);
return {
root_post: this.parsePost(sorted[0]),
replies: sorted.slice(1).map((t) => this.parsePost(t)),
};
}
// Simulation methods for testing without real API credentials
private simulateFetchMentions(username: string): Mention[] {
const simulatedMentions: Mention[] = [
{
post: {
id: 'sim_123456789',
text: `@${username} Can you analyze this market trend and give me insights?`,
author_id: 'sim_user_001',
author_username: 'test_user',
created_at: new Date().toISOString(),
conversation_id: 'sim_conv_001',
},
mentioned_at: new Date(),
processed: false,
},
];
console.log(`📨 Simulated: Found ${simulatedMentions.length} mention(s)`);
return simulatedMentions;
}
private simulateFetchThread(conversationId: string): XThread {
const thread: XThread = {
root_post: {
id: 'sim_root_123',
text: 'This is the root post of the conversation',
author_id: 'sim_user_001',
author_username: 'test_user',
created_at: new Date(Date.now() - 60000).toISOString(),
conversation_id: conversationId,
},
replies: [
{
id: 'sim_reply_456',
text: 'This is a reply in the thread',
author_id: 'sim_user_002',
author_username: 'another_user',
created_at: new Date().toISOString(),
conversation_id: conversationId,
},
],
};
console.log(`🧵 Simulated: Fetched thread with ${thread.replies.length + 1} posts`);
return thread;
}
private simulatePostReply(inReplyToTweetId: string, text: string): boolean {
console.log(`📤 Simulated: Would post reply to ${inReplyToTweetId}:`);
console.log(` "${text}"`);
return true;
}
private simulateSearchTweets(query: string): XPost[] {
console.log(`🔍 Simulated: Searched for "${query}"`);
return [
{
id: 'sim_search_001',
text: `Sample tweet matching query: ${query}`,
author_id: 'sim_user_003',
author_username: 'search_result_user',
created_at: new Date().toISOString(),
},
];
}
}