server registration and subscription

This commit is contained in:
VinceC
2024-11-28 02:53:42 -06:00
parent ad6d98d501
commit 92c1fa3a9e
11 changed files with 1988 additions and 980 deletions

5
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"cSpell.words": [
"supabase"
]
}

View File

@@ -1,90 +1,106 @@
const { REST, Routes, SlashCommandBuilder } = require('discord.js'); const { REST, Routes, SlashCommandBuilder, PermissionFlagsBits } = require("discord.js");
require('dotenv').config(); require("dotenv").config();
const commands = [ const commands = [
new SlashCommandBuilder() new SlashCommandBuilder()
.setName('ping') .setName("ping")
.setDescription('Replies with Pong!'), .setDescription("Replies with Pong!"),
new SlashCommandBuilder() new SlashCommandBuilder()
.setName('finduser') .setName("finduser")
.setDescription('Find a user by username') .setDescription("Find a user by username")
.addStringOption(option => .addStringOption((option) =>
option.setName('username') option
.setDescription('The username to search for') .setName("username")
.setRequired(true)) .setDescription("The username to search for")
.addStringOption(option => .setRequired(true)
option.setName('game') )
.setDescription('Specify a game to view stats for') .addStringOption((option) =>
.setRequired(false)), option
new SlashCommandBuilder() .setName("game")
.setName('matchhistory') .setDescription("Specify a game to view stats for")
.setDescription('View match history') .setRequired(false)
.addStringOption(option => ),
option.setName('username') new SlashCommandBuilder()
.setDescription('The username to search for') .setName("matchhistory")
.setRequired(true)) .setDescription("View match history")
.addStringOption(option => .addStringOption((option) =>
option.setName('game') option
.setDescription('Filter by game') .setName("username")
.setRequired(false)), .setDescription("The username to search for")
// New subscription commands .setRequired(true)
new SlashCommandBuilder() )
.setName('subscribe') .addStringOption((option) =>
.setDescription('Subscribe to game notifications') option.setName("game").setDescription("Filter by game").setRequired(false)
.addStringOption(option => ),
option.setName('game') new SlashCommandBuilder()
.setDescription('Game to subscribe to') .setName("subscribe")
.setRequired(true) .setDescription("Subscribe to game notifications")
.addChoices( .addStringOption((option) =>
{ name: 'Big Ballers VR', value: 'Big Ballers VR' }, option
{ name: 'Blacktop Hoops', value: 'Blacktop Hoops' }, .setName("game")
{ name: 'Breachers', value: 'Breachers' }, .setDescription("Game to subscribe to")
{ name: 'Echo Arena', value: 'Echo Arena' }, .setRequired(true)
{ name: 'Echo Combat', value: 'Echo Combat' }, .addChoices(
{ name: 'Gun Raiders', value: 'Gun Raiders' }, { name: "Big Ballers VR", value: "Big Ballers VR" },
{ name: 'Nock', value: 'Nock' }, { name: "Blacktop Hoops", value: "Blacktop Hoops" },
{ name: 'VAIL', value: 'VAIL' } { name: "Breachers", value: "Breachers" },
)) { name: "Echo Arena", value: "Echo Arena" },
.addChannelOption(option => { name: "Echo Combat", value: "Echo Combat" },
option.setName('channel') { name: "Gun Raiders", value: "Gun Raiders" },
.setDescription('Channel for notifications') { name: "Nock", value: "Nock" },
.setRequired(true)), { name: "VAIL", value: "VAIL" }
new SlashCommandBuilder() )
.setName('unsubscribe') )
.setDescription('Unsubscribe from game notifications') .addChannelOption((option) =>
.addStringOption(option => option
option.setName('game') .setName("channel")
.setDescription('Game to unsubscribe from') .setDescription("Channel for notifications")
.setRequired(true) .setRequired(true)
.addChoices( ),
{ name: 'Big Ballers VR', value: 'Big Ballers VR' }, new SlashCommandBuilder()
{ name: 'Blacktop Hoops', value: 'Blacktop Hoops' }, .setName("unsubscribe")
{ name: 'Breachers', value: 'Breachers' }, .setDescription("Unsubscribe from game notifications")
{ name: 'Echo Arena', value: 'Echo Arena' }, .addStringOption((option) =>
{ name: 'Echo Combat', value: 'Echo Combat' }, option
{ name: 'Gun Raiders', value: 'Gun Raiders' }, .setName("game")
{ name: 'Nock', value: 'Nock' }, .setDescription("Game to unsubscribe from")
{ name: 'VAIL', value: 'VAIL' } .setRequired(true)
)), .addChoices(
new SlashCommandBuilder() { name: "Big Ballers VR", value: "Big Ballers VR" },
.setName('list_subscriptions') { name: "Blacktop Hoops", value: "Blacktop Hoops" },
.setDescription('List all game subscriptions for this server') { name: "Breachers", value: "Breachers" },
{ name: "Echo Arena", value: "Echo Arena" },
{ name: "Echo Combat", value: "Echo Combat" },
{ name: "Gun Raiders", value: "Gun Raiders" },
{ name: "Nock", value: "Nock" },
{ name: "VAIL", value: "VAIL" }
)
),
new SlashCommandBuilder()
.setName("register_server")
.setDescription("Register this Discord server with BattleBot")
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
new SlashCommandBuilder()
.setName("list_subscriptions")
.setDescription("List all game subscriptions for this server"),
]; ];
const rest = new REST({ version: '10' }).setToken(process.env.BOT_TOKEN); const rest = new REST({ version: "10" }).setToken(process.env.BOT_TOKEN);
(async () => { (async () => {
try { try {
console.log('Started refreshing application (/) commands.'); console.log("Started refreshing application (/) commands.");
console.log('Commands to be deployed:', commands.map(cmd => cmd.name)); console.log(
"Commands to be deployed:",
commands.map((cmd) => cmd.name)
);
await rest.put( await rest.put(Routes.applicationCommands(process.env.CLIENT_ID), {
Routes.applicationCommands(process.env.CLIENT_ID), body: commands.map((command) => command.toJSON()),
{ body: commands.map(command => command.toJSON()) }, });
);
console.log('Successfully reloaded application (/) commands.'); console.log("Successfully reloaded application (/) commands.");
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
})(); })();

View File

@@ -1,9 +1,57 @@
// index.js const winston = require('winston');
require('dotenv').config(); const { createClient } = require('@supabase/supabase-js');
const Bot = require('./src/Bot'); const Bot = require('./src/Bot');
require('dotenv').config();
const bot = new Bot(); // Initialize logger
bot.start(process.env.BOT_TOKEN).catch(error => { const logger = winston.createLogger({
console.error('Failed to start bot:', error); level: 'debug',
process.exit(1); format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
})
]
});
// Initialize Supabase client
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_KEY
);
// Initialize and start bot
const bot = new Bot(process.env.DISCORD_TOKEN, supabase, logger);
bot.start().catch(error => {
console.error('Failed to start bot:', error);
process.exit(1);
});
// Handle process termination
process.on('SIGINT', async () => {
console.log('Received SIGINT. Shutting down...');
try {
await bot.stop();
process.exit(0);
} catch (error) {
console.error('Error during shutdown:', error);
process.exit(1);
}
});
process.on('SIGTERM', async () => {
console.log('Received SIGTERM. Shutting down...');
try {
await bot.stop();
process.exit(0);
} catch (error) {
console.error('Error during shutdown:', error);
process.exit(1);
}
}); });

