-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
538 lines (469 loc) · 18.4 KB
/
server.js
File metadata and controls
538 lines (469 loc) · 18.4 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
const express = require('express');
const axios = require('axios');
const path = require('path');
const { Client, GatewayIntentBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 25580;
// Discord Bot Client with all necessary intents
const discordClient = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers
]
});
// Store generated images
let generatedImages = [];
// Available models
const AVAILABLE_MODELS = {
'flux': 'Flux (Recommended)',
'seeddream': 'SeedDream (New)',
'turbo': 'Turbo (Fast)',
'kontext': 'Kontext (Premium)'
};
// Bot commands information
const BOT_COMMANDS = {
'ai': [
{
name: '.imggen',
description: 'Generate AI images from text prompts',
usage: '.imggen <prompt> [--model <model>]',
examples: [
'.imggen a beautiful sunset over mountains',
'.imggen a cyberpunk city --model turbo',
'.imggen fantasy landscape --model seeddream'
]
},
{
name: '.help-ai',
description: 'Show AI image generation help',
usage: '.help-ai',
examples: ['.help-ai']
}
],
'music': [
{
name: '.play',
description: 'Play music in voice channel',
usage: '.play <song name or URL>',
examples: ['.play never gonna give you up', '.play https://youtube.com/watch?v=...']
},
{
name: '.skip',
description: 'Skip current song',
usage: '.skip',
examples: ['.skip']
},
{
name: '.stop',
description: 'Stop music and clear queue',
usage: '.stop',
examples: ['.stop']
}
],
'utility': [
{
name: '.help',
description: 'Show all bot commands',
usage: '.help [category]',
examples: ['.help', '.help ai', '.help music']
},
{
name: '.ping',
description: 'Check bot latency',
usage: '.ping',
examples: ['.ping']
}
]
};
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// API endpoint for image generation
app.post('/generate-image', async (req, res) => {
try {
const { prompt, model = 'flux', width = 512, height = 512 } = req.body;
if (!prompt) {
return res.status(400).json({ error: 'Prompt is required' });
}
const params = {
prompt: prompt,
model: model,
width: width,
height: height
};
console.log(`Web API: Generating image - ${prompt} with model: ${model}`);
const response = await axios.get('https://imggen-api.ankitgupta.com.np/api/pollination', {
params,
timeout: 120000
});
if (response.data.url) {
const imageData = {
prompt: prompt,
url: response.data.url,
model: model,
timestamp: new Date().toISOString(),
dimensions: `${width}x${height}`
};
generatedImages.unshift(imageData);
if (generatedImages.length > 50) {
generatedImages = generatedImages.slice(0, 50);
}
res.json({ success: true, data: imageData });
} else {
res.status(500).json({ error: 'Failed to generate image' });
}
} catch (error) {
console.error('Web API Image generation error:', error);
res.status(500).json({ error: 'Image generation failed. Please try again.' });
}
});
// Get recent images
app.get('/recent-images', (req, res) => {
res.json({ images: generatedImages.slice(0, 20) });
});
// Discord bot status
app.get('/bot-status', (req, res) => {
res.json({
status: discordClient.isReady() ? 'online' : 'offline',
username: discordClient.user?.tag || 'Not connected',
guilds: discordClient.guilds?.cache.size || 0
});
});
// Health check
app.get('/health', (req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
port: PORT,
nodeVersion: process.version,
discordBot: discordClient.isReady() ? 'online' : 'offline'
});
});
// ========== DISCORD BOT EVENT HANDLERS ==========
// Bot ready event
discordClient.once('ready', () => {
console.log(`🤖 DTEmpire Bot logged in as ${discordClient.user.tag}`);
console.log(`📊 Serving ${discordClient.guilds.cache.size} servers`);
console.log(`🔗 Invite Link: https://discord.com/oauth2/authorize?client_id=${discordClient.user.id}&permissions=2147485696&scope=bot%20applications.commands`);
// Set bot activity
discordClient.user.setActivity('.help-ai | DTEmpire AI');
});
// Debug: Log when bot joins a guild
discordClient.on('guildCreate', (guild) => {
console.log(`✅ Joined new guild: ${guild.name} (${guild.id}) with ${guild.memberCount} members`);
});
// Debug: Log when bot leaves a guild
discordClient.on('guildDelete', (guild) => {
console.log(`❌ Left guild: ${guild.name} (${guild.id})`);
});
// Parse command arguments
function parseCommandArgs(content) {
const args = content.slice(8).trim();
let prompt = args;
let model = 'flux'; // Default model
// Check for --model parameter
const modelMatch = args.match(/--model\s+(\w+)/i);
if (modelMatch) {
const requestedModel = modelMatch[1].toLowerCase();
if (AVAILABLE_MODELS[requestedModel]) {
model = requestedModel;
// Remove model parameter from prompt
prompt = args.replace(/--model\s+\w+/i, '').trim();
}
}
return { prompt, model };
}
// Create AI help embed
function createAIHelpEmbed() {
const modelList = Object.entries(AVAILABLE_MODELS)
.map(([key, value]) => `**${key}** - ${value}`)
.join('\n');
const aiCommands = BOT_COMMANDS.ai.map(cmd =>
`**${cmd.name}**\n${cmd.description}\n\`${cmd.usage}\`\n${cmd.examples.map(ex => `• ${ex}`).join('\n')}`
).join('\n\n');
return new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('🖼️ DTEmpire AI - Image Generation Help')
.setDescription('Generate amazing AI images with multiple models!')
.addFields(
{
name: '🎨 AI Commands',
value: aiCommands,
inline: false
},
{
name: '🤖 Available Models',
value: modelList,
inline: false
},
{
name: '💡 Tips',
value: '• Be descriptive with your prompts\n• Use --model to switch AI models\n• Keep prompts under 500 characters\n• Try different models for different styles',
inline: false
},
{
name: '🌐 Web Interface',
value: `[Open Web Panel](http://panel.ankitgupta.com.np:${PORT})`,
inline: true
},
{
name: '🔗 Links',
value: '[Add Bot](http://dsc.gg/dtempire) • [Join Server](http://dsc.gg/dtempire-server)',
inline: true
}
)
.setFooter({ text: 'Use .help for all commands • Made by DTEmpire' })
.setTimestamp();
}
// Create general help embed
function createGeneralHelpEmbed(category = null) {
const embed = new EmbedBuilder()
.setColor(0x00FF00)
.setTitle('🤖 DTEmpire Bot - Command Help')
.setDescription('Multi-purpose bot with AI image generation, music, and more!')
.setFooter({ text: 'Made by DTEmpire • http://dsc.gg/dtempire' })
.setTimestamp();
if (category && BOT_COMMANDS[category.toLowerCase()]) {
// Show specific category
const categoryCommands = BOT_COMMANDS[category.toLowerCase()];
const commandList = categoryCommands.map(cmd =>
`**${cmd.name}**\n${cmd.description}\n\`${cmd.usage}\``
).join('\n\n');
embed.addFields({
name: `📁 ${category.toUpperCase()} Commands`,
value: commandList,
inline: false
});
embed.setDescription(`**${category.toUpperCase()} Commands**\nUse \`.help-ai\` for AI-specific help`);
} else {
// Show all categories
const categories = Object.entries(BOT_COMMANDS).map(([cat, commands]) =>
`**${cat.toUpperCase()}** (${commands.length} commands)\n${commands.map(cmd => `\`${cmd.name}\``).join(', ')}`
).join('\n\n');
embed.addFields(
{
name: '📂 Command Categories',
value: categories,
inline: false
},
{
name: '🔍 More Help',
value: 'Use these commands for detailed help:\n• `.help-ai` - AI image generation\n• `.help <category>` - Specific category\n• `.help all` - All commands',
inline: false
},
{
name: '🌐 Web Panel',
value: `[AI Image Generator](${`http://panel.ankitgupta.com.np:${PORT}`})`,
inline: true
},
{
name: '🔗 Links',
value: '[Add Bot](http://dsc.gg/dtempire) • [Join Server](http://dsc.gg/dtempire-server)',
inline: true
}
);
}
return embed;
}
// Create action buttons for image results
function createImageActionButtons(imageUrl) {
return new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setLabel('🖼️ Download Image')
.setStyle(ButtonStyle.Link)
.setURL(imageUrl),
new ButtonBuilder()
.setLabel('🤖 AI Help')
.setStyle(ButtonStyle.Secondary)
.setCustomId('ai_help'),
new ButtonBuilder()
.setLabel('⭐ Join DTEmpire')
.setStyle(ButtonStyle.Link)
.setURL('http://dsc.gg/dtempire-server'),
new ButtonBuilder()
.setLabel('➕ Add Bot')
.setStyle(ButtonStyle.Link)
.setURL('http://dsc.gg/dtempire')
);
}
// Message handler for all commands
discordClient.on('messageCreate', async (message) => {
// Ignore messages from bots
if (message.author.bot) return;
console.log(`📨 Message received: "${message.content}" from ${message.author.tag} in ${message.guild?.name || 'DM'}`);
// .imggen command
if (message.content.startsWith('.imggen')) {
console.log(`🎨 .imggen command detected from ${message.author.tag}`);
const { prompt, model } = parseCommandArgs(message.content);
if (!prompt) {
console.log('❌ No prompt provided');
const embed = createAIHelpEmbed();
return message.reply({ embeds: [embed] });
}
if (prompt.length > 500) {
console.log('❌ Prompt too long');
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('❌ DTEmpire AI Image Generator')
.setDescription('Prompt too long! Keep it under 500 characters.')
.setFooter({ text: 'Made by DTEmpire' });
return message.reply({ embeds: [embed] });
}
try {
console.log(`🔄 Starting image generation for: "${prompt}" with model: ${model}`);
// Send generating message
const generatingEmbed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('🔄 DTEmpire AI Image Generator')
.setDescription(`Generating image for: \`\`\`${prompt}\`\`\``)
.addFields(
{ name: 'Model', value: AVAILABLE_MODELS[model], inline: true },
{ name: 'Status', value: 'Generating...', inline: true }
)
.setFooter({ text: 'This may take 30-60 seconds...' });
const sentMessage = await message.reply({
embeds: [generatingEmbed]
});
// Generate image
const startTime = Date.now();
console.log(`📡 Calling image API for: "${prompt}" with model: ${model}`);
const response = await axios.get('https://imggen-api.ankitgupta.com.np/api/pollination', {
params: {
prompt: prompt,
model: model,
width: 512,
height: 512
},
timeout: 120000
});
const generationTime = Date.now() - startTime;
console.log(`✅ Image generated in ${generationTime}ms: ${response.data.url}`);
if (response.data && response.data.url) {
// Create result embed
const resultEmbed = new EmbedBuilder()
.setColor(0x00FF00)
.setTitle('🎨 DTEmpire AI Image Generator')
.setDescription(`**Prompt:** \`\`\`${prompt}\`\`\``)
.addFields(
{ name: 'Model', value: AVAILABLE_MODELS[model], inline: true },
{ name: 'Status', value: 'Completed ✅', inline: true },
{ name: 'Generation Time', value: `${generationTime}ms`, inline: true }
)
.setImage(response.data.url)
.setFooter({
text: `Made by DTEmpire • Requested by ${message.author.tag}`,
iconURL: message.author.displayAvatarURL()
})
.setTimestamp();
const actionButtons = createImageActionButtons(response.data.url);
// Edit the original message with result
await sentMessage.edit({
embeds: [resultEmbed],
components: [actionButtons]
});
console.log(`✅ Successfully sent image to ${message.author.tag}`);
} else {
throw new Error('No image URL received from API');
}
} catch (error) {
console.error('❌ Command error:', error);
const errorEmbed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('❌ DTEmpire AI Image Generator')
.setDescription(`Failed to generate image: ${error.message}`)
.addFields(
{ name: 'Model', value: AVAILABLE_MODELS[model], inline: true },
{ name: 'Status', value: 'Failed ❌', inline: true }
)
.setFooter({ text: 'Please try again with a different prompt' });
try {
await message.reply({ embeds: [errorEmbed] });
} catch (replyError) {
console.error('Failed to send error message:', replyError);
}
}
}
// .help-ai command
else if (message.content.startsWith('.help-ai')) {
console.log(`❓ .help-ai command from ${message.author.tag}`);
const embed = createAIHelpEmbed();
await message.reply({ embeds: [embed] });
}
// .help command
else if (message.content.startsWith('.help')) {
console.log(`❓ .help command from ${message.author.tag}`);
const args = message.content.slice(6).trim();
const embed = createGeneralHelpEmbed(args);
await message.reply({ embeds: [embed] });
}
// .ping command
else if (message.content.startsWith('.ping')) {
const latency = Date.now() - message.createdTimestamp;
const apiLatency = Math.round(discordClient.ws.ping);
const embed = new EmbedBuilder()
.setColor(0x00FF00)
.setTitle('🏓 Pong!')
.addFields(
{ name: '📡 Bot Latency', value: `${latency}ms`, inline: true },
{ name: '🌐 API Latency', value: `${apiLatency}ms`, inline: true }
)
.setFooter({ text: 'DTEmpire Bot • Made with ❤️' })
.setTimestamp();
await message.reply({ embeds: [embed] });
}
});
// Handle button interactions
discordClient.on('interactionCreate', async (interaction) => {
if (!interaction.isButton()) return;
if (interaction.customId === 'ai_help') {
const embed = createAIHelpEmbed();
await interaction.reply({
embeds: [embed],
ephemeral: true
});
}
});
// Error handling
discordClient.on('error', (error) => {
console.error('❌ Discord client error:', error);
});
discordClient.on('warn', (warning) => {
console.warn('⚠️ Discord client warning:', warning);
});
process.on('unhandledRejection', (error) => {
console.error('❌ Unhandled promise rejection:', error);
});
// Start server and bot
async function startServer() {
try {
console.log('🚀 Starting DTEmpire AI Server...');
// Start Discord bot
console.log('🔐 Logging into Discord...');
await discordClient.login(process.env.DISCORD_BOT_TOKEN);
// Start web server
app.listen(PORT, '0.0.0.0', () => {
console.log(`🌐 DTEmpire Web server running on http://0.0.0.0:${PORT}`);
console.log(`📍 Access via: http://panel.ankitgupta.com.np:${PORT}`);
console.log(`🤖 DTEmpire Discord bot is: ${discordClient.isReady() ? '✅ ONLINE' : '❌ OFFLINE'}`);
console.log(`⏰ Started at: ${new Date().toLocaleString()}`);
if (discordClient.isReady()) {
console.log(`📊 Bot is in ${discordClient.guilds.cache.size} servers:`);
discordClient.guilds.cache.forEach(guild => {
console.log(` - ${guild.name} (${guild.id})`);
});
}
});
} catch (error) {
console.error('❌ Failed to start:', error);
process.exit(1);
}
}
startServer();