-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
306 lines (267 loc) · 11.9 KB
/
worker.js
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Import only the necessary functions
import { main, debug, getBlueskyAuth } from './bot.js';
import { uploadSourceTweetsFromText, getTweetCount } from './kv.js';
import { handleMastodonReply, handleBlueskyReply, generateReply, fetchPostContent, initializeKV, loadRecentPostsFromKV } from './replies.js';
// Create a global process.env if it doesn't exist
if (typeof process === 'undefined' || typeof process.env === 'undefined') {
globalThis.process = { env: {} };
}
// Helper function to setup environment variables
async function setupEnvironment(env) {
try {
debug('Setting up environment with:', 'info', {
hasPostsKV: !!env.POSTS_KV,
envKeys: Object.keys(env),
kvBindings: Object.keys(env).filter(key => key.endsWith('_KV'))
});
process.env = {
...process.env,
MASTODON_API_URL: env.MASTODON_API_URL || '',
MASTODON_ACCESS_TOKEN: env.MASTODON_ACCESS_TOKEN || '',
BLUESKY_API_URL: env.BLUESKY_API_URL || '',
BLUESKY_USERNAME: env.BLUESKY_USERNAME || '',
BLUESKY_PASSWORD: env.BLUESKY_PASSWORD || '',
MASTODON_SOURCE_ACCOUNTS: env.MASTODON_SOURCE_ACCOUNTS || '',
BLUESKY_SOURCE_ACCOUNTS: env.BLUESKY_SOURCE_ACCOUNTS || '',
EXCLUDED_WORDS: env.EXCLUDED_WORDS || '',
DEBUG_MODE: env.DEBUG_MODE || 'false',
DEBUG_LEVEL: env.DEBUG_LEVEL || 'info',
MARKOV_STATE_SIZE: env.MARKOV_STATE_SIZE || '2',
MARKOV_MIN_CHARS: env.MARKOV_MIN_CHARS || '100',
MARKOV_MAX_CHARS: env.MARKOV_MAX_CHARS || '280',
MARKOV_MAX_TRIES: env.MARKOV_MAX_TRIES || '100',
OPENAI_API_KEY: env.OPENAI_API_KEY || ''
};
// Initialize KV namespace
if (env.POSTS_KV) {
debug('Found POSTS_KV binding, attempting to initialize', 'info', {
type: typeof env.POSTS_KV,
methods: Object.keys(env.POSTS_KV)
});
// Initialize KV first
await initializeKV(env.POSTS_KV);
debug('KV initialization complete');
// Then load existing posts
debug('Loading posts from KV...');
await loadRecentPostsFromKV();
debug('Posts loaded successfully');
} else {
debug('No POSTS_KV found in env', 'warn', {
availableBindings: Object.keys(env).filter(key => key.includes('KV')),
envType: typeof env,
envIsNull: env === null,
envIsUndefined: env === undefined
});
}
debug('Environment setup complete', 'info', {
env: Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.includes('TOKEN') && !key.includes('PASSWORD'))
)
});
} catch (error) {
debug('Error during environment setup:', 'error', {
error: error.message,
stack: error.stack
});
throw error;
}
}
// Check for notifications on both platforms
async function checkNotifications(_env) {
try {
debug('Checking for notifications...');
debug('Fetching Mastodon notifications...', 'info');
// Check Mastodon notifications
const mastodonResponse = await fetch(`${process.env.MASTODON_API_URL}/api/v1/notifications?types[]=mention`, {
headers: {
'Authorization': `Bearer ${process.env.MASTODON_ACCESS_TOKEN}`
}
});
debug('Mastodon notifications response status:', 'info', {
status: mastodonResponse.status,
statusText: mastodonResponse.statusText
});
if (!mastodonResponse.ok) {
debug('Failed to fetch Mastodon notifications', 'error', {
status: mastodonResponse.status,
statusText: mastodonResponse.statusText
});
return;
}
const mastodonNotifications = await mastodonResponse.json();
debug('Retrieved Mastodon notifications', 'info', {
totalCount: mastodonNotifications.length,
firstNotification: mastodonNotifications[0]
});
// Process each Mastodon notification
for (const notification of mastodonNotifications) {
debug('Processing Mastodon notification', 'info', {
type: notification.type,
id: notification.id,
status: notification.status?.content
});
if (notification.type === 'mention') {
await handleMastodonReply(notification);
}
}
// Check Bluesky notifications if configured
if (process.env.BLUESKY_USERNAME && process.env.BLUESKY_PASSWORD) {
debug('Fetching Bluesky notifications...', 'info');
// Get Bluesky auth
const auth = await getBlueskyAuth();
if (!auth || !auth.accessJwt) {
debug('Failed to authenticate with Bluesky - missing access token', 'error');
return;
}
// Fetch notifications using the ATP API
const notificationsResponse = await fetch(`${process.env.BLUESKY_API_URL}/xrpc/app.bsky.notification.listNotifications`, {
headers: {
'Authorization': `Bearer ${auth.accessJwt}`,
'Accept': 'application/json'
}
});
if (!notificationsResponse.ok) {
debug('Failed to fetch Bluesky notifications', 'error', {
status: notificationsResponse.status,
statusText: notificationsResponse.statusText
});
return;
}
const blueskyData = await notificationsResponse.json();
const notifications = blueskyData.notifications || [];
debug('Retrieved Bluesky notifications', 'info', {
totalCount: notifications.length,
firstNotification: notifications[0]
});
// Process each Bluesky notification
for (const notification of notifications) {
debug('Processing Bluesky notification', 'info', {
reason: notification.reason,
author: notification.author?.handle,
cid: notification.cid
});
if (notification.reason === 'reply') {
await handleBlueskyReply(notification);
}
}
// Mark notifications as read
if (notifications.length > 0) {
const seenAt = new Date().toISOString();
await fetch(`${process.env.BLUESKY_API_URL}/xrpc/app.bsky.notification.updateSeen`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${auth.accessJwt}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ seenAt })
});
}
}
} catch (error) {
debug('Error checking notifications:', 'error', error);
}
}
export default {
// Handle HTTP requests
async fetch(request, env) {
try {
// Initialize environment first
await setupEnvironment(env);
debug('Starting HTTP request handler...');
const url = new URL(request.url);
// Handle source tweets operations
if (url.pathname === '/upload-tweets') {
if (request.method === 'POST') {
const text = await request.text();
const append = request.headers.get('X-Append') !== 'false'; // Default to append
const success = await uploadSourceTweetsFromText(env, text, append);
const totalTweets = await getTweetCount(env);
return new Response(JSON.stringify({
success,
totalTweets,
mode: append ? 'append' : 'replace'
}), {
headers: { 'Content-Type': 'application/json' }
});
} else if (request.method === 'GET') {
const count = await getTweetCount(env);
return new Response(JSON.stringify({ count }), {
headers: { 'Content-Type': 'application/json' }
});
}
return new Response('Method not allowed', { status: 405 });
}
// Test reply generation
if (url.pathname === '/test-reply') {
if (request.method === 'POST') {
const { postUrl, replyContent } = await request.json();
if (!postUrl || !replyContent) {
return new Response('Missing postUrl or replyContent in request body', {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
debug('Testing reply generation...', 'info', { postUrl, replyContent });
// Fetch the original post content
const originalPost = await fetchPostContent(postUrl);
if (!originalPost) {
return new Response('Failed to fetch post content', {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
const generatedReply = await generateReply(originalPost, replyContent);
return new Response(JSON.stringify({
postUrl,
originalPost,
replyContent,
generatedReply
}), {
headers: { 'Content-Type': 'application/json' }
});
}
return new Response('Method not allowed', { status: 405 });
}
// Handle bot execution
if (url.pathname === '/run') {
if (request.method === 'POST') {
debug('Starting bot execution...');
await main(env);
debug('Bot execution completed');
return new Response('Bot execution completed', { status: 200 });
}
return new Response('Method not allowed', { status: 405 });
}
// Handle checking notifications
if (url.pathname === '/check-replies') {
if (request.method === 'POST') {
debug('Checking for replies...');
await checkNotifications(env);
return new Response('Notifications checked', { status: 200 });
}
return new Response('Method not allowed', { status: 405 });
}
return new Response('Not found', { status: 404 });
} catch (error) {
debug('Worker error:', 'error', error);
return new Response('Internal Server Error', { status: 500 });
}
},
// Handle scheduled events
async scheduled(event, env, ctx) {
try {
// Initialize environment first
await setupEnvironment(env);
debug('Starting scheduled execution...');
// Run the main bot
await ctx.waitUntil(main(env));
debug('Main execution completed');
// Check for and handle replies
await ctx.waitUntil(checkNotifications(env));
debug('Notification check completed');
debug('Scheduled execution completed');
} catch (error) {
debug('Scheduled execution error:', 'error', error);
}
}
};