-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
283 lines (236 loc) Β· 9.93 KB
/
server.js
File metadata and controls
283 lines (236 loc) Β· 9.93 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
const express = require('express');
const axios = require('axios');
const path = require('path');
const { Client, GatewayIntentBits, EmbedBuilder } = 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 = [];
// 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}`);
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('.imggen | 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})`);
});
// Message handler for .imggen command
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'}`);
// Check for .imggen command
if (message.content.startsWith('.imggen')) {
console.log(`π¨ .imggen command detected from ${message.author.tag}`);
const args = message.content.slice(8).trim();
if (!args) {
console.log('β No prompt provided');
const embed = new EmbedBuilder()
.setColor(0xFFA500)
.setTitle('β DTEmpire AI - Usage')
.setDescription('**Command:** `.imggen <prompt>`')
.addFields(
{ name: 'Example', value: '`.imggen a beautiful sunset over mountains`', inline: false },
{ name: 'Available Models', value: 'Flux (default), Turbo, Kontext', inline: false },
{ name: 'Note', value: 'Keep prompts under 500 characters', inline: false }
)
.setFooter({ text: 'Made by DTEmpire β’ http://dsc.gg/dtempire' });
return message.reply({ embeds: [embed] });
}
if (args.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: "${args}"`);
// Send generating message
const generatingEmbed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('π DTEmpire AI Image Generator')
.setDescription(`Generating image for: \`\`\`${args}\`\`\``)
.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: "${args}"`);
const response = await axios.get('https://imggen-api.ankitgupta.com.np/api/pollination', {
params: {
prompt: args,
model: 'flux',
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:** \`\`\`${args}\`\`\``)
.addFields(
{ name: 'Model', value: 'Flux', 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();
// Edit the original message with result
await sentMessage.edit({
embeds: [resultEmbed]
});
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}`)
.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);
}
}
}
});
// 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();