-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js.bak
More file actions
1266 lines (1078 loc) · 61.3 KB
/
Copy pathbot.js.bak
File metadata and controls
1266 lines (1078 loc) · 61.3 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
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
// Import node-fetch at the top level
let fetch;
try {
// Try to use the global fetch if available (Node.js 18+)
if (typeof global.fetch === 'function') {
fetch = global.fetch;
} else {
// Otherwise use node-fetch
fetch = require('node-fetch');
}
} catch (error) {
console.error('Error importing fetch:', error);
// Fallback to dynamic import if needed
fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
}
// SchedulerPost Bot
class SchedulerPostBot {
constructor() {
console.log('=== Starting SchedulerPost Bot ===');
// Initialize scheduled posts array
this.scheduledPosts = [];
// Initialize daily post counter
this.dailyPostCount = 0;
this.lastPostDate = new Date().toDateString();
// Initialize user channels map (userId -> channelId)
this.userChannels = new Map();
this.initBot();
}
// Helper function to verify channel access
async verifyChannelAccess(userId, chatId) {
// Get the user's configured channel
const userChannel = this.userChannels.get(userId);
if (!userChannel) {
await this.bot.sendMessage(chatId,
'⚠️ No channel configured. Please use /set_channel to configure your channel first.'
);
return null;
}
try {
// Get bot info first to ensure we have the bot ID
const botInfo = await this.bot.getMe();
// Check if the bot is an admin in the channel
const chatMember = await this.bot.getChatMember(userChannel, botInfo.id);
if (!['administrator', 'creator'].includes(chatMember.status)) {
await this.bot.sendMessage(chatId,
'❌ The bot is not an administrator in your channel.\n' +
'Please add the bot as an admin to your channel and use /set_channel again.'
);
return null;
}
return userChannel;
} catch (error) {
console.error('Channel access verification failed:', error.message);
await this.bot.sendMessage(chatId,
'❌ Failed to verify channel access: ' + error.message + '\n' +
'Please make sure:\n' +
'1. The bot is an admin in your channel\n' +
'2. The channel username/ID is correct\n' +
'Use /set_channel to reconfigure your channel.'
);
return null;
}
}
async initBot() {
// Check environment variables
console.log('Environment Check:');
console.log('TELEGRAM_BOT_TOKEN:', process.env.TELEGRAM_BOT_TOKEN ? '✅ SET' : '❌ MISSING');
console.log('CHANNEL_ID:', process.env.CHANNEL_ID || '❌ MISSING');
console.log('GEMINI_API_KEY:', process.env.GEMINI_API_KEY ? '✅ SET' : '❌ MISSING');
console.log('HUGGINGFACE_API_KEY:', process.env.HUGGINGFACE_API_KEY ? '✅ SET' : '❌ MISSING');
if (!process.env.TELEGRAM_BOT_TOKEN) {
console.error('❌ TELEGRAM_BOT_TOKEN is required!');
process.exit(1);
}
try {
// Initialize bot
this.bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, {
polling: true
});
// Test bot connection
const botInfo = await this.bot.getMe();
console.log('✅ Bot connected:', botInfo.username);
// Set up basic commands
this.setupCommands();
console.log('🤖 SchedulerPost bot is ready!');
} catch (error) {
console.error('❌ Failed to initialize bot:', error.message);
process.exit(1);
}
}
// Check daily post limit and update counter
checkDailyPostLimit() {
const currentDate = new Date().toDateString();
// Reset counter if it's a new day
if (this.lastPostDate !== currentDate) {
this.dailyPostCount = 0;
this.lastPostDate = currentDate;
}
// Check if limit reached
if (this.dailyPostCount >= 3) {
return false;
}
// Increment counter and return true
this.dailyPostCount++;
return true;
}
setupCommands() {
// Start command
this.bot.onText(/\/start/, async (msg) => {
const chatId = msg.chat.id;
console.log(`📱 /start from chat: ${chatId}`);
try {
await this.bot.sendMessage(chatId,
'🤖 SchedulerPost Bot is here!\n\n' +
'⚙️ Setup:\n' +
'/set_channel - Set your channel for posting\n\n' +
'📝 Content Generation:\n' +
'/generate_post - Generate a complete post with text and image\n\n' +
'📅 Scheduling:\n' +
'/schedule - Schedule a post\n' +
'/list_scheduled - List all scheduled posts\n' +
'/cancel_scheduled - Cancel a scheduled post'
);
} catch (error) {
console.error('Error sending start message:', error.message);
}
});
// Test command
this.bot.onText(/\/test/, async (msg) => {
const chatId = msg.chat.id;
console.log(`🧪 /test from chat: ${chatId}`);
try {
await this.bot.sendMessage(chatId, '✅ Bot is working correctly!');
} catch (error) {
console.error('Error in test command:', error.message);
}
});
// Set channel command
this.bot.onText(/\/set_channel/, async (msg) => {
const chatId = msg.chat.id;
const userId = msg.from.id;
console.log(`⚙️ /set_channel from chat: ${chatId}, user: ${userId}`);
await this.bot.sendMessage(chatId,
'📢 To set up your channel, please follow these steps:\n\n' +
'1. Make sure you\'ve added this bot as an admin to your channel\n' +
'2. Send me your channel username (e.g., @yourchannel) or channel ID\n\n' +
'Note: The bot needs admin rights to post content to your channel.'
);
// Set up a one-time listener for the channel ID
this.bot.once('message', async (channelMsg) => {
if (channelMsg.chat.id !== chatId) return;
const channelInput = channelMsg.text.trim();
// Validate channel format
if (!channelInput.startsWith('@') && !/^-100\d+$/.test(channelInput)) {
await this.bot.sendMessage(chatId,
'❌ Invalid channel format. Please provide a channel username starting with @ (e.g., @yourchannel) or a channel ID.'
);
return;
}
try {
// Get bot info
const botInfo = await this.bot.getMe();
// First check if the bot is an admin in the channel
try {
const chatMember = await this.bot.getChatMember(channelInput, botInfo.id);
if (!['administrator', 'creator'].includes(chatMember.status)) {
await this.bot.sendMessage(chatId,
'❌ The bot is not an administrator in your channel.\n' +
'Please add the bot as an admin to your channel and try again.'
);
return;
}
} catch (adminError) {
// If we can't check admin status, the bot likely doesn't have access
await this.bot.sendMessage(chatId,
'❌ Could not verify admin status: ' + adminError.message + '\n' +
'Please make sure:\n' +
'1. The bot is an admin in your channel\n' +
'2. The channel username/ID is correct\n' +
'Then try again.'
);
return;
}
// Try to send a test message to verify access
await this.bot.sendMessage(channelInput, '🧪 Test message from SchedulerPost Bot');
// Store the channel ID for this user
this.userChannels.set(userId, channelInput);
await this.bot.sendMessage(chatId,
'✅ Channel setup successful!\n\n' +
`Your posts will now be sent to ${channelInput}\n\n` +
'You can now use /generate_post to create and post content to your channel.'
);
} catch (error) {
await this.bot.sendMessage(chatId,
`❌ Channel setup failed: ${error.message}\n\n` +
'Possible reasons:\n' +
'- The bot is not an admin in your channel\n' +
'- The channel username/ID is incorrect\n' +
'- The channel is private and the bot doesn\'t have access\n\n' +
'Please add the bot as an admin to your channel and try again.'
);
console.error('Channel setup failed:', error.message);
}
});
});
// Channel test command
this.bot.onText(/\/channel/, async (msg) => {
const chatId = msg.chat.id;
const userId = msg.from.id;
console.log(`📺 /channel from chat: ${chatId}`);
// Verify channel access using our helper function
const channelId = await this.verifyChannelAccess(userId, chatId);
if (!channelId) {
// Error message already sent by verifyChannelAccess
return;
}
try {
await this.bot.sendMessage(channelId, '🧪 Test message from SchedulerPost Bot');
await this.bot.sendMessage(chatId, `✅ Channel access working! Messages will be sent to ${channelId}`);
} catch (error) {
await this.bot.sendMessage(chatId, `❌ Channel access failed: ${error.message}`);
console.error('Channel test failed:', error.message);
}
});
// API test command
this.bot.onText(/\/apis/, async (msg) => {
const chatId = msg.chat.id;
console.log(`🔗 /apis from chat: ${chatId}`);
let results = '🔍 API Test Results:\n\n';
// Test Gemini API
if (process.env.GEMINI_API_KEY) {
try {
const { GoogleGenerativeAI } = require('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
// Use the latest model version
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" });
const result = await model.generateContent("Say hello in one word");
const response = await result.response;
results += '✅ Gemini API: Working\n';
} catch (error) {
results += `❌ Gemini API: ${error.message}\n`;
}
} else {
results += '⚠️ Gemini API: Not configured\n';
}
// Test Hugging Face API
if (process.env.HUGGINGFACE_API_KEY) {
try {
// fetch is already imported at the top level
// Use a text-to-image model which is more likely to be available
const response = await fetch('https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.HUGGINGFACE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
inputs: "a photo of an astronaut riding a horse on mars"
})
});
if (response.ok) {
results += '✅ Hugging Face API: Working\n';
} else {
const errorText = await response.text().catch(e => 'Could not read error response');
results += `❌ Hugging Face API: HTTP ${response.status}\n`;
results += `Error details: ${errorText.substring(0, 100)}${errorText.length > 100 ? '...' : ''}\n`;
// If we get a 404, try one more model as a fallback
if (response.status === 404) {
try {
const fallbackResponse = await fetch('https://api-inference.huggingface.co/models/bert-base-uncased', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.HUGGINGFACE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
inputs: "Hello world"
})
});
if (fallbackResponse.ok) {
results += '✅ Fallback Hugging Face API: Working\n';
} else {
results += `❌ Fallback also failed: HTTP ${fallbackResponse.status}\n`;
}
} catch (fallbackError) {
results += `❌ Fallback error: ${fallbackError.message}\n`;
}
}
}
} catch (error) {
results += `❌ Hugging Face API: ${error.message}\n`;
}
} else {
results += '⚠️ Hugging Face API: Not configured\n';
}
await this.bot.sendMessage(chatId, results);
});
// Info command
this.bot.onText(/\/info/, async (msg) => {
const chatId = msg.chat.id;
console.log(`ℹ️ /info from chat: ${chatId}`);
try {
const botInfo = await this.bot.getMe();
await this.bot.sendMessage(chatId,
`🤖 Bot Information:\n\n` +
`Name: ${botInfo.first_name}\n` +
`Username: @${botInfo.username}\n` +
`ID: ${botInfo.id}\n` +
`Can Join Groups: ${botInfo.can_join_groups}\n` +
`Can Read Messages: ${botInfo.can_read_all_group_messages}\n` +
`Channel ID: ${process.env.CHANNEL_ID || 'Not set'}`
);
} catch (error) {
console.error('Error getting bot info:', error.message);
}
});
// Error handlers
this.bot.on('polling_error', (error) => {
console.error('❌ Polling error:', error.message);
if (error.message.includes('409')) {
console.log('🔄 Another instance might be running. Stopping...');
process.exit(1);
}
// Handle rate limiting
if (error.message.includes('429')) {
const retryAfterMatch = error.message.match(/retry after (\d+)/);
if (retryAfterMatch && retryAfterMatch[1]) {
const retryAfterSeconds = parseInt(retryAfterMatch[1]);
console.log(`⏳ Rate limited by Telegram. Waiting ${retryAfterSeconds} seconds before retrying...`);
// Pause polling for the specified time
this.bot.stopPolling();
setTimeout(() => {
console.log('🔄 Resuming polling after rate limit cooldown');
this.bot.startPolling();
}, (retryAfterSeconds + 1) * 1000);
}
}
});
this.bot.on('error', (error) => {
console.error('❌ Bot error:', error.message);
});
// Generate complete post (text + image) command
this.bot.onText(/\/generate_post/, async (msg) => {
const chatId = msg.chat.id;
const userId = msg.from.id;
console.log(`🔄 /generate_post from chat: ${chatId}, user: ${userId}`);
// Verify channel access using our helper function
const channelId = await this.verifyChannelAccess(userId, chatId);
if (!channelId) {
// Error message already sent by verifyChannelAccess
return;
}
// Check daily post limit
if (!this.checkDailyPostLimit()) {
await this.bot.sendMessage(chatId, '❌ Daily post limit reached (3/3). Try again tomorrow.');
return;
}
// Check if APIs are configured
if (!process.env.GEMINI_API_KEY || !process.env.HUGGINGFACE_API_KEY) {
await this.bot.sendMessage(chatId,
'❌ API configuration missing:\n' +
`${!process.env.GEMINI_API_KEY ? '- Gemini API not configured\n' : ''}` +
`${!process.env.HUGGINGFACE_API_KEY ? '- Hugging Face API not configured' : ''}`
);
return;
}
try {
// Step 1: Ask for the post title/topic
await this.bot.sendMessage(chatId,
'📝 What would you like to write about?\n' +
'Send a title or topic for your post.'
);
// Set up a one-time listener for the title
this.bot.once('message', async (titleMsg) => {
if (titleMsg.chat.id !== chatId) return;
const title = titleMsg.text;
if (!title) {
await this.bot.sendMessage(chatId, '❌ Please provide a valid title');
return;
}
await this.bot.sendMessage(chatId, '⏳ Generating text content...');
try {
// Generate text content
const { GoogleGenerativeAI } = require('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" });
// Generate content with specific instructions for shorter post
const textPrompt = `Write a short, engaging post about: ${title}.
Make it suitable for a Telegram channel post.
IMPORTANT REQUIREMENTS:
1. Use simple, straightforward language - avoid flowery or complex words
2. Keep it STRICTLY to 2 short paragraphs only
3. Focus only on the main points - be direct and concise
4. Do NOT include any hashtags, asterisks, or formatting
5. Total length should be around 3-5 sentences total`;
const textResult = await model.generateContent(textPrompt);
const textResponse = await textResult.response;
const postText = textResponse.text();
// Send the generated text
await this.bot.sendMessage(chatId, postText);
// Step 2: Ask if they want to add an image
await this.bot.sendMessage(chatId,
'🖼️ Would you like to add an image to this post?\n\n' +
'1. Yes, generate an image based on the title\n' +
'2. Yes, I\'ll describe a specific image\n' +
'3. No, text only\n\n' +
'Reply with the number of your choice.'
);
// Set up a one-time listener for the image choice
this.bot.once('message', async (imageChoiceMsg) => {
if (imageChoiceMsg.chat.id !== chatId) return;
const imageChoice = imageChoiceMsg.text;
// Handle text-only post
if (imageChoice === '3') {
// Show options for text-only post
await this.bot.sendMessage(chatId, '✅ Here\'s your text-only post:');
await this.bot.sendMessage(chatId, postText);
await this.showPostOptions(chatId, postText, null, null);
return;
}
let imagePrompt = '';
// Handle image generation based on title
if (imageChoice === '1') {
imagePrompt = title;
await this.bot.sendMessage(chatId, `⏳ Generating image based on: "${title}"... This may take a minute.`);
}
// Handle custom image description
else if (imageChoice === '2') {
await this.bot.sendMessage(chatId,
'🎨 Please describe the image you want:\n' +
'What image would complement this content?'
);
// Wait for image description
const imageDescriptionPromise = new Promise(resolve => {
this.bot.once('message', (imageDescMsg) => {
if (imageDescMsg.chat.id !== chatId) return;
resolve(imageDescMsg.text);
});
});
imagePrompt = await imageDescriptionPromise;
if (!imagePrompt) {
await this.bot.sendMessage(chatId, '❌ Please provide a valid image description');
return;
}
await this.bot.sendMessage(chatId, `⏳ Generating image... This may take a minute.`);
}
// Handle invalid choice
else {
await this.bot.sendMessage(chatId, '❌ Invalid choice. Using text-only post.');
await this.showPostOptions(chatId, postText, null, null);
return;
}
try {
// Generate image
// fetch is already imported at the top level
const response = await fetch('https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.HUGGINGFACE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
inputs: imagePrompt
})
});
if (response.ok) {
// Get the image data
const imageBuffer = await response.buffer();
// Send the complete post preview
await this.bot.sendMessage(chatId, '✅ Here\'s your complete post:');
console.log('Sending preview photo with caption');
// Make sure we're explicitly setting the caption option
const previewOptions = {
caption: postText
};
console.log('Preview caption options:', previewOptions);
// Send preview
await this.bot.sendPhoto(chatId, imageBuffer, previewOptions);
// Show post options
await this.showPostOptions(chatId, postText, imageBuffer, imagePrompt);
} else {
const errorText = await response.text();
await this.bot.sendMessage(chatId, `❌ Failed to generate image: ${response.status} ${errorText.substring(0, 100)}`);
// Show options for text-only post as fallback
await this.bot.sendMessage(chatId, '✅ Proceeding with text-only post:');
await this.showPostOptions(chatId, postText, null, null);
}
} catch (error) {
await this.bot.sendMessage(chatId, `❌ Error generating image: ${error.message}`);
// Show options for text-only post as fallback
await this.bot.sendMessage(chatId, '✅ Proceeding with text-only post:');
await this.showPostOptions(chatId, postText, null, null);
}
});
} catch (error) {
await this.bot.sendMessage(chatId, `❌ Error generating text: ${error.message}`);
// Decrement the post count since we failed
this.dailyPostCount--;
}
});
} catch (error) {
console.error('Error in generate_post command:', error.message);
// Decrement the post count since we failed
this.dailyPostCount--;
}
});
// Generate text command
this.bot.onText(/\/generate_text/, async (msg) => {
const chatId = msg.chat.id;
console.log(`📝 /generate_text from chat: ${chatId}`);
// Check if Gemini API is configured
if (!process.env.GEMINI_API_KEY) {
await this.bot.sendMessage(chatId, '❌ Gemini API not configured');
return;
}
try {
// Ask for the prompt
await this.bot.sendMessage(chatId,
'🤖 What would you like me to write about?\n' +
'Send a topic or prompt, and I\'ll generate content using Gemini AI.'
);
// Set up a one-time listener for the next message
this.bot.once('message', async (promptMsg) => {
if (promptMsg.chat.id !== chatId) return; // Ensure it's from the same chat
const prompt = promptMsg.text;
if (!prompt) {
await this.bot.sendMessage(chatId, '❌ Please provide a valid prompt');
return;
}
await this.bot.sendMessage(chatId, '⏳ Generating content...');
try {
const { GoogleGenerativeAI } = require('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" });
// Generate content with a more specific instruction
const fullPrompt = `Write a short, engaging post about: ${prompt}.
Make it suitable for a Telegram channel post.
IMPORTANT REQUIREMENTS:
1. Use simple, straightforward language - avoid flowery or complex words
2. Keep it STRICTLY to 2 short paragraphs only
3. Focus only on the main points - be direct and concise
4. Do NOT include any hashtags, asterisks, or formatting
5. Total length should be around 3-5 sentences total`;
const result = await model.generateContent(fullPrompt);
const response = await result.response;
const text = response.text();
// Send the generated content
await this.bot.sendMessage(chatId, text);
// Ask if they want to post it to the channel
if (process.env.CHANNEL_ID) {
await this.bot.sendMessage(chatId,
'📢 Would you like to post this to your channel?\n' +
'Reply with "yes" to post now or "no" to cancel.'
);
// Set up a one-time listener for the confirmation
this.bot.once('message', async (confirmMsg) => {
if (confirmMsg.chat.id !== chatId) return;
const confirmation = confirmMsg.text.toLowerCase();
if (confirmation === 'yes') {
try {
await this.bot.sendMessage(process.env.CHANNEL_ID, text);
await this.bot.sendMessage(chatId, '✅ Posted to channel successfully!');
} catch (error) {
await this.bot.sendMessage(chatId, `❌ Failed to post to channel: ${error.message}`);
}
} else {
await this.bot.sendMessage(chatId, '❌ Post cancelled');
}
});
}
} catch (error) {
await this.bot.sendMessage(chatId, `❌ Error generating content: ${error.message}`);
}
});
} catch (error) {
console.error('Error in generate_text command:', error.message);
}
});
// Generate image command
this.bot.onText(/\/generate_image/, async (msg) => {
const chatId = msg.chat.id;
console.log(`🖼️ /generate_image from chat: ${chatId}`);
// Check if Hugging Face API is configured
if (!process.env.HUGGINGFACE_API_KEY) {
await this.bot.sendMessage(chatId, '❌ Hugging Face API not configured');
return;
}
try {
// Ask for the prompt
await this.bot.sendMessage(chatId,
'🎨 What image would you like me to generate?\n' +
'Describe the image you want, and I\'ll generate it using AI.'
);
// Set up a one-time listener for the next message
this.bot.once('message', async (promptMsg) => {
if (promptMsg.chat.id !== chatId) return; // Ensure it's from the same chat
const prompt = promptMsg.text;
if (!prompt) {
await this.bot.sendMessage(chatId, '❌ Please provide a valid description');
return;
}
await this.bot.sendMessage(chatId, '⏳ Generating image... This may take a minute.');
try {
const fetch = (await import('node-fetch')).default;
const response = await fetch('https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.HUGGINGFACE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
inputs: prompt
})
});
if (response.ok) {
// Get the image data
const imageBuffer = await response.buffer();
// Send the image
await this.bot.sendPhoto(chatId, imageBuffer, { caption: `Generated image for: "${prompt}"` });
// Ask if they want to post it to the channel
if (process.env.CHANNEL_ID) {
await this.bot.sendMessage(chatId,
'📢 Would you like to post this to your channel?\n' +
'Reply with "yes" to post now or "no" to cancel.'
);
// Set up a one-time listener for the confirmation
this.bot.once('message', async (confirmMsg) => {
if (confirmMsg.chat.id !== chatId) return;
const confirmation = confirmMsg.text.toLowerCase();
if (confirmation === 'yes') {
try {
await this.bot.sendPhoto(process.env.CHANNEL_ID, imageBuffer, { caption: prompt });
await this.bot.sendMessage(chatId, '✅ Posted to channel successfully!');
} catch (error) {
await this.bot.sendMessage(chatId, `❌ Failed to post to channel: ${error.message}`);
}
} else {
await this.bot.sendMessage(chatId, '❌ Post cancelled');
}
});
}
} else {
const errorText = await response.text();
await this.bot.sendMessage(chatId, `❌ Failed to generate image: ${response.status} ${errorText.substring(0, 100)}`);
}
} catch (error) {
await this.bot.sendMessage(chatId, `❌ Error generating image: ${error.message}`);
}
});
} catch (error) {
console.error('Error in generate_image command:', error.message);
}
});
// Schedule post command
this.bot.onText(/\/schedule/, async (msg) => {
const chatId = msg.chat.id;
const userId = msg.from.id;
console.log(`📅 /schedule from chat: ${chatId}, user: ${userId}`);
// Verify channel access using our helper function
const channelId = await this.verifyChannelAccess(userId, chatId);
if (!channelId) {
// Error message already sent by verifyChannelAccess
return;
}
try {
// Ask what type of content to schedule
await this.bot.sendMessage(chatId,
'📝 What type of content would you like to schedule?\n\n' +
'1. Text post (AI-generated)\n' +
'2. Image post (AI-generated)\n' +
'3. Custom message\n\n' +
'Reply with the number of your choice.'
);
// Set up a one-time listener for content type
this.bot.once('message', async (typeMsg) => {
if (typeMsg.chat.id !== chatId) return;
const contentType = typeMsg.text;
if (!['1', '2', '3'].includes(contentType)) {
await this.bot.sendMessage(chatId, '❌ Invalid choice. Please use /schedule to try again.');
return;
}
// Handle different content types
if (contentType === '1') {
// AI-generated text
await this.bot.sendMessage(chatId,
'🤖 What topic would you like the AI to write about?\n' +
'Send a topic or prompt for the AI-generated text.'
);
this.bot.once('message', async (promptMsg) => {
if (promptMsg.chat.id !== chatId) return;
const prompt = promptMsg.text;
if (!prompt) {
await this.bot.sendMessage(chatId, '❌ Please provide a valid prompt');
return;
}
// Now ask for scheduling time
await this.askForScheduleTime(chatId, {
type: 'text',
prompt: prompt,
contentType: 'ai-text'
});
});
} else if (contentType === '2') {
// AI-generated image
await this.bot.sendMessage(chatId,
'🎨 What image would you like the AI to generate?\n' +
'Describe the image you want for the scheduled post.'
);
this.bot.once('message', async (promptMsg) => {
if (promptMsg.chat.id !== chatId) return;
const prompt = promptMsg.text;
if (!prompt) {
await this.bot.sendMessage(chatId, '❌ Please provide a valid description');
return;
}
// Now ask for scheduling time
await this.askForScheduleTime(chatId, {
type: 'image',
prompt: prompt,
contentType: 'ai-image'
});
});
} else if (contentType === '3') {
// Custom message
await this.bot.sendMessage(chatId,
'✏️ Please enter the custom message you want to schedule:'
);
this.bot.once('message', async (contentMsg) => {
if (contentMsg.chat.id !== chatId) return;
const content = contentMsg.text;
if (!content) {
await this.bot.sendMessage(chatId, '❌ Please provide valid content');
return;
}
// Now ask for scheduling time
await this.askForScheduleTime(chatId, {
type: 'text',
content: content,
contentType: 'custom'
});
});
}
});
} catch (error) {
console.error('Error in schedule command:', error.message);
await this.bot.sendMessage(chatId, `❌ Error: ${error.message}`);
}
});
// List scheduled posts command
this.bot.onText(/\/list_scheduled/, async (msg) => {
const chatId = msg.chat.id;
console.log(`📋 /list_scheduled from chat: ${chatId}`);
try {
if (this.scheduledPosts.length === 0) {
await this.bot.sendMessage(chatId, '📅 No scheduled posts found.');
return;
}
let message = '📅 Scheduled Posts:\n\n';
this.scheduledPosts.forEach((post, index) => {
const date = new Date(post.timestamp);
message += `${index + 1}. [${post.contentType}] - ${date.toLocaleString()}\n`;
if (post.contentType === 'custom') {
message += `Content: ${post.content.substring(0, 30)}${post.content.length > 30 ? '...' : ''}\n`;
} else if (post.contentType === 'ai-text' || post.contentType === 'ai-image') {
message += `Prompt: ${post.prompt.substring(0, 30)}${post.prompt.length > 30 ? '...' : ''}\n`;
} else if (post.contentType === 'combined-post') {
message += `Combined post (text + image)\n`;
message += `Text: ${post.text.substring(0, 30)}${post.text.length > 30 ? '...' : ''}\n`;
}
message += '\n';
});
await this.bot.sendMessage(chatId, message);
} catch (error) {
console.error('Error listing scheduled posts:', error.message);
await this.bot.sendMessage(chatId, `❌ Error: ${error.message}`);
}
});
// Cancel scheduled post command
this.bot.onText(/\/cancel_scheduled/, async (msg) => {
const chatId = msg.chat.id;
console.log(`❌ /cancel_scheduled from chat: ${chatId}`);
try {
if (this.scheduledPosts.length === 0) {
await this.bot.sendMessage(chatId, '📅 No scheduled posts to cancel.');
return;
}
let message = '📅 Select a post to cancel:\n\n';
this.scheduledPosts.forEach((post, index) => {
const date = new Date(post.timestamp);
message += `${index + 1}. [${post.contentType}] - ${date.toLocaleString()}\n`;
if (post.contentType === 'custom') {
message += `Content: ${post.content.substring(0, 30)}${post.content.length > 30 ? '...' : ''}\n`;
} else if (post.contentType === 'ai-text' || post.contentType === 'ai-image') {
message += `Prompt: ${post.prompt.substring(0, 30)}${post.prompt.length > 30 ? '...' : ''}\n`;
} else if (post.contentType === 'combined-post') {
message += `Combined post (text + image)\n`;
message += `Text: ${post.text.substring(0, 30)}${post.text.length > 30 ? '...' : ''}\n`;
}
message += '\n';
});
message += 'Reply with the number of the post you want to cancel.';
await this.bot.sendMessage(chatId, message);
// Set up a one-time listener for the selection
this.bot.once('message', async (selectionMsg) => {
if (selectionMsg.chat.id !== chatId) return;
const selection = parseInt(selectionMsg.text);
if (isNaN(selection) || selection < 1 || selection > this.scheduledPosts.length) {
await this.bot.sendMessage(chatId, '❌ Invalid selection. Please try again.');
return;
}
const index = selection - 1;
const post = this.scheduledPosts[index];
// Clear the scheduled job
if (post.job) {
clearTimeout(post.job);
}
// Remove from the array
this.scheduledPosts.splice(index, 1);
await this.bot.sendMessage(chatId, '✅ Scheduled post cancelled successfully.');
});
} catch (error) {
console.error('Error cancelling scheduled post:', error.message);
await this.bot.sendMessage(chatId, `❌ Error: ${error.message}`);
}
});
// Log all messages for debugging
this.bot.on('message', (msg) => {
if (msg.text) {
console.log(`📩 Message from ${msg.from.first_name} (${msg.chat.id}): ${msg.text}`);
} else {
console.log(`📩 Non-text message from ${msg.from.first_name} (${msg.chat.id})`);
}
});
}
// Helper method to ask for schedule time
async askForScheduleTime(chatId, postData) {
try {
// Get user ID from chat ID (assuming private chat)
const userId = chatId;
await this.bot.sendMessage(chatId,
'⏰ When would you like to schedule this post?\n\n' +
'Please enter the number of minutes from now (e.g., 5 for 5 minutes from now).\n' +
'For testing purposes, we recommend using a small value like 1-5 minutes.'
);
this.bot.once('message', async (timeMsg) => {
if (timeMsg.chat.id !== chatId) return;
const minutes = parseInt(timeMsg.text);