-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
3024 lines (2717 loc) · 95.6 KB
/
bot.js
File metadata and controls
3024 lines (2717 loc) · 95.6 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { Client, GatewayIntentBits } = require("discord.js");
const axios = require("axios");
const envUpdater = require("./helpers/env-updater");
const fs = require("fs");
const path = require("path");
const ffmpeg = require("fluent-ffmpeg");
const delay = require("delay");
const geminiService = require("./gemini-service");
function logToDiscord(channel, message, type = "info") {
const icons = {
info: "ℹ️",
success: "✅",
warning: "⚠️",
error: "❌",
process: "⚙️",
};
// Validate channel object
if (!channel || typeof channel.send !== "function") {
console.error(`❌ Invalid channel object passed to logToDiscord`);
console.log(`${icons[type]} ${message}`);
return Promise.resolve();
}
return channel.send(`${icons[type]} ${message}`).catch((err) => {
console.error(`Failed to send Discord message: ${err.message}`);
});
}
// Load environment variables
require("dotenv").config();
const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const CHANNEL_ID = process.env.CHANNEL_ID;
// Parse Instagram accounts from environment
const ACCOUNTS = JSON.parse(process.env.INSTAGRAM_ACCOUNTS || "[]");
const GITHUB_CONFIG = {
token: process.env.GITHUB_TOKEN,
owner: process.env.GITHUB_OWNER,
repo: process.env.GITHUB_REPO,
};
// Parse YouTube accounts from environment
const YOUTUBE_ACCOUNTS = JSON.parse(process.env.YOUTUBE_ACCOUNTS || "[]");
// Validate required environment variables
if (!DISCORD_TOKEN || !CHANNEL_ID) {
console.error(
"❌ Missing required environment variables: DISCORD_TOKEN, CHANNEL_ID",
);
process.exit(1);
}
if (ACCOUNTS.length === 0) {
console.warn("⚠️ No Instagram accounts configured");
}
if (!GITHUB_CONFIG.token || !GITHUB_CONFIG.owner || !GITHUB_CONFIG.repo) {
console.warn("⚠️ GitHub configuration incomplete - uploads will fail");
}
if (!process.env.GEMINI_API_KEY) {
console.warn("⚠️ GEMINI_API_KEY not set - AI captions will be disabled");
console.warn(" Add GEMINI_API_KEY to .env to enable AI-powered captions");
console.warn(
" Get your free API key from: https://aistudio.google.com/app/apikey",
);
}
const BASE_CAPTION =
"@idolchat.app is better than c.ai / chai\n\nNot only can you chat with your AI characters but you can collect other's characters, style them, trade them as a card game through a multiplayer experience.\n\nIdol Chat turns these characters into unique collectibles that you can earn, customize, upgrade, trade, and more!\n\n─── ⋆⋅☆⋅⋆ ──✨── ⋆⋅☆⋅⋆ ───\n\n🎬 Yoinked from: @%author% (DM for removal)\n💭 Original Caption:\n\n%originalCaption%";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const activeSessions = new Set();
const MAX_CONCURRENT_SESSIONS = 5;
const RETRY_CONFIG = {
maxRetries: 3,
baseDelay: 15000,
maxDelay: 120000,
backoffMultiplier: 2,
};
// Timing constants to avoid magic numbers
const DELAYS = {
BETWEEN_ACCOUNTS: 30000, // 30 seconds between Instagram account uploads
BETWEEN_YOUTUBE: 10000, // 10 seconds between YouTube uploads
RANDOM_MIN: 2000, // Minimum random delay
RANDOM_MAX: 5000, // Maximum random delay
RANDOM_LARGE_MIN: 5000, // Larger random delay min
RANDOM_LARGE_MAX: 8000, // Larger random delay max
COMMENT_DELAY_MIN: 5000, // Min delay before posting comment
COMMENT_DELAY_MAX: 8000, // Max delay before posting comment
RATE_LIMIT_WAIT: 60000, // 1 minute wait for rate limits
CONTAINER_CHECK: 5000, // Base delay for checking container status
CONTAINER_CHECK_RANDOM: 8000, // Random addition to container check
PUBLISH_DELAY_MIN: 5000, // Min delay before publishing
PUBLISH_DELAY_MAX: 10000, // Max delay before publishing
DOWNLOAD_RETRY: 5000, // Delay between download retries
API_RETRY: 10000, // Delay between API retries
BACKOFF_BASE: 30000, // Base backoff delay (30s)
};
// Timeout constants
const TIMEOUTS = {
AXIOS_DEFAULT: 30000, // 30 seconds
AXIOS_DOWNLOAD: 60000, // 60 seconds for video downloads
DOWNLOAD_TOTAL: 120000, // 2 minutes total download timeout
CAPTION_EXTRACTION: 20000, // 20 seconds for caption extraction
OEMBED_API: 8000, // 8 seconds for oEmbed API
ALT_API: 8000, // 8 seconds for alternative API
SCRAPING: 10000, // 10 seconds for web scraping
GITHUB_UPLOAD: 120000, // 2 minutes for GitHub upload
YOUTUBE_API: 15000, // 15 seconds for YouTube API calls
YOUTUBE_UPLOAD: 30000, // 30 seconds for YouTube upload
INSTAGRAM_API: 30000, // 30 seconds for Instagram API
INSTAGRAM_STATUS: 15000, // 15 seconds for status checks
};
// File size limits
const FILE_LIMITS = {
MIN_VIDEO_SIZE: 1024, // 1KB minimum
GITHUB_MAX_MB: 70, // 70MB for GitHub (accounting for base64 overhead)
YOUTUBE_MAX_GB: 128, // 128GB for YouTube (unverified accounts)
INSTAGRAM_CAPTION_MAX: 2200, // Instagram caption character limit
};
client.once("clientReady", async () => {
console.log(`Logged in as ${client.user.tag}`);
// Auto-refresh Instagram tokens on startup
// Note: Tokens are refreshed intelligently - if recently refreshed (<5 min ago), skips refresh
try {
await autoRefreshInstagramTokens();
} catch (error) {
console.error(`❌ Critical error during token refresh: ${error.message}`);
console.error(
"⚠️ Bot will continue, but uploads may fail if tokens are expired",
);
}
});
/**
* Auto-refresh Instagram tokens on startup
* Extends token validity by 60 days if successful
*
* @throws {Error} If critical error occurs during refresh
*/
async function autoRefreshInstagramTokens() {
// Check if tokens were recently refreshed (within last 5 minutes)
const REFRESH_COOLDOWN = 5 * 60 * 1000; // 5 minutes
const timestampFile = path.join(__dirname, ".last-token-refresh");
try {
if (fs.existsSync(timestampFile)) {
const lastRefresh = parseInt(fs.readFileSync(timestampFile, "utf8"));
const timeSinceRefresh = Date.now() - lastRefresh;
if (timeSinceRefresh < REFRESH_COOLDOWN) {
const secondsAgo = Math.floor(timeSinceRefresh / 1000);
const minutesAgo = Math.floor(secondsAgo / 60);
const displayTime =
minutesAgo > 0
? `${minutesAgo} minute(s) ago`
: `${secondsAgo} second(s) ago`;
console.log(
`⏭️ Skipping token refresh (last refreshed ${displayTime})\n`,
);
return;
}
}
} catch (error) {
// If we can't read timestamp, proceed with refresh
}
console.log("\n🔄 Auto-refreshing Instagram tokens...");
// Reload environment variables to get latest tokens
delete require.cache[require.resolve("dotenv")];
require("dotenv").config();
let accounts;
try {
const accountsStr = process.env.INSTAGRAM_ACCOUNTS || "[]";
accounts = JSON.parse(accountsStr);
if (!Array.isArray(accounts)) {
throw new Error("INSTAGRAM_ACCOUNTS must be an array");
}
} catch (error) {
console.log(`⚠️ Could not parse Instagram accounts: ${error.message}`);
console.log(" Skipping token refresh");
return;
}
if (accounts.length === 0) {
console.log("⚠️ No Instagram accounts configured, skipping refresh");
return;
}
const updatedAccounts = [];
let refreshedCount = 0;
let failedCount = 0;
const REFRESH_TIMEOUT = 20000; // 20 seconds per account
const DELAY_BETWEEN_REQUESTS = 2000; // 2 seconds between requests to avoid rate limiting
for (let i = 0; i < accounts.length; i++) {
const account = accounts[i];
const accountName = account.name || `Account ${i + 1}`;
// Add delay between requests (except for first account)
if (i > 0) {
await delay(DELAY_BETWEEN_REQUESTS);
}
// Validate account structure
if (!account || typeof account !== "object") {
console.log(`⚠️ ${accountName}: Invalid account structure, skipping`);
updatedAccounts.push(account);
failedCount++;
continue;
}
if (!account.token) {
console.log(`⚠️ ${accountName}: Missing token, skipping`);
updatedAccounts.push(account);
failedCount++;
continue;
}
if (!account.id) {
console.log(`⚠️ ${accountName}: Missing Instagram ID, skipping`);
updatedAccounts.push(account);
failedCount++;
continue;
}
try {
// Create timeout promise
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error("Request timeout")), REFRESH_TIMEOUT);
});
// Create refresh request promise
const refreshPromise = axios.get(
"https://graph.instagram.com/refresh_access_token",
{
params: {
grant_type: "ig_refresh_token",
access_token: account.token,
},
timeout: REFRESH_TIMEOUT - 1000, // Axios timeout slightly less than our timeout
},
);
// Race between timeout and actual request
const response = await Promise.race([refreshPromise, timeoutPromise]);
if (response.data && response.data.access_token) {
const newToken = response.data.access_token;
const expiresIn = response.data.expires_in;
const daysValid = Math.floor(expiresIn / 86400);
console.log(
`✅ ${accountName}: Token refreshed (valid for ${daysValid} days)`,
);
updatedAccounts.push({
name: account.name,
id: account.id,
token: newToken,
});
refreshedCount++;
} else {
console.log(
`⚠️ ${accountName}: Unexpected response format, keeping old token`,
);
updatedAccounts.push(account);
failedCount++;
}
} catch (error) {
// Extract detailed error information
let errorMsg = error.message;
let errorCode = null;
let httpStatus = null;
if (error.response) {
httpStatus = error.response.status;
errorCode = error.response.data?.error?.code;
errorMsg = error.response.data?.error?.message || error.message;
// Provide specific guidance based on error
if (httpStatus === 400 && errorCode === 190) {
errorMsg = "Token expired or invalid - needs manual regeneration";
} else if (httpStatus === 429) {
errorMsg = "Rate limit exceeded - too many refresh requests";
} else if (httpStatus === 403) {
errorMsg = "Permission denied - check app permissions";
}
}
console.log(`❌ ${accountName}: Refresh failed`);
console.log(` Error: ${errorMsg}`);
if (httpStatus) console.log(` HTTP Status: ${httpStatus}`);
if (errorCode) console.log(` Error Code: ${errorCode}`);
console.log(` → Keeping old token, but it may be expired`);
updatedAccounts.push(account);
failedCount++;
}
}
// Only update .env file if at least one token was successfully refreshed
if (refreshedCount > 0) {
try {
const result = await envUpdater.updateEnvFile(
"INSTAGRAM_ACCOUNTS",
updatedAccounts,
);
if (result.success) {
console.log(
`✅ Updated .env file with ${refreshedCount} refreshed token(s)`,
);
// Reload environment variables after update
delete require.cache[require.resolve("dotenv")];
require("dotenv").config();
// Write timestamp to prevent double-refresh
try {
const timestampFile = path.join(__dirname, ".last-token-refresh");
fs.writeFileSync(timestampFile, Date.now().toString(), "utf8");
} catch (tsError) {
// Non-critical error, just log it
}
} else {
console.log(`⚠️ Could not update .env file: ${result.error}`);
console.log(
" Tokens were refreshed but not saved - they will expire in 1 hour",
);
}
} catch (error) {
console.log(`⚠️ Error updating .env file: ${error.message}`);
console.log(
" Tokens were refreshed but not saved - they will expire in 1 hour",
);
}
} else if (failedCount === accounts.length) {
console.log("⚠️ All token refreshes failed - .env file not updated");
}
console.log(
`📊 Instagram token refresh: ${refreshedCount} succeeded, ${failedCount} failed\n`,
);
if (failedCount > 0) {
console.log(
"💡 Tip: Run 'npm run instagram-refresh' for detailed token status",
);
if (refreshedCount === 0) {
console.log("⚠️ WARNING: All tokens failed to refresh!");
console.log(" If tokens are expired, uploads will fail.");
console.log(" Generate new tokens: See SETUP_GUIDE.md\n");
}
}
}
async function retryUpload(uploadFunction, account, ...args) {
let lastError = null;
// Extract channel from args (should be the last argument)
const channel = args[args.length - 1];
for (let attempt = 1; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
try {
console.log(
`Upload attempt ${attempt}/${RETRY_CONFIG.maxRetries} for ${account.name}`,
);
const result = await uploadFunction(account, ...args);
if (attempt > 1 && channel) {
await logToDiscord(
channel,
`✅ Upload succeeded on attempt ${attempt} for ${account.name}`,
"success",
);
}
return result;
} catch (error) {
lastError = error;
console.log(
`Upload attempt ${attempt} failed for ${account.name}: ${error.message}`,
);
if (attempt < RETRY_CONFIG.maxRetries) {
const delay = Math.min(
RETRY_CONFIG.baseDelay *
Math.pow(RETRY_CONFIG.backoffMultiplier, attempt - 1),
RETRY_CONFIG.maxDelay,
);
if (channel) {
await logToDiscord(
channel,
`⚠️ Upload attempt ${attempt} failed for ${
account.name
}. Retrying in ${Math.round(delay / 1000)}s...`,
"warning",
);
}
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
}
// All retries failed
throw lastError;
}
client.on("messageCreate", async (message) => {
if (
message.channel.id !== CHANNEL_ID ||
!message.content.includes("instagram.com") ||
message.author.bot
)
return;
// Match Instagram URLs including both direct and username-based formats
const reelUrlMatch = message.content.match(
/https?:\/\/(www\.)?instagram\.com\/(?:([^\/]+)\/)?(reels?|p)\/[\w-]+[^\s]*/,
);
if (!reelUrlMatch) return;
const isRepost = message.content.toLowerCase().includes("repost");
let reelUrl = reelUrlMatch[0];
if (reelUrl.includes("/reels/")) {
reelUrl = reelUrl.replace("/reels/", "/reel/");
console.log(`🔄 Normalized URL from /reels/ to /reel/: ${reelUrl}`);
}
console.log(`🔗 Processing Instagram URL: ${reelUrl}`);
// Usage examples (supports both /reel/ and /reels/ URLs):
// Basic: https://instagram.com/reel/xyz author: username_123
// With /reels/: https://instagram.com/reels/xyz author: username_123
// With manual caption: https://instagram.com/reel/xyz author: username_123 caption: Amazing K-pop dance! #kpop #trending #viral
// Multi-line caption: https://instagram.com/reel/xyz author: username_123 caption: Amazing dance!
// #kpop #trending #viral
// Caption only: https://instagram.com/reels/xyz caption: Best K-drama scene ever! #kdrama #emotional #crying
// Repost with original caption: https://instagram.com/reel/xyz repost author: username_123
let author = "Original Creator";
const authorMatch = message.content.match(/author:?\s*([^\s,\n\r]+)/i);
if (authorMatch && authorMatch[1]) {
author = authorMatch[1].trim();
console.log(`👤 Using provided author: ${author}`);
} else {
try {
const apiResponse = await axios.get(
`https://www.instagram.com/api/v1/oembed/?url=${encodeURIComponent(
reelUrl,
)}`,
{
timeout: TIMEOUTS.OEMBED_API,
},
);
if (apiResponse.data && apiResponse.data.author_name) {
author = apiResponse.data.author_name;
console.log(`👤 Author fetched from API: ${author}`);
} else {
console.log(`ℹ️ No author found, using default: Original Creator`);
}
} catch (error) {
console.log(`⚠️ Could not fetch author, using default: ${error.message}`);
}
}
let manualCaption = "";
if (!isRepost) {
// Try to find caption after removing the URL and author parts
let textAfterUrl = message.content
.replace(/https?:\/\/[^\s]+/gi, "")
.trim();
if (author !== "Original Creator") {
textAfterUrl = textAfterUrl
.replace(
new RegExp(
`author:?\\s*${author.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
"gi",
),
"",
)
.trim();
}
const captionMatch = textAfterUrl.match(/caption:?\s*([\s\S]+)/i);
if (captionMatch && captionMatch[1]) {
manualCaption = captionMatch[1].trim();
console.log(
`📝 Manual caption provided: "${manualCaption.substring(0, 80)}${
manualCaption.length > 80 ? "..." : ""
}"`,
);
console.log(`📝 Full caption length: ${manualCaption.length} characters`);
}
} else {
console.log(`🔄 Repost mode: Will use original caption from the post`);
}
if (activeSessions.size >= MAX_CONCURRENT_SESSIONS) {
await message.reply(
`⚠️ Server is currently processing ${activeSessions.size} reels. Please wait a moment and try again.`,
);
return;
}
const sessionId = `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
activeSessions.add(sessionId);
console.log(
`Starting new session: ${sessionId} (Active: ${activeSessions.size}/${MAX_CONCURRENT_SESSIONS})`,
);
try {
const videosDir = path.join(__dirname, "videos");
if (!fs.existsSync(videosDir)) {
fs.mkdirSync(videosDir, { recursive: true });
}
const memUsage = process.memoryUsage();
const memUsageMB = Math.round(memUsage.heapUsed / 1024 / 1024);
// Reject session if memory is critically high
if (memUsage.heapUsed > 800 * 1024 * 1024) {
// 800MB threshold
activeSessions.delete(sessionId);
await message.reply(
`❌ Server memory critically high (${memUsageMB}MB). Please try again in a few minutes.`,
);
console.error(
`Session ${sessionId} rejected due to high memory: ${memUsageMB}MB`,
);
return;
} else if (memUsage.heapUsed > 500 * 1024 * 1024) {
console.warn(`⚠️ High memory usage: ${memUsageMB}MB`);
}
console.log(
`Session ${sessionId}: System checks passed (Memory: ${memUsageMB}MB)`,
);
} catch (diskError) {
activeSessions.delete(sessionId);
await message.reply(
"❌ System resources unavailable. Please try again later.",
);
return;
}
try {
let statusMsg;
async function updateStatus(title, description, fields, color = 0x3498db) {
const embed = {
title,
description,
fields,
color,
timestamp: new Date(),
};
if (!statusMsg) {
statusMsg = await message.channel.send({ embeds: [embed] });
} else {
await statusMsg.edit({ embeds: [embed] }).catch(console.error);
}
}
await updateStatus(
"🎬 Reel Processing Status",
"Starting to process your Instagram reel…",
[
{ name: "URL", value: reelUrl, inline: true },
{ name: "Author", value: author, inline: true },
{ name: "Session ID", value: sessionId, inline: true },
{ name: "Status", value: "⏳ Initializing…", inline: false },
],
);
await updateStatus(
"🎬 Reel Processing Status",
"Downloading reel from Instagram…",
[
{ name: "URL", value: reelUrl, inline: true },
{ name: "Author", value: author, inline: true },
{ name: "Status", value: "⏳ Downloading…", inline: false },
],
);
const downloadResult = await downloadReel(
reelUrl,
sessionId,
manualCaption,
isRepost,
);
const videoPath = downloadResult.videoPath;
const originalHashtags = downloadResult.originalHashtags;
const originalCaption = downloadResult.originalCaption;
await updateStatus("🎬 Reel Processing Status", "Processing video...", [
{ name: "URL", value: reelUrl, inline: true },
{ name: "Author", value: author, inline: true },
{
name: "Mode",
value: isRepost ? "🔄 Repost" : "🆕 Standard",
inline: true,
},
{
name: "Caption Source",
value: isRepost ? "Original" : manualCaption ? "Manual" : "Auto",
inline: true,
},
{
name: "Hashtags Found",
value: originalHashtags.length.toString(),
inline: true,
},
{ name: "Status", value: "⏳ Processing...", inline: false },
]);
let cleanedPath = videoPath;
let editedPath = videoPath;
let finalPath = videoPath;
try {
// Step 1: stripAllMetadata does: 1.1x speed + 2% brightness + bg music
cleanedPath = await stripAllMetadata(videoPath, sessionId);
// Step 2: Add text overlay branding (optional, controlled by env var)
const ADD_BRANDING = process.env.ADD_VIDEO_BRANDING !== "false"; // Default: true
if (ADD_BRANDING) {
try {
finalPath = await addPromoToVideo(cleanedPath, sessionId, {
text: "idolchat.app",
subtitle: "Better than c.ai",
x: 70,
y: 150,
appearAt: 0.5,
visibleFor: 5.0,
fadeInDuration: 0.3,
fadeOutDuration: 0.3,
fontSize: 64,
subtitleSize: 38,
barWidth: 8,
barColor: "red",
textColor: "white",
crf: 23,
preset: "ultrafast", // Changed from "medium" to "ultrafast" for speed
});
console.log(`✅ Branding added for session: ${sessionId}`);
} catch (brandingError) {
console.error(
`⚠️ Branding failed for session ${sessionId}: ${brandingError.message}`,
);
finalPath = cleanedPath; // Fallback to cleaned video without branding
}
} else {
console.log(`ℹ️ Branding disabled for session: ${sessionId}`);
finalPath = cleanedPath;
}
} catch (processingError) {
console.error(
`Processing error for session ${sessionId}:`,
processingError.message,
);
finalPath = videoPath; // Fallback to original video
}
await updateStatus("🎬 Reel Processing Status", "Uploading to Discord...", [
{ name: "URL", value: reelUrl, inline: true },
{ name: "Author", value: author, inline: true },
{ name: "Status", value: "⏳ Uploading...", inline: false },
]);
const githubVideoUrl = await uploadToGitHub(message.channel, finalPath);
const githubStoryUrl = githubVideoUrl; // Use same video for story
// Generate AI captions ONCE for all accounts - OPTIMIZED!
// Upload video once and reuse for both Instagram and YouTube
let aiGeneratedCaption = null;
let ytTitle = null;
let ytDescription = null;
if (!isRepost) {
let geminiVideoFile = null;
try {
// Step 1: Upload video to Gemini ONCE
await logToDiscord(
message.channel,
`📹 Uploading video to AI for analysis...`,
"info",
);
geminiVideoFile = await geminiService.uploadVideoForAnalysis(finalPath);
console.log(`✅ Video uploaded to Gemini: ${geminiVideoFile.name}`);
// Step 2: Generate Instagram caption using uploaded video
await logToDiscord(
message.channel,
`🤖 Generating Instagram caption...`,
"info",
);
aiGeneratedCaption =
await geminiService.generateInstagramCaptionWithFile(
originalCaption,
author,
originalHashtags,
geminiVideoFile,
);
console.log(
`✨ Instagram caption generated (${
aiGeneratedCaption.length
} chars): ${aiGeneratedCaption.substring(0, 100)}...`,
);
// Step 3: Generate YouTube metadata using SAME uploaded video
if (YOUTUBE_ACCOUNTS.length > 0) {
await logToDiscord(
message.channel,
`🤖 Generating YouTube metadata...`,
"info",
);
const ytMetadata =
await geminiService.generateYouTubeMetadataWithFile(
originalCaption,
author,
originalHashtags,
geminiVideoFile,
);
ytTitle = ytMetadata.title;
ytDescription = ytMetadata.description;
console.log(`✨ YouTube metadata generated:`);
console.log(` Title: ${ytTitle}`);
console.log(` Description: ${ytDescription.substring(0, 100)}...`);
}
// Step 4: Clean up uploaded video file
await geminiService.cleanupVideoFile(geminiVideoFile.name);
console.log(`🧹 Cleaned up Gemini video file`);
} catch (error) {
console.error("Failed to generate AI captions:", error);
await logToDiscord(
message.channel,
`⚠️ AI caption generation failed: ${error.message}`,
"warning",
);
await logToDiscord(
message.channel,
`Using fallback captions for all accounts`,
"info",
);
// Clean up video file if it was uploaded
if (geminiVideoFile) {
try {
await geminiService.cleanupVideoFile(geminiVideoFile.name);
} catch (cleanupError) {
console.error("Failed to cleanup video file:", cleanupError);
}
}
}
}
let completedUploads = 0;
const totalUploads = ACCOUNTS.length;
for (let i = 0; i < ACCOUNTS.length; i++) {
const account = ACCOUNTS[i];
try {
await updateStatus(
"📤 Upload Progress",
`Uploading to Instagram (${account.name})...`,
[
{ name: "Current Account", value: account.name, inline: true },
{ name: "Platform", value: "Instagram", inline: true },
{
name: "Progress",
value: `${completedUploads}/${totalUploads}`,
inline: true,
},
{ name: "Status", value: "⏳ Publishing…", inline: false },
],
0xf1c40f,
);
await retryUpload(
postToInstagram,
account,
githubVideoUrl,
githubStoryUrl,
author,
originalHashtags,
message.channel,
originalCaption,
isRepost,
3, // maxRetries
aiGeneratedCaption, // Pass the pre-generated caption
);
completedUploads++;
} catch (error) {
await logToDiscord(
message.channel,
`❌ All retry attempts failed for ${account.name}: ${error.message}`,
"error",
);
await logToDiscord(
message.channel,
`Skipping to the next account...`,
"info",
);
}
// Only delay if not the last account
if (i < ACCOUNTS.length - 1) {
await delay(DELAYS.BETWEEN_ACCOUNTS);
}
}
// Upload to YouTube accounts
let completedYouTubeUploads = 0;
const totalYouTubeUploads = YOUTUBE_ACCOUNTS.length;
// YouTube metadata already generated above (reusing same video upload)
// Set fallback if not generated
if (!ytTitle && YOUTUBE_ACCOUNTS.length > 0) {
ytTitle = `${author} | K-drama/K-pop Content | idolchat.app`;
ytDescription =
isRepost && originalCaption
? originalCaption
: `${BASE_CAPTION.replace("%author%", author).replace(
"%originalCaption%",
originalCaption || "No caption available",
)}`;
}
const ytTags = ["kpop", "kdrama", "idolchat", "viral", "trending", author];
for (let j = 0; j < YOUTUBE_ACCOUNTS.length; j++) {
const ytAccount = YOUTUBE_ACCOUNTS[j];
try {
await updateStatus(
"📤 YouTube Upload Progress",
`Uploading to YouTube (${ytAccount.name})...`,
[
{ name: "Current Account", value: ytAccount.name, inline: true },
{ name: "Platform", value: "YouTube", inline: true },
{
name: "Progress",
value: `${completedYouTubeUploads}/${totalYouTubeUploads}`,
inline: true,
},
{ name: "Status", value: "⏳ Uploading…", inline: false },
],
0xff0000,
);
await uploadToYouTube(
ytAccount,
finalPath,
ytTitle,
ytDescription,
ytTags,
message.channel,
);
completedYouTubeUploads++;
} catch (error) {
await logToDiscord(
message.channel,
`❌ YouTube upload failed for ${ytAccount.name}: ${error.message}`,
"error",
);
await logToDiscord(
message.channel,
`Skipping to the next YouTube account...`,
"info",
);
}
// Only delay if not the last account
if (j < YOUTUBE_ACCOUNTS.length - 1) {
await delay(DELAYS.BETWEEN_YOUTUBE);
}
}
try {
const filesToClean = [
path.join(__dirname, "videos", `reel_${sessionId}.mp4`),
path.join(__dirname, "videos", `cleaned_${sessionId}.mp4`),
path.join(__dirname, "videos", `edited_reel_${sessionId}.mp4`),
path.join(__dirname, "videos", `final_reel_${sessionId}.mp4`),
];
// Also clean up any retry attempt files for THIS session only
try {
const videosDir = path.join(__dirname, "videos");
if (fs.existsSync(videosDir)) {
const allFiles = fs.readdirSync(videosDir);
const now = Date.now();
const retryFiles = allFiles
.filter((f) => {
// Clean session-specific files
if (f.includes(sessionId)) return true;
// Clean orphaned instagram_upload files older than 10 minutes
if (f.startsWith("instagram_upload_")) {
try {
const filePath = path.join(videosDir, f);
const stats = fs.statSync(filePath);
const ageMs = now - stats.mtimeMs;
return ageMs > 600000; // 10 minutes
} catch (e) {
return false;
}
}
// Clean orphaned trimmed_ai_ files older than 10 minutes
if (f.startsWith("trimmed_ai_")) {
try {
const filePath = path.join(videosDir, f);
const stats = fs.statSync(filePath);
const ageMs = now - stats.mtimeMs;
return ageMs > 600000; // 10 minutes
} catch (e) {
return false;
}
}
return false;
})
.map((f) => path.join(videosDir, f));
filesToClean.push(...retryFiles);
}
} catch (dirError) {
console.error(`Error reading videos directory:`, dirError.message);
}
// Use Set to avoid duplicate file paths
const uniqueFiles = [...new Set(filesToClean)];
for (const file of uniqueFiles) {
try {
// Double-check existence before deletion to avoid race conditions
if (fs.existsSync(file)) {
fs.unlinkSync(file);
console.log(`🧹 Cleaned up: ${path.basename(file)}`);
}
} catch (error) {
// Ignore ENOENT errors (file already deleted)
if (error.code !== "ENOENT") {
console.error(
`Failed to delete ${path.basename(file)}:`,
error.message,
);
}
}
}
console.log(`🧹 Cleanup completed for session: ${sessionId}`);
} catch (cleanupError) {
console.error(
`Cleanup error for session ${sessionId}:`,
cleanupError.message,
);
} finally {
// Only delete session here, not in try block (prevents race condition)
if (activeSessions.has(sessionId)) {
activeSessions.delete(sessionId);
console.log(
`Session ${sessionId} completed. Active sessions: ${activeSessions.size}`,
);
}
}
// Better success/failure logic
const instagramFailed = totalUploads > 0 && completedUploads === 0;
const youtubeFailed =
totalYouTubeUploads > 0 && completedYouTubeUploads === 0;