258
node_modules/.package-lock.json generated vendored
View File

@@ -4,6 +4,26 @@
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"node_modules/@colors/colors": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",
"integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==",
"license": "MIT",
"engines": {
"node": ">=0.1.90"
}
},
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
"integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==",
"license": "MIT",
"dependencies": {
"colorspace": "1.1.x",
"enabled": "2.0.x",
"kuler": "^2.0.0"
}
},
"node_modules/@discordjs/builders": { "node_modules/@discordjs/builders": {
"version": "1.9.0", "version": "1.9.0",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.9.0.tgz", "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.9.0.tgz",
@@ -259,6 +279,12 @@
"integrity": "sha512-xegpDuR+z0UqG9fwHqNoy3rI7JDlvaPh2TY47Fl80oq6g+hXT+c/LEuE43X48clZ6lOfANl5WrPur9fYO1RJ/w==", "integrity": "sha512-xegpDuR+z0UqG9fwHqNoy3rI7JDlvaPh2TY47Fl80oq6g+hXT+c/LEuE43X48clZ6lOfANl5WrPur9fYO1RJ/w==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/triple-beam": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==",
"license": "MIT"
},
"node_modules/@types/ws": { "node_modules/@types/ws": {
"version": "8.5.12", "version": "8.5.12",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz",
@@ -297,6 +323,12 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/async": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"license": "MIT"
},
"node_modules/asynckit": { "node_modules/asynckit": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -366,6 +398,51 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/color": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz",
"integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==",
"license": "MIT",
"dependencies": {
"color-convert": "^1.9.3",
"color-string": "^1.6.0"
}
},
"node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"license": "MIT",
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
"license": "MIT"
},
"node_modules/color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"license": "MIT",
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"node_modules/colorspace": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz",
"integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==",
"license": "MIT",
"dependencies": {
"color": "^3.1.3",
"text-hex": "1.0.x"
}
},
"node_modules/combined-stream": { "node_modules/combined-stream": {
"version": "1.0.8", "version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -518,6 +595,12 @@
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/enabled": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",
"integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==",
"license": "MIT"
},
"node_modules/encodeurl": { "node_modules/encodeurl": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
@@ -611,6 +694,12 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/fecha": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
"integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==",
"license": "MIT"
},
"node_modules/finalhandler": { "node_modules/finalhandler": {
"version": "1.3.1", "version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
@@ -629,6 +718,12 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/fn.name": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz",
"integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==",
"license": "MIT"
},
"node_modules/follow-redirects": { "node_modules/follow-redirects": {
"version": "1.15.9", "version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
@@ -812,6 +907,30 @@
"node": ">= 0.10" "node": ">= 0.10"
} }
}, },
"node_modules/is-arrayish": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==",
"license": "MIT"
},
"node_modules/is-stream": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
"license": "MIT",
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/kuler": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
"integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==",
"license": "MIT"
},
"node_modules/lodash": { "node_modules/lodash": {
"version": "4.17.21", "version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
@@ -824,6 +943,29 @@
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/logform": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz",
"integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==",
"license": "MIT",
"dependencies": {
"@colors/colors": "1.6.0",
"@types/triple-beam": "^1.3.2",
"fecha": "^4.2.0",
"ms": "^2.1.1",
"safe-stable-stringify": "^2.3.1",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/logform/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/magic-bytes.js": { "node_modules/magic-bytes.js": {
"version": "1.10.0", "version": "1.10.0",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz", "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz",
@@ -929,6 +1071,15 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/one-time": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz",
"integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==",
"license": "MIT",
"dependencies": {
"fn.name": "1.x.x"
}
},
"node_modules/parseurl": { "node_modules/parseurl": {
"version": "1.3.3", "version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -1002,6 +1153,20 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/safe-buffer": { "node_modules/safe-buffer": {
"version": "5.2.1", "version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -1022,6 +1187,15 @@
], ],
"license": "MIT" "license": "MIT"
}, },
"node_modules/safe-stable-stringify": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/safer-buffer": { "node_modules/safer-buffer": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -1123,6 +1297,24 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
"integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==",
"license": "MIT",
"dependencies": {
"is-arrayish": "^0.3.1"
}
},
"node_modules/stack-trace": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
"integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/statuses": { "node_modules/statuses": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
@@ -1132,6 +1324,21 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/text-hex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
"integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==",
"license": "MIT"
},
"node_modules/toidentifier": { "node_modules/toidentifier": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@@ -1147,6 +1354,15 @@
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/triple-beam": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
"integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==",
"license": "MIT",
"engines": {
"node": ">= 14.0.0"
}
},
"node_modules/ts-mixer": { "node_modules/ts-mixer": {
"version": "6.0.4", "version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
@@ -1196,6 +1412,12 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": { "node_modules/utils-merge": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -1230,6 +1452,42 @@
"webidl-conversions": "^3.0.0" "webidl-conversions": "^3.0.0"
} }
}, },
"node_modules/winston": {
"version": "3.17.0",
"resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz",
"integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==",
"license": "MIT",
"dependencies": {
"@colors/colors": "^1.6.0",
"@dabh/diagnostics": "^2.0.2",
"async": "^3.2.3",
"is-stream": "^2.0.0",
"logform": "^2.7.0",
"one-time": "^1.0.0",
"readable-stream": "^3.4.0",
"safe-stable-stringify": "^2.3.1",
"stack-trace": "0.0.x",
"triple-beam": "^1.3.0",
"winston-transport": "^4.9.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/winston-transport": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
"integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==",
"license": "MIT",
"dependencies": {
"logform": "^2.7.0",
"readable-stream": "^3.6.2",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/ws": { "node_modules/ws": {
"version": "8.18.0", "version": "8.18.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",

261
package-lock.json generated
View File

@@ -14,7 +14,28 @@
"discord.js": "^14.16.2", "discord.js": "^14.16.2",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1", "express": "^4.21.1",
"undici": "^6.19.8" "undici": "^6.19.8",
"winston": "^3.17.0"
}
},
"node_modules/@colors/colors": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",
"integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==",
"license": "MIT",
"engines": {
"node": ">=0.1.90"
}
},
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
"integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==",
"license": "MIT",
"dependencies": {
"colorspace": "1.1.x",
"enabled": "2.0.x",
"kuler": "^2.0.0"
} }
}, },
"node_modules/@discordjs/builders": { "node_modules/@discordjs/builders": {
@@ -272,6 +293,12 @@
"integrity": "sha512-xegpDuR+z0UqG9fwHqNoy3rI7JDlvaPh2TY47Fl80oq6g+hXT+c/LEuE43X48clZ6lOfANl5WrPur9fYO1RJ/w==", "integrity": "sha512-xegpDuR+z0UqG9fwHqNoy3rI7JDlvaPh2TY47Fl80oq6g+hXT+c/LEuE43X48clZ6lOfANl5WrPur9fYO1RJ/w==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/triple-beam": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==",
"license": "MIT"
},
"node_modules/@types/ws": { "node_modules/@types/ws": {
"version": "8.5.12", "version": "8.5.12",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz",
@@ -310,6 +337,12 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/async": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"license": "MIT"
},
"node_modules/asynckit": { "node_modules/asynckit": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -379,6 +412,51 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/color": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz",
"integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==",
"license": "MIT",
"dependencies": {
"color-convert": "^1.9.3",
"color-string": "^1.6.0"
}
},
"node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"license": "MIT",
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
"license": "MIT"
},
"node_modules/color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"license": "MIT",
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"node_modules/colorspace": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz",
"integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==",
"license": "MIT",
"dependencies": {
"color": "^3.1.3",
"text-hex": "1.0.x"
}
},
"node_modules/combined-stream": { "node_modules/combined-stream": {
"version": "1.0.8", "version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -531,6 +609,12 @@
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/enabled": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",
"integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==",
"license": "MIT"
},
"node_modules/encodeurl": { "node_modules/encodeurl": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
@@ -624,6 +708,12 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/fecha": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
"integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==",
"license": "MIT"
},
"node_modules/finalhandler": { "node_modules/finalhandler": {
"version": "1.3.1", "version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
@@ -642,6 +732,12 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/fn.name": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz",
"integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==",
"license": "MIT"
},
"node_modules/follow-redirects": { "node_modules/follow-redirects": {
"version": "1.15.9", "version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
@@ -825,6 +921,30 @@
"node": ">= 0.10" "node": ">= 0.10"
} }
}, },
"node_modules/is-arrayish": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==",
"license": "MIT"
},
"node_modules/is-stream": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
"license": "MIT",
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/kuler": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
"integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==",
"license": "MIT"
},
"node_modules/lodash": { "node_modules/lodash": {
"version": "4.17.21", "version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
@@ -837,6 +957,29 @@
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/logform": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz",
"integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==",
"license": "MIT",
"dependencies": {
"@colors/colors": "1.6.0",
"@types/triple-beam": "^1.3.2",
"fecha": "^4.2.0",
"ms": "^2.1.1",
"safe-stable-stringify": "^2.3.1",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/logform/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/magic-bytes.js": { "node_modules/magic-bytes.js": {
"version": "1.10.0", "version": "1.10.0",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz", "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz",
@@ -942,6 +1085,15 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/one-time": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz",
"integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==",
"license": "MIT",
"dependencies": {
"fn.name": "1.x.x"
}
},
"node_modules/parseurl": { "node_modules/parseurl": {
"version": "1.3.3", "version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -1015,6 +1167,20 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/safe-buffer": { "node_modules/safe-buffer": {
"version": "5.2.1", "version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -1035,6 +1201,15 @@
], ],
"license": "MIT" "license": "MIT"
}, },
"node_modules/safe-stable-stringify": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/safer-buffer": { "node_modules/safer-buffer": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -1136,6 +1311,24 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
"integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==",
"license": "MIT",
"dependencies": {
"is-arrayish": "^0.3.1"
}
},
"node_modules/stack-trace": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
"integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/statuses": { "node_modules/statuses": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
@@ -1145,6 +1338,21 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/text-hex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
"integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==",
"license": "MIT"
},
"node_modules/toidentifier": { "node_modules/toidentifier": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@@ -1160,6 +1368,15 @@
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/triple-beam": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
"integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==",
"license": "MIT",
"engines": {
"node": ">= 14.0.0"
}
},
"node_modules/ts-mixer": { "node_modules/ts-mixer": {
"version": "6.0.4", "version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
@@ -1209,6 +1426,12 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": { "node_modules/utils-merge": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -1243,6 +1466,42 @@
"webidl-conversions": "^3.0.0" "webidl-conversions": "^3.0.0"
} }
}, },
"node_modules/winston": {
"version": "3.17.0",
"resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz",
"integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==",
"license": "MIT",
"dependencies": {
"@colors/colors": "^1.6.0",
"@dabh/diagnostics": "^2.0.2",
"async": "^3.2.3",
"is-stream": "^2.0.0",
"logform": "^2.7.0",
"one-time": "^1.0.0",
"readable-stream": "^3.4.0",
"safe-stable-stringify": "^2.3.1",
"stack-trace": "0.0.x",
"triple-beam": "^1.3.0",
"winston-transport": "^4.9.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/winston-transport": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
"integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==",
"license": "MIT",
"dependencies": {
"logform": "^2.7.0",
"readable-stream": "^3.6.2",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/ws": { "node_modules/ws": {
"version": "8.18.0", "version": "8.18.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",

View File

@@ -16,6 +16,7 @@
"discord.js": "^14.16.2", "discord.js": "^14.16.2",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1", "express": "^4.21.1",
"undici": "^6.19.8" "undici": "^6.19.8",
"winston": "^3.17.0"
} }
} }

