-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
187 lines (160 loc) · 5.82 KB
/
index.js
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
require('dotenv').config();
const { Client, GatewayIntentBits, Collection, REST, Routes, ActivityType } = require('discord.js');
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');
const { checkAndSendNewCodes } = require('./utils/autoCodeSend');
const { setupTopggWebhook } = require('./utils/topggWebhook');
// Express setup
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public')); // Create a 'public' folder for static files
app.get('/api/codes/genshin', async (req, res) => {
try {
const response = await axios.get('https://hoyo-codes.seria.moe/codes?game=genshin');
res.json(response.data);
} catch (error) {
console.error('Error fetching codes:', error);
res.status(500).json({ error: 'Failed to fetch codes' });
}
});
app.get('/api/codes/hsr', async (req, res) => {
try {
const response = await axios.get('https://hoyo-codes.seria.moe/codes?game=hkrpg');
res.json(response.data);
} catch (error) {
console.error('Error fetching codes:', error);
res.status(500).json({ error: 'Failed to fetch codes' });
}
});
// API Routes
app.get('/api/codes/zzz', async (req, res) => {
try {
const response = await axios.get('https://hoyo-codes.seria.moe/codes?game=nap');
res.json(response.data);
} catch (error) {
console.error('Error fetching codes:', error);
res.status(500).json({ error: 'Failed to fetch codes' });
}
});
// Serve HTML
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Start Express server
app.listen(PORT, () => {
console.log(`Web server running on port ${PORT}`);
});
// Discord bot setup
if (!process.env.DISCORD_TOKEN || !process.env.CLIENT_ID || !process.env.MONGODB_URI) {
throw new Error('Missing required environment variables');
}
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
//GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
]
});
client.commands = new Collection();
// Register commands function
async function registerCommands() {
try {
const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
// Clear require cache
delete require.cache[require.resolve(filePath)];
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
console.log(`Registered command: ${command.data.name}`);
}
}
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(process.env.CLIENT_ID),
{ body: commands }
);
console.log('Successfully registered application commands.');
} catch (error) {
console.error('Error registering commands:', error);
}
}
// Connect to MongoDB and start bot
mongoose.connect(process.env.MONGODB_URI)
.then(() => {
console.log('Connected to MongoDB');
client.login(process.env.DISCORD_TOKEN);
})
.catch(err => console.error('MongoDB connection error:', err));
client.once('ready', async () => {
console.log(`Logged in as ${client.user.tag}`);
try {
await registerCommands();
console.log('Commands registered successfully');
} catch (error) {
console.error('Error during startup:', error);
}
client.user.setPresence({
activities: [{
name: `for redemption codes | ${process.env.VERSION}`,
type: ActivityType.Watching
}],
status: 'online'
});
setInterval(() => checkAndSendNewCodes(client), 5 * 60 * 1000);
});
// After Express and client setup
setupTopggWebhook(app, client);
// Handle interactions
client.on('interactionCreate', async interaction => {
try {
// Command interactions
if (interaction.isCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error('Command execution error:', error);
const content = {
content: 'An error occurred while executing this command.',
ephemeral: true
};
if (interaction.deferred || interaction.replied) {
await interaction.editReply(content);
} else {
await interaction.reply(content);
}
}
}
// Modal submit interactions
if (interaction.isModalSubmit() && interaction.customId === 'redeemModal') {
const command = client.commands.get('redeem');
if (command?.modalSubmit) {
await command.modalSubmit(interaction);
}
}
} catch (error) {
console.error('Interaction error:', error);
}
});
// Error handling for uncaught exceptions
process.on('uncaughtException', error => {
console.error('Uncaught Exception:', error);
});
process.on('unhandledRejection', error => {
console.error('Unhandled Rejection:', error);
});