-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
281 lines (239 loc) · 7.25 KB
/
Copy pathbot.js
File metadata and controls
281 lines (239 loc) · 7.25 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
const { Client, GatewayIntentBits } = require('discord.js');
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
class BotManager {
constructor() {
this.clients = new Map(); // Map of botId to client
this.currentBotId = null;
this.logs = [];
this.botConfigs = [];
this.loadBotConfigs();
}
// Load bot configurations from config folder
loadBotConfigs() {
const configDir = path.join(__dirname, 'config');
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
// Create example config
this.createExampleConfig();
return;
}
const items = fs.readdirSync(configDir);
for (const item of items) {
const itemPath = path.join(configDir, item);
const stat = fs.statSync(itemPath);
if (stat.isDirectory()) {
const envPath = path.join(itemPath, '.env');
if (fs.existsSync(envPath)) {
this.botConfigs.push({
id: item,
name: item,
path: itemPath
});
}
}
}
}
createExampleConfig() {
const exampleDir = path.join(__dirname, 'config', 'example-bot');
fs.mkdirSync(exampleDir, { recursive: true });
const envContent = `# Discord Bot Token - Get this from https://discord.com/developers/applications
DISCORD_TOKEN=your_bot_token_here
# Bot Configuration
BOT_PREFIX=!
BOT_NAME=Example Bot
`;
fs.writeFileSync(path.join(exampleDir, '.env'), envContent);
this.log('Created example bot config in config/example-bot/.env');
}
init() {
if (this.botConfigs.length > 0) {
this.switchBot(this.botConfigs[0].id);
} else {
this.log('No bot configurations found. Please add a .env file in config/your-bot-name/');
}
}
switchBot(botId) {
// Cleanup current bot
if (this.currentBotId && this.clients.has(this.currentBotId)) {
const client = this.clients.get(this.currentBotId);
client.destroy();
this.clients.delete(this.currentBotId);
}
this.currentBotId = botId;
const config = this.botConfigs.find(c => c.id === botId);
if (!config) {
this.log(`Bot config ${botId} not found`);
return;
}
this.createClient(config);
}
createClient(config) {
// Load environment variables
const envPath = path.join(config.path, '.env');
const envConfig = dotenv.config({ path: envPath });
if (envConfig.error) {
this.log(`Error loading .env for ${config.id}: ${envConfig.error.message}`);
return;
}
const token = process.env.DISCORD_TOKEN;
if (!token) {
this.log(`No DISCORD_TOKEN found in ${envPath}`);
return;
}
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
// Event handlers
client.on('ready', () => {
this.log(`Bot ${config.name} is ready! Logged in as ${client.user.tag}`);
});
client.on('messageCreate', (message) => {
if (message.author.bot) return;
this.log(`Message from ${message.author.tag} in ${message.channel.name}: ${message.content}`);
});
client.on('error', (error) => {
this.log(`Bot error: ${error.message}`);
});
client.on('disconnect', () => {
this.log('Bot disconnected');
});
client.on('reconnecting', () => {
this.log('Bot reconnecting...');
});
// Login
client.login(token).catch(error => {
this.log(`Failed to login: ${error.message}`);
});
this.clients.set(config.id, client);
}
reconnect() {
if (this.currentBotId) {
this.switchBot(this.currentBotId);
}
}
getGuilds() {
const client = this.clients.get(this.currentBotId);
if (!client) return [];
return client.guilds.cache.map(guild => ({
id: guild.id,
name: guild.name,
iconURL: guild.iconURL()
}));
}
getChannels(guildId) {
const client = this.clients.get(this.currentBotId);
if (!client) return [];
const guild = client.guilds.cache.get(guildId);
if (!guild) return [];
return guild.channels.cache
.filter(channel => channel.type === 0) // TEXT channels
.map(channel => ({
id: channel.id,
name: channel.name,
type: channel.type
}));
}
async sendMessage(channelId, message) {
const client = this.clients.get(this.currentBotId);
if (!client) {
this.log('No active bot client');
return false;
}
try {
const channel = client.channels.cache.get(channelId);
if (!channel) {
this.log(`Channel ${channelId} not found`);
return false;
}
await channel.send(message);
this.log(`Message sent to ${channel.name}: ${message}`);
return true;
} catch (error) {
this.log(`Error sending message: ${error.message}`);
return false;
}
}
getLogs() {
return this.logs.slice(-100); // Last 100 logs
}
getBotConfigs() {
return this.botConfigs;
}
log(message) {
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] ${message}`;
this.logs.push(logEntry);
console.log(logEntry);
}
// Save bot configuration from UI input
saveBotConfig(token, name) {
try {
const botId = `ui-bot-${Date.now()}`;
const botDir = path.join(__dirname, 'config', botId);
fs.mkdirSync(botDir, { recursive: true });
const envContent = `# Discord Bot Token - Saved from UI
DISCORD_TOKEN=${token}
# Bot Configuration
BOT_PREFIX=!
BOT_NAME=${name}
`;
fs.writeFileSync(path.join(botDir, '.env'), envContent);
// Add to bot configs
this.botConfigs.push({
id: botId,
name: name,
path: botDir
});
this.log(`Bot configuration saved for ${name}`);
return true;
} catch (error) {
this.log(`Error saving bot config: ${error.message}`);
return false;
}
}
// Get stored tokens (without exposing the actual tokens)
getStoredTokens() {
return this.botConfigs.map(config => ({
id: config.id,
name: config.name,
created: fs.statSync(config.path).birthtime
}));
}
// Clear all stored data
clearAllData() {
try {
// Remove all config directories except example
const configDir = path.join(__dirname, 'config');
const items = fs.readdirSync(configDir);
for (const item of items) {
if (item !== 'example-bot') {
const itemPath = path.join(configDir, item);
fs.rmSync(itemPath, { recursive: true, force: true });
}
}
// Clear clients and configs
this.clients.clear();
this.botConfigs = [];
this.currentBotId = null;
this.logs = [];
this.log('All data cleared');
return true;
} catch (error) {
this.log(`Error clearing data: ${error.message}`);
return false;
}
}
cleanup() {
for (const [id, client] of this.clients) {
client.destroy();
}
this.clients.clear();
}
}
module.exports = BotManager;