View File

@@ -1,263 +1,144 @@
const { Client, GatewayIntentBits } = require("discord.js"); const { Client, GatewayIntentBits } = require('discord.js');
const CommandHandler = require("./commands/CommandHandler.js"); const CommandHandler = require('./commands/CommandHandler');
const PlayerService = require("./services/PlayerService.js"); const SubscriptionCommands = require('./commands/SubscriptionCommands');
const NotificationService = require("./services/NotificationService.js"); const PlayerService = require('./services/PlayerService');
const MatchCommands = require("./commands/MatchCommands.js"); const SupabaseService = require('./services/SupabaseService');
const SupabaseService = require("./services/SupabaseService.js"); const NotificationService = require('./services/NotificationService');
const SubscriptionCommands = require("./commands/SubscriptionCommands.js"); const Logger = require('./utils/Logger');
const CooldownManager = require("./utils/CooldownManager.js"); const ServerRegistrationService = require('./services/ServerRegistrationService');
const Logger = require("./utils/Logger.js");
class Bot { class Bot {
constructor() { constructor(token, supabase, logger) {
this.logger = new Logger('Bot'); if (!logger || typeof logger.error !== 'function') {
this.cooldownManager = new CooldownManager(); throw new Error('Invalid logger provided to Bot constructor');
}
this.client = new Client({ this.client = new Client({ intents: [GatewayIntentBits.Guilds] });
intents: [ this.token = token;
GatewayIntentBits.Guilds, this.supabase = supabase;
GatewayIntentBits.GuildMessages, this.logger = logger;
GatewayIntentBits.MessageContent, this.processingLock = new Map();
],
// Initialize services
this.playerService = new PlayerService(logger);
this.serverRegistrationService = new ServerRegistrationService(supabase, logger);
// Initialize command handlers
this.commandHandler = new CommandHandler(
this.playerService,
this.supabase,
this.logger,
this.serverRegistrationService
);
this.subscriptionCommands = new SubscriptionCommands(supabase, logger);
// Setup event handlers
this.client.on('ready', () => {
this.logger.info(`Logged in as ${this.client.user.tag}`);
}); });
this.logger.info('Initializing bot...');
this.initializeServices();
this.setupEventHandlers();
}
initializeServices() {
this.logger.debug('Initializing services...');
this.playerService = new PlayerService();
this.commandHandler = new CommandHandler(this.playerService);
this.matchCommands = new MatchCommands(this.playerService);
this.notificationService = new NotificationService(this);
this.initializeSupabase();
}
initializeSupabase() {
this.logger.debug('Initializing Supabase service...');
this.supabaseService = new SupabaseService();
if (this.supabaseService.supabase) {
this.subscriptionCommands = new SubscriptionCommands(this.supabaseService);
this.logger.info('Supabase service initialized successfully');
} else {
this.logger.warn('Supabase initialization failed. Subscription commands unavailable.');
this.subscriptionCommands = null;
}
}
setupEventHandlers() {
this.logger.debug('Setting up event handlers...');
this.client.on('error', this.handleError.bind(this));
this.client.once('ready', this.handleReady.bind(this));
this.client.on('interactionCreate', this.handleInteraction.bind(this)); this.client.on('interactionCreate', this.handleInteraction.bind(this));
} }
async start(token) { async start() {
this.logger.info('Starting bot...');
try { try {
await this.client.login(token); await this.client.login(this.token);
this.logger.info('Login successful');
const port = process.env.NOTIFICATION_PORT || 3000;
await this.notificationService.start(port);
this.logger.info(`Notification service started on port ${port}`);
} catch (error) { } catch (error) {
this.logger.error('Startup failed:', error); this.logger.error('Failed to start bot:', error);
throw error; throw error;
} }
} }
async stop() { async handleInteraction(interaction) {
this.logger.info('Stopping bot...'); if (!interaction.isCommand() && !interaction.isButton()) {
try { this.logger.debug('Ignoring non-command/button interaction');
await this.notificationService.stop(); return;
await this.client.destroy();
this.logger.info('Bot stopped successfully');
} catch (error) {
this.logger.error('Error stopping bot:', error);
throw error;
} }
}
handleError(error) { const lockKey = interaction.id;
this.logger.error('Discord client error:', error); if (this.processingLock.get(lockKey)) {
} this.logger.debug('Interaction already being processed', { id: lockKey });
return;
handleReady() {
this.logger.info(`Logged in as ${this.client.user.tag}`);
}
handleInteraction(interaction) {
this.logger.debug('Received interaction', {
type: interaction.type,
commandName: interaction.commandName,
user: interaction.user.tag,
guild: interaction.guild?.name,
channel: interaction.channel?.name
});
if (interaction.isCommand()) {
this.handleCommand(interaction)
.catch(error => this.handleInteractionError(interaction, error));
} else if (interaction.isButton()) {
this.handleButton(interaction)
.catch(error => this.handleInteractionError(interaction, error));
} }
}
async handleCommand(interaction) { // Set the lock before any async operations
this.processingLock.set(lockKey, true);
try { try {
// Check cooldown // Special handling for register_server command
const cooldownTime = this.cooldownManager.checkCooldown(interaction); if (interaction.isCommand() && interaction.commandName === 'register_server') {
if (cooldownTime > 0) { // Send initial response immediately
await interaction.reply({ await interaction.reply({
content: `Please wait ${cooldownTime.toFixed(1)} more seconds before using this command again.`, content: 'Attempting to register server...',
ephemeral: true ephemeral: true
}); });
return;
}
this.logger.debug('Processing command', { const guildId = interaction.guildId;
command: interaction.commandName, const serverName = interaction.guild.name;
user: interaction.user.tag
});
await this.processCommand(interaction); this.logger.debug('Starting server registration', {
guildId,
} catch (error) { serverName,
this.logger.error('Command error:', error); timestamp: new Date().toISOString()
await this.handleCommandError(interaction, error);
}
}
async processCommand(interaction) {
switch (interaction.commandName) {
case "ping":
await this.commandHandler.handlePing(interaction);
break;
case "finduser":
await this.commandHandler.handleFindUser(interaction);
break;
case "matchhistory":
await this.commandHandler.handleMatchHistory(interaction);
break;
case "subscribe":
case "unsubscribe":
case "list_subscriptions":
await this.handleSubscriptionCommand(interaction);
break;
default:
await interaction.reply({
content: "Unknown command",
ephemeral: true
}); });
}
}
async handleSubscriptionCommand(interaction) { try {
if (!this.subscriptionCommands) { // Attempt database operation first
await this.safeReply(interaction, "Subscription commands are not available."); const result = await this.serverRegistrationService.registerServer(guildId, serverName);
return;
}
try { this.logger.info('Server registration database operation completed', {
// Defer the reply immediately status: result.status,
await this.safeReply(interaction, "Processing your request..."); guildId,
serverId: result.server.id,
switch (interaction.commandName) { timestamp: new Date().toISOString()
case "subscribe":
await this.subscriptionCommands.handleSubscribe(interaction);
break;
case "unsubscribe":
await this.subscriptionCommands.handleUnsubscribe(interaction);
break;
case "list_subscriptions":
await this.subscriptionCommands.handleListSubscriptions(interaction);
break;
}
} catch (error) {
this.logger.error('Subscription command error:', error);
await this.safeReply(interaction, 'An error occurred while processing your request.');
}
}
async handleButton(interaction) {
const [action, matchId] = interaction.customId.split("_match_");
try {
this.logger.debug('Processing button interaction', {
action,
matchId,
user: interaction.user.tag
});
switch (action) {
case "accept":
await this.matchCommands.handleMatchAccept(interaction, matchId);
break;
case "view":
await this.matchCommands.handleViewDetails(interaction, matchId);
break;
default:
this.logger.warn('Unknown button action', { action });
await interaction.reply({
content: "Unknown button action",
ephemeral: true,
}); });
// Update the response with the result
const message = result.status === 'exists'
? '⚠️ This Discord server is already registered with BattleBot.'
: '✅ Server successfully registered with BattleBot! You can now use subscription commands.';
await interaction.editReply({
content: message,
ephemeral: true
});
} catch (dbError) {
this.logger.error('Server registration failed:', {
error: dbError.message,
stack: dbError.stack,
guildId,
timestamp: new Date().toISOString()
});
await interaction.editReply({
content: '❌ Failed to register server. Please try again.',
ephemeral: true
});
}
} else if (interaction.isCommand()) {
// Handle all other commands through the command handler
await this.commandHandler.handleCommand(interaction);
} else if (interaction.isButton()) {
// Handle button interactions
await this.commandHandler.handleButton(interaction);
} }
} catch (error) { } catch (error) {
this.logger.error("Error handling button:", error); this.logger.error('Command processing error:', {
await this.handleInteractionError(interaction, error); error: error.message,
} stack: error.stack,
} command: interaction.commandName,
guild: interaction.guild?.name,
async handleCommandError(interaction, error) { timestamp: new Date().toISOString()
this.logger.error('Command error:', error); });
try { } finally {
if (!interaction.replied && !interaction.deferred) { this.processingLock.delete(lockKey);
await interaction.reply({ this.logger.debug('Interaction processing completed', {
content: 'An error occurred while processing your command.', id: lockKey,
ephemeral: true command: interaction.commandName,
}); timestamp: new Date().toISOString()
} else if (interaction.deferred && !interaction.replied) { });
await interaction.editReply('An error occurred while processing your command.');
}
} catch (e) {
this.logger.error('Error sending error message:', e);
}
}
async safeReply(interaction, content, options = {}) {
try {
if (!interaction.deferred && !interaction.replied) {
await interaction.reply({ content, ephemeral: true, ...options });
} else if (interaction.deferred && !interaction.replied) {
await interaction.editReply({ content, ...options });
}
} catch (error) {
this.logger.error('Error in safeReply:', error);
}
}
async handleInteractionError(interaction, error) {
this.logger.error('Interaction error:', error);
try {
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content: 'An error occurred while processing your request.',
ephemeral: true
});
} else if (interaction.deferred && !interaction.replied) {
await interaction.editReply({
content: 'An error occurred while processing your request.'
});
}
} catch (e) {
this.logger.error('Error sending error message:', e);
} }
} }
} }

