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,89 +1,105 @@
const { REST, Routes, SlashCommandBuilder } = require('discord.js');
require('dotenv').config();
const { REST, Routes, SlashCommandBuilder, PermissionFlagsBits } = require("discord.js");
require("dotenv").config();
const commands = [
new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
.setName("ping")
.setDescription("Replies with Pong!"),
new SlashCommandBuilder()
.setName('finduser')
.setDescription('Find a user by username')
.addStringOption(option =>
option.setName('username')
.setDescription('The username to search for')
.setRequired(true))
.addStringOption(option =>
option.setName('game')
.setDescription('Specify a game to view stats for')
.setRequired(false)),
.setName("finduser")
.setDescription("Find a user by username")
.addStringOption((option) =>
option
.setName("username")
.setDescription("The username to search for")
.setRequired(true)
)
.addStringOption((option) =>
option
.setName("game")
.setDescription("Specify a game to view stats for")
.setRequired(false)
),
new SlashCommandBuilder()
.setName('matchhistory')
.setDescription('View match history')
.addStringOption(option =>
option.setName('username')
.setDescription('The username to search for')
.setRequired(true))
.addStringOption(option =>
option.setName('game')
.setDescription('Filter by game')
.setRequired(false)),
// New subscription commands
.setName("matchhistory")
.setDescription("View match history")
.addStringOption((option) =>
option
.setName("username")
.setDescription("The username to search for")
.setRequired(true)
)
.addStringOption((option) =>
option.setName("game").setDescription("Filter by game").setRequired(false)
),
new SlashCommandBuilder()
.setName('subscribe')
.setDescription('Subscribe to game notifications')
.addStringOption(option =>
option.setName('game')
.setDescription('Game to subscribe to')
.setName("subscribe")
.setDescription("Subscribe to game notifications")
.addStringOption((option) =>
option
.setName("game")
.setDescription("Game to subscribe to")
.setRequired(true)
.addChoices(
{ name: 'Big Ballers VR', value: 'Big Ballers VR' },
{ name: 'Blacktop Hoops', value: 'Blacktop Hoops' },
{ 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' }
))
.addChannelOption(option =>
option.setName('channel')
.setDescription('Channel for notifications')
.setRequired(true)),
{ name: "Big Ballers VR", value: "Big Ballers VR" },
{ name: "Blacktop Hoops", value: "Blacktop Hoops" },
{ 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" }
)
)
.addChannelOption((option) =>
option
.setName("channel")
.setDescription("Channel for notifications")
.setRequired(true)
),
new SlashCommandBuilder()
.setName('unsubscribe')
.setDescription('Unsubscribe from game notifications')
.addStringOption(option =>
option.setName('game')
.setDescription('Game to unsubscribe from')
.setName("unsubscribe")
.setDescription("Unsubscribe from game notifications")
.addStringOption((option) =>
option
.setName("game")
.setDescription("Game to unsubscribe from")
.setRequired(true)
.addChoices(
{ name: 'Big Ballers VR', value: 'Big Ballers VR' },
{ name: 'Blacktop Hoops', value: 'Blacktop Hoops' },
{ 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' }
)),
{ name: "Big Ballers VR", value: "Big Ballers VR" },
{ name: "Blacktop Hoops", value: "Blacktop Hoops" },
{ 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('list_subscriptions')
.setDescription('List all game subscriptions for this server')
.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 () => {
try {
console.log('Started refreshing application (/) commands.');
console.log('Commands to be deployed:', commands.map(cmd => cmd.name));
await rest.put(
Routes.applicationCommands(process.env.CLIENT_ID),
{ body: commands.map(command => command.toJSON()) },
console.log("Started refreshing application (/) commands.");
console.log(
"Commands to be deployed:",
commands.map((cmd) => cmd.name)
);
console.log('Successfully reloaded application (/) commands.');
await rest.put(Routes.applicationCommands(process.env.CLIENT_ID), {
body: commands.map((command) => command.toJSON()),
});
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}

View File

@@ -1,9 +1,57 @@
// index.js
require('dotenv').config();
const winston = require('winston');
const { createClient } = require('@supabase/supabase-js');
const Bot = require('./src/Bot');
require('dotenv').config();
const bot = new Bot();
bot.start(process.env.BOT_TOKEN).catch(error => {
// Initialize logger
const logger = winston.createLogger({
level: 'debug',
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,
"requires": true,
"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": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.9.0.tgz",
@@ -259,6 +279,12 @@
"integrity": "sha512-xegpDuR+z0UqG9fwHqNoy3rI7JDlvaPh2TY47Fl80oq6g+hXT+c/LEuE43X48clZ6lOfANl5WrPur9fYO1RJ/w==",
"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": {
"version": "8.5.12",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz",
@@ -297,6 +323,12 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"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": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -366,6 +398,51 @@
"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": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -518,6 +595,12 @@
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"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": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
@@ -611,6 +694,12 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"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": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
@@ -629,6 +718,12 @@
"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": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
@@ -812,6 +907,30 @@
"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": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
@@ -824,6 +943,29 @@
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
"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": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz",
@@ -929,6 +1071,15 @@
"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": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -1002,6 +1153,20 @@
"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": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -1022,6 +1187,15 @@
],
"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": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -1123,6 +1297,24 @@
"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": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
@@ -1132,6 +1324,21 @@
"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": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@@ -1147,6 +1354,15 @@
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"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": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
@@ -1196,6 +1412,12 @@
"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": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -1230,6 +1452,42 @@
"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": {
"version": "8.18.0",
"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",
"dotenv": "^16.4.5",
"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": {
@@ -272,6 +293,12 @@
"integrity": "sha512-xegpDuR+z0UqG9fwHqNoy3rI7JDlvaPh2TY47Fl80oq6g+hXT+c/LEuE43X48clZ6lOfANl5WrPur9fYO1RJ/w==",
"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": {
"version": "8.5.12",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz",
@@ -310,6 +337,12 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"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": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -379,6 +412,51 @@
"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": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -531,6 +609,12 @@
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"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": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
@@ -624,6 +708,12 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"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": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
@@ -642,6 +732,12 @@
"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": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
@@ -825,6 +921,30 @@
"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": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
@@ -837,6 +957,29 @@
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
"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": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.10.0.tgz",
@@ -942,6 +1085,15 @@
"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": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -1015,6 +1167,20 @@
"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": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -1035,6 +1201,15 @@
],
"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": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -1136,6 +1311,24 @@
"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": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
@@ -1145,6 +1338,21 @@
"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": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@@ -1160,6 +1368,15 @@
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"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": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
@@ -1209,6 +1426,12 @@
"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": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -1243,6 +1466,42 @@
"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": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",

View File

@@ -16,6 +16,7 @@
"discord.js": "^14.16.2",
"dotenv": "^16.4.5",
"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 CommandHandler = require("./commands/CommandHandler.js");
const PlayerService = require("./services/PlayerService.js");
const NotificationService = require("./services/NotificationService.js");
const MatchCommands = require("./commands/MatchCommands.js");
const SupabaseService = require("./services/SupabaseService.js");
const SubscriptionCommands = require("./commands/SubscriptionCommands.js");
const CooldownManager = require("./utils/CooldownManager.js");
const Logger = require("./utils/Logger.js");
const { Client, GatewayIntentBits } = require('discord.js');
const CommandHandler = require('./commands/CommandHandler');
const SubscriptionCommands = require('./commands/SubscriptionCommands');
const PlayerService = require('./services/PlayerService');
const SupabaseService = require('./services/SupabaseService');
const NotificationService = require('./services/NotificationService');
const Logger = require('./utils/Logger');
const ServerRegistrationService = require('./services/ServerRegistrationService');
class Bot {
constructor() {
this.logger = new Logger('Bot');
this.cooldownManager = new CooldownManager();
constructor(token, supabase, logger) {
if (!logger || typeof logger.error !== 'function') {
throw new Error('Invalid logger provided to Bot constructor');
}
this.client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
this.client = new Client({ intents: [GatewayIntentBits.Guilds] });
this.token = token;
this.supabase = supabase;
this.logger = logger;
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));
}
async start(token) {
this.logger.info('Starting bot...');
async start() {
try {
await this.client.login(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}`);
await this.client.login(this.token);
} catch (error) {
this.logger.error('Startup failed:', error);
this.logger.error('Failed to start bot:', error);
throw error;
}
}
async stop() {
this.logger.info('Stopping bot...');
try {
await this.notificationService.stop();
await this.client.destroy();
this.logger.info('Bot stopped successfully');
} catch (error) {
this.logger.error('Error stopping bot:', error);
throw error;
}
}
handleError(error) {
this.logger.error('Discord client error:', error);
}
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) {
try {
// Check cooldown
const cooldownTime = this.cooldownManager.checkCooldown(interaction);
if (cooldownTime > 0) {
await interaction.reply({
content: `Please wait ${cooldownTime.toFixed(1)} more seconds before using this command again.`,
ephemeral: true
});
async handleInteraction(interaction) {
if (!interaction.isCommand() && !interaction.isButton()) {
this.logger.debug('Ignoring non-command/button interaction');
return;
}
this.logger.debug('Processing command', {
command: interaction.commandName,
user: interaction.user.tag
});
await this.processCommand(interaction);
} catch (error) {
this.logger.error('Command error:', error);
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) {
if (!this.subscriptionCommands) {
await this.safeReply(interaction, "Subscription commands are not available.");
const lockKey = interaction.id;
if (this.processingLock.get(lockKey)) {
this.logger.debug('Interaction already being processed', { id: lockKey });
return;
}
try {
// Defer the reply immediately
await this.safeReply(interaction, "Processing your request...");
switch (interaction.commandName) {
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_");
// Set the lock before any async operations
this.processingLock.set(lockKey, true);
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 });
// Special handling for register_server command
if (interaction.isCommand() && interaction.commandName === 'register_server') {
// Send initial response immediately
await interaction.reply({
content: "Unknown button action",
ephemeral: true,
});
}
} catch (error) {
this.logger.error("Error handling button:", error);
await this.handleInteractionError(interaction, error);
}
}
async handleCommandError(interaction, error) {
this.logger.error('Command error:', error);
try {
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content: 'An error occurred while processing your command.',
content: 'Attempting to register server...',
ephemeral: true
});
} 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);
}
}
const guildId = interaction.guildId;
const serverName = interaction.guild.name;
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
this.logger.debug('Starting server registration', {
guildId,
serverName,
timestamp: new Date().toISOString()
});
} else if (interaction.deferred && !interaction.replied) {
try {
// Attempt database operation first
const result = await this.serverRegistrationService.registerServer(guildId, serverName);
this.logger.info('Server registration database operation completed', {
status: result.status,
guildId,
serverId: result.server.id,
timestamp: new Date().toISOString()
});
// 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: 'An error occurred while processing your request.'
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
});
}
} catch (e) {
this.logger.error('Error sending error message:', e);
} 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) {
this.logger.error('Command processing error:', {
error: error.message,
stack: error.stack,
command: interaction.commandName,
guild: interaction.guild?.name,
timestamp: new Date().toISOString()
});
} finally {
this.processingLock.delete(lockKey);
this.logger.debug('Interaction processing completed', {
id: lockKey,
command: interaction.commandName,
timestamp: new Date().toISOString()
});
}
}
}

View File

@@ -1,234 +1,145 @@
// src/commands/CommandHandler.js
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
class CommandHandler {
constructor(playerService) {
constructor(playerService, supabase, logger, serverRegistrationService) {
this.playerService = playerService;
this.supabase = supabase;
this.logger = logger;
this.serverRegistrationService = serverRegistrationService;
}
async handlePing(interaction) {
await interaction.reply('Pong!');
async handleCommand(interaction) {
try {
switch (interaction.commandName) {
case 'register_server':
await this.handleRegisterServer(interaction);
break;
case 'ping':
await interaction.editReply({ content: 'Pong!', ephemeral: true });
break;
case 'finduser':
await this.handleFindUser(interaction);
break;
case 'matchhistory':
await this.handleMatchHistory(interaction);
break;
default:
await interaction.editReply({ content: 'Unknown command', ephemeral: true });
}
} catch (error) {
// Only log the error, let Bot class handle the response
this.logger.error('Command handling error:', {
command: interaction.commandName,
error: error.message,
stack: error.stack
});
throw error; // Re-throw to let Bot handle it
}
}
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.');
async handleRegisterServer(interaction) {
if (!interaction.deferred) {
this.logger.warn('Interaction not deferred, cannot proceed', {
guildId: interaction.guildId
});
return;
}
const playerData = typeof userData.player_data === 'string'
? JSON.parse(userData.player_data)
: userData.player_data;
// Get the server details first
const guildId = interaction.guildId;
const serverName = interaction.guild.name;
const embed = await this.createUserEmbed(playerData, gameFilter);
const row = this.createActionRow(playerData.username);
await interaction.editReply({ embeds: [embed], components: [row] });
}
async handleMatchHistory(interaction) {
await interaction.deferReply();
const username = interaction.options.getString('username');
const gameFilter = interaction.options.getString('game');
this.logger.debug('Starting server registration', {
guildId,
serverName,
timestamp: new Date().toISOString()
});
try {
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;
// 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()
});
}
const playerData = typeof userData.player_data === 'string'
? 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] });
return result;
} catch (error) {
console.error('Error in handleMatchHistory:', error);
await interaction.editReply('An error occurred while processing the match history.');
// 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;
}
}
async handleButton(interaction) {
const [action, ...params] = interaction.customId.split(':');
switch (action) {
case 'refresh':
await this.handleFindUser(interaction, params[0]);
break;
default:
await interaction.editReply({
content: 'Unknown button interaction',
ephemeral: true
});
}
}
// Helper methods for creating embeds and action rows remain unchanged
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
});
}
});
});
}
// Add teams if available
const teams = playerData.teams;
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(
{ name: '\u200B', value: '**Teams**' },
{ name: 'Team List', value: teamList || 'No teams available' }
);
}
// Add recent matches if available
const matches = playerData.matches;
if (matches && Object.keys(matches).length > 0) {
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;
// ... (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
const wins = matches.filter(m => {
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;
// ... (keep existing implementation)
}
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')
);
// ... (keep existing implementation)
}
}

View File

@@ -1,152 +1,387 @@
const { EmbedBuilder } = require('discord.js');
const Logger = require('../utils/Logger');
const { EmbedBuilder } = require("discord.js");
const Logger = require("../utils/Logger");
class SubscriptionCommands {
constructor(supabaseService) {
this.supabase = supabaseService.getClient();
this.logger = new Logger('SubscriptionCommands');
constructor(supabase, supabaseService) {
this.logger = new Logger("SubscriptionCommands");
this.supabase = supabase;
this.supabaseService = supabaseService;
if (!this.supabase) {
throw new Error('Supabase client not initialized');
throw new Error("Supabase client not initialized");
}
}
async handleSubscribe(interaction) {
try {
const gameName = this.sanitizeInput(interaction.options.getString('game'));
const channel = interaction.options.getChannel('channel');
const guildId = interaction.guildId;
const serverName = this.sanitizeInput(interaction.guild.name);
if (!gameName || gameName.length === 0) {
await this.safeReply(interaction, 'Invalid game name provided.');
// Verify interaction is already deferred
if (!interaction.deferred) {
this.logger.warn("Interaction not deferred before handleSubscribe");
return;
}
this.logger.debug('Processing subscription request', {
game: gameName,
channel: channel.name,
const gameName = this.sanitizeInput(
interaction.options.getString("game")
);
const channel = interaction.options.getChannel("channel");
const guildId = interaction.guildId;
const serverName = this.sanitizeInput(interaction.guild.name);
this.logger.debug("Starting subscription process", {
gameName,
channelId: channel?.id,
guildId,
serverName,
});
// Get or create the server
const serverId = await this.getOrCreateServer(guildId, serverName);
if (!serverId) {
await this.safeReply(interaction, 'Failed to register or retrieve server. Please try again later.');
// Input validation
if (!gameName || gameName.length === 0) {
await interaction.editReply("Invalid game name provided.");
return;
}
// Fetch the game
if (!channel) {
await interaction.editReply("Invalid channel selected.");
return;
}
// Get or create server
let server;
try {
server = await this.getOrCreateServer(guildId, serverName);
} catch (error) {
this.logger.error("Failed to get/create server", {
error: error.message,
guildId,
serverName,
});
await interaction.editReply(
"Failed to register server. Please try again later."
);
return;
}
// Get game data
const gameData = await this.getGame(gameName);
if (!gameData) {
await this.safeReply(interaction, `Game "${gameName}" not found or inactive.`);
await interaction.editReply(
`Game "${gameName}" not found or is not currently supported.`
);
return;
}
// Check for existing subscription
const existingSubscription = await this.verifySubscription(
server.id,
gameData.id
);
// Create or update subscription
const subscriptionResult = await this.createOrUpdateSubscription(serverId, gameData.id, channel.id);
const subscriptionResult = await this.createOrUpdateSubscription(
server.id,
gameData.id,
channel.id
);
if (!subscriptionResult) {
await this.safeReply(interaction, 'Failed to save subscription. Please try again later.');
await interaction.editReply(
"Failed to save subscription. Please try again later."
);
return;
}
// Success response
this.logger.debug('Subscription created successfully', { gameName, channelId: channel.id, guildId: interaction.guildId });
await this.safeReply(interaction, `Successfully subscribed to ${gameName} notifications in ${channel}.`);
const successMessage = existingSubscription
? `Updated subscription for ${gameName} to channel ${channel}.`
: `Successfully subscribed to ${gameName} notifications in ${channel}.`;
await interaction.editReply(successMessage);
} catch (error) {
this.logger.error('Error in handleSubscribe:', { error, stack: error.stack });
await this.safeReply(interaction, 'An unexpected error occurred. Please try again later.');
this.logger.error("Error in handleSubscribe:", {
error: error.message,
stack: error.stack,
interaction: {
guildId: interaction.guildId,
channelId: interaction.channelId,
}
});
if (interaction.deferred && !interaction.replied) {
await interaction.editReply(
"An unexpected error occurred. Please try again later."
);
}
}
}
// Helper methods
async checkExistingSubscription(serverId, gameId) {
try {
const { data, error } = await this.supabase
.from("server_game_preferences")
.select("*")
.eq("server_id", serverId)
.eq("game_id", gameId)
.single();
if (error && error.code !== "PGRST116") {
// PGRST116 is "no rows returned"
this.logger.error("Error checking existing subscription:", error);
return null;
}
return data;
} catch (error) {
this.logger.error("Error in checkExistingSubscription:", {
error: error.message,
stack: error.stack,
});
return null;
}
}
async verifySubscription(serverId, gameId) {
try {
const { data, error } = await this.supabase
.from("server_game_preferences")
.select("*")
.eq("server_id", serverId)
.eq("game_id", gameId)
.single();
if (error) {
if (error.code === "PGRST116") {
// No rows found is not an error in this context
this.logger.debug("No existing subscription found", {
serverId,
gameId
});
return null;
}
this.logger.error("Error verifying subscription:", error);
return null;
}
return data;
} catch (error) {
this.logger.error("Error in verifySubscription:", {
error: error.message,
stack: error.stack,
});
return null;
}
}
async handleUnsubscribe(interaction) {
try {
const gameName = this.sanitizeInput(interaction.options.getString('game'));
const gameName = this.sanitizeInput(
interaction.options.getString("game")
);
const guildId = interaction.guildId;
if (!gameName || gameName.length === 0) {
await this.safeReply(interaction, 'Invalid game name provided.');
await this.safeReply(interaction, "Invalid game name provided.");
return;
}
this.logger.debug('Processing unsubscribe request', { game: gameName, guildId });
this.logger.debug("Processing unsubscribe request", {
game: gameName,
guildId,
});
const subscription = await this.fetchSubscription(guildId, gameName);
if (!subscription) {
await this.safeReply(interaction, `No subscription found for ${gameName}.`);
await this.safeReply(
interaction,
`No subscription found for ${gameName}.`
);
return;
}
this.logger.debug('Subscription to delete', { subscription });
this.logger.debug("Subscription to delete", { subscription });
const success = await this.deleteSubscription(subscription);
if (success) {
await this.safeReply(interaction, `Successfully unsubscribed from ${gameName} notifications.`);
await this.safeReply(
interaction,
`Successfully unsubscribed from ${gameName} notifications.`
);
} else {
await this.safeReply(interaction, `Failed to unsubscribe from ${gameName} notifications. Please try again later.`);
await this.safeReply(
interaction,
`Failed to unsubscribe from ${gameName} notifications. Please try again later.`
);
}
} catch (error) {
this.logger.error('Error in handleUnsubscribe:', { error, stack: error.stack });
await this.safeReply(interaction, 'An unexpected error occurred. Please try again later.');
this.logger.error("Error in handleUnsubscribe:", {
error,
stack: error.stack,
});
await this.safeReply(
interaction,
"An unexpected error occurred. Please try again later."
);
}
}
async handleListSubscriptions(interaction) {
try {
// Defer the reply first
await interaction.deferReply({ ephemeral: true });
const guildId = interaction.guildId;
this.logger.debug("Fetching subscriptions", { guildId });
this.logger.debug('Fetching subscriptions', { guildId });
const subscriptions = await this.getSubscriptions(guildId, interaction);
const subscriptions = await this.getSubscriptions(guildId);
if (!subscriptions || subscriptions.length === 0) {
await interaction.editReply('This server has no game subscriptions.');
await interaction.editReply("This server has no game subscriptions.");
return;
}
const embed = this.buildSubscriptionsEmbed(subscriptions);
await interaction.editReply({ embeds: [embed] });
} catch (error) {
this.handleError('handleListSubscriptions', error, interaction);
}
}
this.logger.error("Error in handleListSubscriptions:", {
error,
stack: error.stack,
message: error.message,
});
// Helper Methods
async getOrCreateServer(guildId, serverName) {
try {
const { data: existingServer, error: checkError } = await this.supabase
.from('servers')
.select('id')
.eq('discord_server_id', guildId)
.single();
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content: "An error occurred while fetching subscriptions.",
ephemeral: true,
});
} else if (interaction.deferred) {
await interaction.editReply(
"An error occurred while fetching subscriptions."
);
}
} catch (e) {
this.logger.error("Error sending error message:", e);
}
}
}
if (checkError) {
this.logger.error('Error fetching server:', { checkError });
// Also update the getSubscriptions method to remove the interaction parameter
async getSubscriptions(guildId) {
const { data: subscriptions, error } = await this.supabase
.from("active_subscriptions")
.select("*")
.eq("discord_server_id", guildId);
if (error) {
this.logger.error("Error fetching subscriptions", { error });
return null;
}
if (existingServer) return existingServer.id;
return subscriptions;
}
// Helper Methods
async testSupabaseConnection() {
try {
const { data, error } = await this.supabase
.from("servers")
.select("id")
.limit(1);
if (error) {
this.logger.error("Supabase connection test failed:", { error });
return false;
}
this.logger.debug("Supabase connection test successful", { data });
return true;
} catch (error) {
this.logger.error("Unexpected error in Supabase connection test:", {
error,
stack: error.stack,
});
return false;
}
}
async getOrCreateServer(guildId, serverName) {
try {
this.logger.debug("Starting getOrCreateServer", {
guildId,
serverName,
timestamp: new Date().toISOString(),
});
// First attempt to get existing server
const { data: existingServer, error: checkError } = await this.supabase
.from("servers")
.select("*")
.eq("discord_server_id", guildId)
.single();
this.logger.debug("Server lookup result", {
exists: !!existingServer,
error: checkError ? {
message: checkError.message,
code: checkError.code,
details: checkError.details,
} : null,
});
// If server exists and is active, return it
if (existingServer) {
this.logger.debug("Using existing server", {
serverId: existingServer.id,
serverDetails: existingServer,
});
return existingServer;
}
// If no server exists, create one with exact schema match
const { data: newServer, error: insertError } = await this.supabase
.from('servers')
.insert({
.from("servers")
.insert([
{
discord_server_id: guildId,
server_name: serverName,
active: true
})
active: true,
// created_at will be handled by Supabase automatically
}
])
.select()
.single();
if (insertError) {
this.logger.error('Error creating server:', { insertError });
return null;
this.logger.error("Server creation failed", {
error: insertError,
details: {
code: insertError.code,
message: insertError.message,
},
attemptedData: { guildId, serverName },
});
throw new Error(`Failed to create server: ${insertError.message}`);
}
return newServer.id;
this.logger.info("New server created successfully", {
serverId: newServer.id,
serverDetails: newServer,
});
return newServer;
} catch (error) {
this.logger.error('Error in getOrCreateServer:', { error, stack: error.stack });
return null;
this.logger.error("Unexpected error in getOrCreateServer", {
error: error.message,
stack: error.stack,
guildId,
serverName,
});
throw error;
}
}
@@ -154,20 +389,23 @@ class SubscriptionCommands {
try {
const sanitizedGameName = this.sanitizeInput(gameName);
const { data: gameData, error: gameError } = await this.supabase
.from('games')
.select('id, name')
.eq('name', sanitizedGameName)
.eq('active', true)
.from("games")
.select("id, name")
.eq("name", sanitizedGameName)
.eq("active", true)
.single();
if (gameError || !gameData) {
this.logger.error('Error fetching game data:', { gameError, gameName: sanitizedGameName });
this.logger.error("Error fetching game data:", {
gameError,
gameName: sanitizedGameName,
});
return null;
}
return gameData;
} catch (error) {
this.logger.error('Error in getGame:', { error, stack: error.stack });
this.logger.error("Error in getGame:", { error, stack: error.stack });
return null;
}
}
@@ -175,21 +413,33 @@ class SubscriptionCommands {
async createOrUpdateSubscription(serverId, gameId, channelId) {
try {
const { data: prefData, error: prefError } = await this.supabase
.from('server_game_preferences')
.from("server_game_preferences")
.upsert(
{ server_id: serverId, game_id: gameId, notification_channel_id: channelId },
{ onConflict: 'server_id,game_id' }
{
server_id: serverId,
game_id: gameId,
notification_channel_id: channelId,
},
{ onConflict: "server_id,game_id" }
)
.select();
if (prefError) {
this.logger.error('Error creating/updating subscription:', { prefError, serverId, gameId, channelId });
this.logger.error("Error creating/updating subscription:", {
prefError,
serverId,
gameId,
channelId,
});
return null;
}
return prefData;
} catch (error) {
this.logger.error('Error in createOrUpdateSubscription:', { error, stack: error.stack });
this.logger.error("Error in createOrUpdateSubscription:", {
error,
stack: error.stack,
});
return null;
}
}
@@ -197,20 +447,20 @@ class SubscriptionCommands {
async getGame(gameName, interaction) {
try {
const { data: gameData, error: gameError } = await this.supabase
.from('games')
.select('id, name')
.eq('name', gameName)
.eq('active', true)
.from("games")
.select("id, name")
.eq("name", gameName)
.eq("active", true)
.single();
if (gameError || !gameData) {
this.logger.error('Error fetching game data:', { gameError, gameName });
this.logger.error("Error fetching game data:", { gameError, gameName });
return null;
}
return gameData;
} catch (error) {
this.logger.error('Error in getGame:', { error, stack: error.stack });
this.logger.error("Error in getGame:", { error, stack: error.stack });
return null;
}
}
@@ -218,21 +468,33 @@ class SubscriptionCommands {
async createOrUpdateSubscription(serverId, gameId, channelId, interaction) {
try {
const { data: prefData, error: prefError } = await this.supabase
.from('server_game_preferences')
.from("server_game_preferences")
.upsert(
{ server_id: serverId, game_id: gameId, notification_channel_id: channelId },
{ onConflict: 'server_id,game_id' }
{
server_id: serverId,
game_id: gameId,
notification_channel_id: channelId,
},
{ onConflict: "server_id,game_id" }
)
.select();
if (prefError) {
this.logger.error('Error creating/updating subscription:', { prefError, serverId, gameId, channelId });
this.logger.error("Error creating/updating subscription:", {
prefError,
serverId,
gameId,
channelId,
});
return null;
}
return prefData;
} catch (error) {
this.logger.error('Error in createOrUpdateSubscription:', { error, stack: error.stack });
this.logger.error("Error in createOrUpdateSubscription:", {
error,
stack: error.stack,
});
return null;
}
}
@@ -240,107 +502,135 @@ class SubscriptionCommands {
async fetchSubscription(guildId, gameName) {
// Fetch the subscription data
const { data: subscription, error: subError } = await this.supabase
.from('active_subscriptions')
.select('*')
.eq('discord_server_id', guildId)
.eq('game_name', gameName)
.from("active_subscriptions")
.select("*")
.eq("discord_server_id", guildId)
.eq("game_name", gameName)
.single();
if (subError || !subscription) {
this.logger.debug('No subscription found', { guildId, gameName });
this.logger.debug("No subscription found", { guildId, gameName });
return null;
}
// Fetch the server_id
const { data: serverData, error: serverError } = await this.supabase
.from('servers')
.select('id')
.eq('discord_server_id', guildId)
.from("servers")
.select("id")
.eq("discord_server_id", guildId)
.single();
if (serverError) {
this.logger.error('Error fetching server_id', { serverError });
this.logger.error("Error fetching server_id", { serverError });
return null;
}
// Fetch the game_id
const { data: gameData, error: gameError } = await this.supabase
.from('games')
.select('id')
.eq('name', gameName)
.from("games")
.select("id")
.eq("name", gameName)
.single();
if (gameError) {
this.logger.error('Error fetching game_id', { gameError });
this.logger.error("Error fetching game_id", { gameError });
return null;
}
this.logger.debug('Subscription fetched', { subscription, serverData, gameData });
this.logger.debug("Subscription fetched", {
subscription,
serverData,
gameData,
});
return {
server_id: serverData.id,
game_id: gameData.id,
discord_server_id: subscription.discord_server_id,
game_name: subscription.game_name,
notification_channel_id: subscription.notification_channel_id
notification_channel_id: subscription.notification_channel_id,
};
}
async deleteSubscription(subscription) {
if (!subscription || !subscription.server_id || !subscription.game_id) {
this.logger.error('Invalid subscription data', {
this.logger.error("Invalid subscription data", {
subscription,
hasServerId: !!subscription?.server_id,
hasGameId: !!subscription?.game_id
hasGameId: !!subscription?.game_id,
});
return false;
}
const { error: deleteError } = await this.supabase
.from('server_game_preferences')
.from("server_game_preferences")
.delete()
.match({
server_id: subscription.server_id,
game_id: subscription.game_id
game_id: subscription.game_id,
});
if (deleteError) {
this.logger.error('Delete error', { deleteError, subscription });
this.logger.error("Delete error", { deleteError, subscription });
return false;
}
this.logger.debug('Subscription deleted', { subscription });
this.logger.debug("Subscription deleted", { subscription });
return true;
}
async getSubscriptions(guildId, interaction) {
const { data: subscriptions, error } = await this.supabase
.from('active_subscriptions')
.select('*')
.eq('discord_server_id', guildId);
.from("active_subscriptions")
.select("*")
.eq("discord_server_id", guildId);
if (error) {
this.logger.error('Error fetching subscriptions', { error });
await interaction.editReply('Failed to fetch subscriptions. Please try again later.');
this.logger.error("Error fetching subscriptions", { error });
await interaction.editReply(
"Failed to fetch subscriptions. Please try again later."
);
return null;
}
return subscriptions;
}
async safeReply(interaction, content, options = {}) {
try {
if (!interaction.deferred && !interaction.replied) {
await interaction.deferReply({ ephemeral: true });
}
if (interaction.deferred) {
await interaction.editReply({ content, ...options });
}
} catch (error) {
this.logger.error("Error in safeReply:", {
error: error.message,
stack: error.stack,
interactionStatus: {
deferred: interaction.deferred,
replied: interaction.replied
}
});
}
}
buildSubscriptionsEmbed(subscriptions) {
return new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Game Subscriptions')
.setDescription('Current game notification subscriptions for this server:')
.setColor("#0099ff")
.setTitle("Game Subscriptions")
.setDescription(
"Current game notification subscriptions for this server:"
)
.addFields(
subscriptions.map(sub => ({
subscriptions.map((sub) => ({
name: sub.game_name,
value: `<#${sub.notification_channel_id}>`,
inline: true
inline: true,
}))
)
.setTimestamp()
.setFooter({ text: 'VRBattles Match System' });
.setFooter({ text: "VRBattles Match System" });
}
async safeReply(interaction, content, options = {}) {
@@ -351,21 +641,50 @@ class SubscriptionCommands {
await interaction.editReply({ content, ...options });
} catch (error) {
this.logger.error('Error in safeReply:', { error, stack: error.stack });
this.logger.error("Error in safeReply:", { error, stack: error.stack });
}
}
sanitizeInput(input) {
if (typeof input !== 'string') {
return '';
if (typeof input !== "string") {
return "";
}
// Remove any characters that aren't alphanumeric, spaces, or hyphens
return input.replace(/[^a-zA-Z0-9 -]/g, '').trim();
return input.replace(/[^a-zA-Z0-9 -]/g, "").trim();
}
handleError(method, error, interaction) {
this.logger.error(`Error in ${method}`, { error, stack: error.stack });
interaction.editReply('An unexpected error occurred. Please try again later.');
interaction.editReply(
"An unexpected error occurred. Please try again later."
);
}
validateServerData(guildId, serverName) {
if (!guildId) {
this.logger.error("Missing guildId in server data");
return false;
}
if (!serverName) {
this.logger.error("Missing serverName in server data");
return false;
}
// Validate guildId format (should be a snowflake)
if (!/^\d+$/.test(guildId)) {
this.logger.error("Invalid guildId format", { guildId });
return false;
}
// Validate serverName
if (serverName.length > 100) {
// Adjust max length based on your database schema
this.logger.error("Server name too long", { length: serverName.length });
return false;
}
return true;
}
}

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,49 +1,199 @@
const { createClient } = require('@supabase/supabase-js');
const Logger = require('../utils/Logger');
class SupabaseService {
constructor() {
this.logger = new Logger('SupabaseService');
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
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;
} else {
this.supabase = createClient(supabaseUrl, supabaseKey);
this.logger.debug('Supabase client created');
}
}
async testConnection() {
if (!this.supabase) {
console.error('Supabase client is not initialized.');
this.logger.error('Client not initialized');
return false;
}
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')
.select('count')
.limit(1);
if (error) {
console.error('Supabase connection test error:', error);
if (gameError) {
this.logger.error('Games table test failed:', gameError);
return false;
}
console.log('Supabase connection successful');
this.logger.info('Database connection successful');
return true;
} catch (error) {
console.error('Supabase connection test failed:', error);
this.logger.error('Connection test failed:', {
error: error.message,
stack: error.stack
});
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) {
if (!this.supabase) {
console.error('Supabase client is not initialized.');
this.logger.error('Client not initialized');
return [];
}
try {
this.logger.debug('Fetching subscriptions', { guildId });
const { data, error } = await this.supabase
.from('server_game_preferences')
.select(`
@@ -53,27 +203,56 @@ class SupabaseService {
`)
.eq('servers.discord_server_id', guildId);
if (error) throw error;
return data;
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) {
if (!this.supabase) {
console.error('Supabase client is not initialized.');
this.logger.error('Client not initialized');
return null;
}
try {
this.logger.debug('Adding subscription', { guildId, gameName, channelId });
// First, get or create server record
const { data: serverData, error: serverError } = await this.supabase
.from('servers')
.upsert({
discord_server_id: guildId
discord_server_id: guildId,
active: true
}, {
onConflict: 'discord_server_id',
returning: true
});
if (serverError) throw serverError;
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
@@ -83,7 +262,10 @@ class SupabaseService {
.eq('active', true)
.single();
if (gameError) throw gameError;
if (gameError) {
this.logger.error('Game fetch error:', { gameError, gameName });
throw gameError;
}
// Create subscription
const { data, error } = await this.supabase
@@ -97,16 +279,38 @@ class SupabaseService {
returning: true
});
if (error) throw error;
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
});
return data;
} catch (error) {
this.logger.error('Error in addSubscription:', {
error: error.message,
stack: error.stack,
guildId,
gameName
});
throw error;
}
}
async removeSubscription(guildId, gameName) {
if (!this.supabase) {
console.error('Supabase client is not initialized.');
this.logger.error('Client not initialized');
return null;
}
try {
this.logger.debug('Removing subscription', { guildId, gameName });
// Get server ID
const { data: serverData, error: serverError } = await this.supabase
.from('servers')
@@ -114,7 +318,10 @@ class SupabaseService {
.eq('discord_server_id', guildId)
.single();
if (serverError) throw serverError;
if (serverError) {
this.logger.error('Server fetch error:', { serverError, guildId });
throw serverError;
}
// Get game ID
const { data: gameData, error: gameError } = await this.supabase
@@ -123,7 +330,10 @@ class SupabaseService {
.eq('name', gameName)
.single();
if (gameError) throw gameError;
if (gameError) {
this.logger.error('Game fetch error:', { gameError, gameName });
throw gameError;
}
// Delete subscription
const { data, error } = await this.supabase
@@ -135,8 +345,26 @@ class SupabaseService {
})
.single();
if (error) throw error;
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() {