View File

@@ -1,235 +1,146 @@
// src/commands/CommandHandler.js
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
class CommandHandler { class CommandHandler {
constructor(playerService) { constructor(playerService, supabase, logger, serverRegistrationService) {
this.playerService = playerService; this.playerService = playerService;
} this.supabase = supabase;
this.logger = logger;
async handlePing(interaction) { this.serverRegistrationService = serverRegistrationService;
await interaction.reply('Pong!');
}
async handleFindUser(interaction) {
await interaction.deferReply();
const username = interaction.options.getString('username');
const gameFilter = interaction.options.getString('game');
const userData = await this.playerService.findUserByUsername(username);
if (!userData || !userData.success) {
await interaction.editReply('User not found or an error occurred while fetching data.');
return;
} }
const playerData = typeof userData.player_data === 'string' async handleCommand(interaction) {
? JSON.parse(userData.player_data) try {
: userData.player_data; switch (interaction.commandName) {
case 'register_server':
const embed = await this.createUserEmbed(playerData, gameFilter); await this.handleRegisterServer(interaction);
const row = this.createActionRow(playerData.username); break;
case 'ping':
await interaction.editReply({ embeds: [embed], components: [row] }); await interaction.editReply({ content: 'Pong!', ephemeral: true });
} break;
case 'finduser':
async handleMatchHistory(interaction) { await this.handleFindUser(interaction);
await interaction.deferReply(); break;
case 'matchhistory':
const username = interaction.options.getString('username'); await this.handleMatchHistory(interaction);
const gameFilter = interaction.options.getString('game'); break;
default:
try { await interaction.editReply({ content: 'Unknown command', ephemeral: true });
const userData = await this.playerService.findUserByUsername(username); }
if (!userData || !userData.success) { } catch (error) {
await interaction.editReply('User not found or an error occurred while fetching data.'); // Only log the error, let Bot class handle the response
return; this.logger.error('Command handling error:', {
} command: interaction.commandName,
error: error.message,
const playerData = typeof userData.player_data === 'string' stack: error.stack
? JSON.parse(userData.player_data)
: userData.player_data;
const matches = Object.values(playerData.matches || {})
.filter(match => !gameFilter || match.game_name.toLowerCase() === gameFilter.toLowerCase())
.sort((a, b) => new Date(b.start_time) - new Date(a.start_time))
.slice(0, 10);
if (matches.length === 0) {
await interaction.editReply(
gameFilter
? `No matches found for ${username} in ${gameFilter}`
: `No matches found for ${username}`
);
return;
}
const embed = this.createMatchHistoryEmbed(playerData, matches);
const row = this.createActionRow(playerData.username);
await interaction.editReply({ embeds: [embed], components: [row] });
} catch (error) {
console.error('Error in handleMatchHistory:', error);
await interaction.editReply('An error occurred while processing the match history.');
}
}
createUserEmbed(playerData, gameFilter) {
const profile = playerData.profile || {};
const embed = new EmbedBuilder()
.setTitle(`User: ${playerData.username || 'Unknown'}`)
.setDescription(profile.bio || 'No bio available')
.setColor('#0099ff');
// Add thumbnail (avatar)
if (profile.avatar) {
embed.setThumbnail(
`https://www.vrbattles.gg/assets/uploads/profile/${profile.avatar}`
);
}
// Add badge image using PlayerService
if (profile.current_level_badge) {
const badgeImageUrl = this.playerService.getBadgeImageUrl(profile.current_level_badge);
embed.setImage(badgeImageUrl);
}
// Add profile fields
const profileFields = [];
if (profile.country) profileFields.push({ name: 'Country', value: profile.country, inline: true });
if (profile.level) profileFields.push({ name: 'Level', value: profile.level.toString(), inline: true });
if (profile.xp) profileFields.push({ name: 'Total XP', value: profile.xp.toString(), inline: true });
if (profile.prestige) profileFields.push({ name: 'Prestige', value: profile.prestige.toString(), inline: true });
if (profileFields.length > 0) {
embed.addFields(profileFields);
}
// Add game stats if available
const games = playerData.stats?.games;
if (games) {
Object.entries(games).forEach(([gameName, gameData]) => {
if (gameFilter && gameName.toLowerCase() !== gameFilter.toLowerCase()) return;
embed.addFields({ name: gameName, value: '\u200B' });
Object.entries(gameData).forEach(([mode, stats]) => {
if (mode === 'Overall') return;
const statFields = [];
if (stats.matches) statFields.push(`Matches: ${stats.matches}`);
if (stats.wins) statFields.push(`Wins: ${stats.wins}`);
if (stats.losses) statFields.push(`Losses: ${stats.losses}`);
if (stats.win_rate) statFields.push(`Win Rate: ${stats.win_rate}`);
if (statFields.length > 0) {
embed.addFields({
name: mode,
value: statFields.join(' | '),
inline: true
}); });
} throw error; // Re-throw to let Bot handle it
}
}
async handleRegisterServer(interaction) {
if (!interaction.deferred) {
this.logger.warn('Interaction not deferred, cannot proceed', {
guildId: interaction.guildId
});
return;
}
// Get the server details first
const guildId = interaction.guildId;
const serverName = interaction.guild.name;
this.logger.debug('Starting server registration', {
guildId,
serverName,
timestamp: new Date().toISOString()
}); });
});
try {
// Log before database operation
this.logger.debug('Calling ServerRegistrationService.registerServer', {
guildId,
serverName,
timestamp: new Date().toISOString()
});
// Attempt the database operation first
const result = await this.serverRegistrationService.registerServer(guildId, serverName);
// Log the result immediately
this.logger.debug('Server registration result received', {
status: result.status,
serverId: result.server?.id,
guildId,
timestamp: new Date().toISOString()
});
// Only after successful database operation, send the response
try {
const message = result.status === 'exists'
? 'This server is already registered!'
: 'Server successfully registered! You can now use subscription commands.';
await interaction.editReply({
content: message,
ephemeral: true
});
// Log the successful operation
this.logger.info('Server registration completed', {
status: result.status,
guildId,
serverId: result.server.id,
timestamp: new Date().toISOString()
});
} catch (replyError) {
// Log that we couldn't send the response but the registration was successful
this.logger.warn('Could not send response, but server registration was successful', {
error: replyError.message,
guildId,
serverId: result.server.id,
timestamp: new Date().toISOString()
});
}
return result;
} catch (error) {
// Log the error but let Bot.js handle the error response
this.logger.error('Failed to register server:', {
error: error.message,
stack: error.stack,
guildId,
serverName,
timestamp: new Date().toISOString()
});
throw error;
}
} }
// Add teams if available async handleButton(interaction) {
const teams = playerData.teams; const [action, ...params] = interaction.customId.split(':');
if (teams && Object.keys(teams).length > 0) {
const teamList = Object.values(teams)
.map(team => `- **${team.team_name}** (${team.game_name} - ${team.game_mode})`)
.join('\n');
embed.addFields( switch (action) {
{ name: '\u200B', value: '**Teams**' }, case 'refresh':
{ name: 'Team List', value: teamList || 'No teams available' } await this.handleFindUser(interaction, params[0]);
); break;
default:
await interaction.editReply({
content: 'Unknown button interaction',
ephemeral: true
});
}
} }
// Add recent matches if available // Helper methods for creating embeds and action rows remain unchanged
const matches = playerData.matches; createUserEmbed(playerData, gameFilter) {
if (matches && Object.keys(matches).length > 0) { // ... (keep existing implementation)
const matchList = Object.values(matches)
.sort((a, b) => new Date(b.start_time) - new Date(a.start_time))
.slice(0, 3)
.map(match => {
const date = new Date(match.start_time).toLocaleDateString();
const team1 = match.team1_name || 'Team 1';
const team2 = match.team2_name || 'Team 2';
const score = match.score || 'N/A';
return `- **${team1}** vs **${team2}** on ${date} - Result: ${score}`;
})
.join('\n');
embed.addFields(
{ name: '\u200B', value: '**Recent Matches**' },
{ name: 'Match History', value: matchList || 'No recent matches' }
);
} }
return embed; createMatchHistoryEmbed(playerData, matches) {
} // ... (keep existing implementation)
createMatchHistoryEmbed(playerData, matches) {
const embed = new EmbedBuilder()
.setTitle(`Match History for ${playerData.username}`)
.setColor('#0099ff')
.setDescription(`Last ${matches.length} matches`);
if (playerData.profile?.avatar) {
embed.setThumbnail(
`https://www.vrbattles.gg/assets/uploads/profile/${playerData.profile.avatar}`
);
} }
// Add match stats createActionRow(username) {
const wins = matches.filter(m => { // ... (keep existing implementation)
const isTeam1 = m.team1_name === playerData.username; }
return m.winner_id === (isTeam1 ? "1" : "2");
}).length;
const winRate = ((wins / matches.length) * 100).toFixed(1);
embed.addFields(
{ name: 'Recent Win Rate', value: `${winRate}%`, inline: true },
{ name: 'Matches Analyzed', value: matches.length.toString(), inline: true },
{ name: 'Recent Wins', value: wins.toString(), inline: true }
);
// Add individual matches
matches.forEach((match, index) => {
const date = new Date(match.start_time).toLocaleDateString();
const isTeam1 = match.team1_name === playerData.username;
const opponent = isTeam1 ? match.team2_name : match.team1_name;
const won = match.winner_id === (isTeam1 ? "1" : "2");
const score = match.score || '0 - 0';
const gameMode = match.game_mode ? ` (${match.game_mode})` : '';
const matchResult = won ? '✅ Victory' : '❌ Defeat';
embed.addFields({
name: `Match ${index + 1} - ${matchResult}`,
value: `🎮 **${match.game_name}${gameMode}**\n` +
`🆚 vs ${opponent}\n` +
`📊 Score: ${score}\n` +
`📅 ${date}`,
inline: false
});
});
return embed;
}
createActionRow(username) {
return new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('🔵 View Profile')
.setStyle(ButtonStyle.Link)
.setURL(this.playerService.getProfileUrl(username)),
new ButtonBuilder()
.setLabel('🟡 Join Main Discord')
.setStyle(ButtonStyle.Link)
.setURL('https://discord.gg/j3DKVATPGQ')
);
}
} }
module.exports = CommandHandler; module.exports = CommandHandler;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,82 @@
class ServerRegistrationService {
constructor(supabase, logger) {
this.supabase = supabase;
this.logger = logger;
// Log when service is instantiated
this.logger.info('ServerRegistrationService initialized');
}
async registerServer(guildId, serverName) {
// Add entry point log
this.logger.info('registerServer method called', {
guildId,
serverName,
timestamp: new Date().toISOString()
});
try {
this.logger.debug('Starting server registration process', {
guildId,
serverName,
timestamp: new Date().toISOString()
});
const { data: existingServer, error: checkError } = await this.supabase
.from('servers')
.select('*')
.eq('discord_server_id', guildId)
.single();
// Log the database query result
this.logger.debug('Database query result', {
hasExistingServer: !!existingServer,
hasError: !!checkError,
errorCode: checkError?.code
});
if (existingServer) {
this.logger.info('Server already exists', {
serverId: existingServer.id,
guildId
});
return { status: 'exists', server: existingServer };
}
if (!existingServer || checkError?.code === 'PGRST116') {
this.logger.debug('Attempting to create new server');
const { data: newServer, error: insertError } = await this.supabase
.from('servers')
.insert([{
discord_server_id: guildId,
server_name: serverName,
active: true
}])
.select()
.single();
if (insertError) {
this.logger.error('Failed to insert new server', { error: insertError });
throw insertError;
}
this.logger.info('New server created successfully', {
serverId: newServer.id,
guildId
});
return { status: 'created', server: newServer };
}
throw checkError;
} catch (error) {
this.logger.error('Error in registerServer:', {
error: error.message,
stack: error.stack,
guildId,
serverName
});
throw error;
}
}
}
module.exports = ServerRegistrationService;

View File

@@ -1,142 +1,370 @@
const { createClient } = require('@supabase/supabase-js'); const { createClient } = require('@supabase/supabase-js');
const Logger = require('../utils/Logger');
class SupabaseService { class SupabaseService {
constructor() { constructor() {
this.logger = new Logger('SupabaseService');
const supabaseUrl = process.env.SUPABASE_URL; const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY; const supabaseKey = process.env.SUPABASE_KEY;
if (!supabaseUrl || !supabaseKey) { if (!supabaseUrl || !supabaseKey) {
console.error('Supabase URL or key is missing. Please check your .env file.'); this.logger.error('Missing configuration', {
hasUrl: !!supabaseUrl,
hasKey: !!supabaseKey
});
this.supabase = null; this.supabase = null;
} else { } else {
this.supabase = createClient(supabaseUrl, supabaseKey); this.supabase = createClient(supabaseUrl, supabaseKey);
this.logger.debug('Supabase client created');
} }
} }
async testConnection() { async testConnection() {
if (!this.supabase) { if (!this.supabase) {
console.error('Supabase client is not initialized.'); this.logger.error('Client not initialized');
return false; return false;
} }
try { try {
const { data, error } = await this.supabase this.logger.debug('Testing database connection...');
// Test servers table
const { data: serverTest, error: serverError } = await this.supabase
.from('servers')
.select('count')
.limit(1);
if (serverError) {
this.logger.error('Server table test failed:', serverError);
return false;
}
// Test games table
const { data: gameTest, error: gameError } = await this.supabase
.from('games') .from('games')
.select('count') .select('count')
.limit(1); .limit(1);
if (error) { if (gameError) {
console.error('Supabase connection test error:', error); this.logger.error('Games table test failed:', gameError);
return false; return false;
} }
console.log('Supabase connection successful'); this.logger.info('Database connection successful');
return true; return true;
} catch (error) { } catch (error) {
console.error('Supabase connection test failed:', error); this.logger.error('Connection test failed:', {
error: error.message,
stack: error.stack
});
return false; return false;
} }
} }
async ensureServerRegistered(guildId, serverName) {
try {
this.logger.debug('Ensuring server is registered', { guildId, serverName });
// Try to find existing server
const { data: existingServer, error: fetchError } = await this.supabase
.from('servers')
.select('*')
.eq('discord_server_id', guildId)
.single();
// If server exists, return it
if (existingServer) {
this.logger.debug('Server already registered', {
serverId: existingServer.id,
guildId,
serverName: existingServer.server_name
});
return existingServer;
}
// If server doesn't exist, create it
this.logger.debug('Registering new server', { guildId, serverName });
const { data: newServer, error: insertError } = await this.supabase
.from('servers')
.insert([{
discord_server_id: guildId,
server_name: serverName,
active: true
}])
.select()
.single();
if (insertError) {
this.logger.error('Failed to register server', {
error: insertError,
guildId,
serverName
});
throw insertError;
}
this.logger.info('New server registered successfully', {
serverId: newServer.id,
guildId,
serverName
});
return newServer;
} catch (error) {
this.logger.error('Error in ensureServerRegistered:', {
error: error.message,
stack: error.stack,
guildId,
serverName
});
throw error;
}
}
// Update the addSubscription method to use ensureServerRegistered
async addSubscription(guildId, gameName, channelId, serverName) {
if (!this.supabase) {
this.logger.error('Client not initialized');
return null;
}
try {
this.logger.debug('Adding subscription', { guildId, gameName, channelId });
// Ensure server is registered
const server = await this.ensureServerRegistered(guildId, serverName);
if (!server) {
throw new Error('Failed to ensure server registration');
}
// Get game ID
const { data: gameData, error: gameError } = await this.supabase
.from('games')
.select('id')
.eq('name', gameName)
.eq('active', true)
.single();
if (gameError) {
this.logger.error('Game fetch error:', { gameError, gameName });
throw gameError;
}
// Create subscription
const { data, error } = await this.supabase
.from('server_game_preferences')
.upsert({
server_id: server.id,
game_id: gameData.id,
notification_channel_id: channelId
}, {
onConflict: '(server_id,game_id)',
returning: true
});
if (error) {
this.logger.error('Subscription upsert error:', { error });
throw error;
}
this.logger.debug('Subscription added successfully', {
serverId: server.id,
gameId: gameData.id,
channelId
});
return data;
} catch (error) {
this.logger.error('Error in addSubscription:', {
error: error.message,
stack: error.stack,
guildId,
gameName
});
throw error;
}
}
async getSubscriptions(guildId) { async getSubscriptions(guildId) {
if (!this.supabase) { if (!this.supabase) {
console.error('Supabase client is not initialized.'); this.logger.error('Client not initialized');
return []; return [];
} }
const { data, error } = await this.supabase try {
.from('server_game_preferences') this.logger.debug('Fetching subscriptions', { guildId });
.select(`
games (name),
notification_channel_id,
servers!inner (discord_server_id)
`)
.eq('servers.discord_server_id', guildId);
if (error) throw error; const { data, error } = await this.supabase
return data; .from('server_game_preferences')
.select(`
games (name),
notification_channel_id,
servers!inner (discord_server_id)
`)
.eq('servers.discord_server_id', guildId);
if (error) {
this.logger.error('Error fetching subscriptions:', { error, guildId });
throw error;
}
this.logger.debug('Subscriptions fetched', {
count: data?.length || 0,
guildId
});
return data || [];
} catch (error) {
this.logger.error('Error in getSubscriptions:', {
error: error.message,
stack: error.stack,
guildId
});
throw error;
}
} }
async addSubscription(guildId, gameName, channelId) { async addSubscription(guildId, gameName, channelId) {
if (!this.supabase) { if (!this.supabase) {
console.error('Supabase client is not initialized.'); this.logger.error('Client not initialized');
return null; return null;
} }
// First, get or create server record try {
const { data: serverData, error: serverError } = await this.supabase this.logger.debug('Adding subscription', { guildId, gameName, channelId });
.from('servers')
.upsert({ // First, get or create server record
discord_server_id: guildId const { data: serverData, error: serverError } = await this.supabase
}, { .from('servers')
onConflict: 'discord_server_id', .upsert({
returning: true discord_server_id: guildId,
active: true
}, {
onConflict: 'discord_server_id',
returning: true
});
if (serverError) {
this.logger.error('Server upsert error:', { serverError, guildId });
throw serverError;
}
if (!serverData || serverData.length === 0) {
this.logger.error('Server creation failed - no data returned', { guildId });
throw new Error('Server creation failed');
}
// Get game ID
const { data: gameData, error: gameError } = await this.supabase
.from('games')
.select('id')
.eq('name', gameName)
.eq('active', true)
.single();
if (gameError) {
this.logger.error('Game fetch error:', { gameError, gameName });
throw gameError;
}
// Create subscription
const { data, error } = await this.supabase
.from('server_game_preferences')
.upsert({
server_id: serverData[0].id,
game_id: gameData.id,
notification_channel_id: channelId
}, {
onConflict: '(server_id,game_id)',
returning: true
});
if (error) {
this.logger.error('Subscription upsert error:', { error });
throw error;
}
this.logger.debug('Subscription added successfully', {
serverId: serverData[0].id,
gameId: gameData.id,
channelId
}); });
if (serverError) throw serverError; return data;
} catch (error) {
// Get game ID this.logger.error('Error in addSubscription:', {
const { data: gameData, error: gameError } = await this.supabase error: error.message,
.from('games') stack: error.stack,
.select('id') guildId,
.eq('name', gameName) gameName
.eq('active', true)
.single();
if (gameError) throw gameError;
// Create subscription
const { data, error } = await this.supabase
.from('server_game_preferences')
.upsert({
server_id: serverData[0].id,
game_id: gameData.id,
notification_channel_id: channelId
}, {
onConflict: '(server_id,game_id)',
returning: true
}); });
throw error;
if (error) throw error; }
return data;
} }
async removeSubscription(guildId, gameName) { async removeSubscription(guildId, gameName) {
if (!this.supabase) { if (!this.supabase) {
console.error('Supabase client is not initialized.'); this.logger.error('Client not initialized');
return null; return null;
} }
// Get server ID try {
const { data: serverData, error: serverError } = await this.supabase this.logger.debug('Removing subscription', { guildId, gameName });
.from('servers')
.select('id')
.eq('discord_server_id', guildId)
.single();
if (serverError) throw serverError; // Get server ID
const { data: serverData, error: serverError } = await this.supabase
.from('servers')
.select('id')
.eq('discord_server_id', guildId)
.single();
// Get game ID if (serverError) {
const { data: gameData, error: gameError } = await this.supabase this.logger.error('Server fetch error:', { serverError, guildId });
.from('games') throw serverError;
.select('id') }
.eq('name', gameName)
.single();
if (gameError) throw gameError; // Get game ID
const { data: gameData, error: gameError } = await this.supabase
.from('games')
.select('id')
.eq('name', gameName)
.single();
// Delete subscription if (gameError) {
const { data, error } = await this.supabase this.logger.error('Game fetch error:', { gameError, gameName });
.from('server_game_preferences') throw gameError;
.delete() }
.match({
server_id: serverData.id,
game_id: gameData.id
})
.single();
if (error) throw error; // Delete subscription
return data; const { data, error } = await this.supabase
.from('server_game_preferences')
.delete()
.match({
server_id: serverData.id,
game_id: gameData.id
})
.single();
if (error) {
this.logger.error('Subscription deletion error:', { error });
throw error;
}
this.logger.debug('Subscription removed successfully', {
serverId: serverData.id,
gameId: gameData.id
});
return data;
} catch (error) {
this.logger.error('Error in removeSubscription:', {
error: error.message,
stack: error.stack,
guildId,
gameName
});
throw error;
}
} }
getClient() { getClient() {