Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57d420a9f4 | ||
|
|
f8cc08ba3e | ||
|
|
60d5c4cb1f | ||
|
|
0288e2f4de | ||
|
|
33d5a79759 | ||
|
|
30b89a3cf9 | ||
|
|
427dc2d040 | ||
|
|
033f32d596 | ||
|
|
d5fa42b55d | ||
|
|
4bb35b1e50 | ||
|
|
d451857d7b | ||
|
|
78b804176a | ||
|
|
15b780ab62 | ||
|
|
9448c4e3d6 | ||
|
|
4af9759700 | ||
|
|
835cbbe937 | ||
|
|
491bb9ba65 | ||
|
|
ced29535f9 | ||
|
|
d99e9a105b | ||
|
|
c72c7c5c34 | ||
|
|
23960bc30d | ||
|
|
abb48c281b | ||
|
|
7acb825713 | ||
|
|
dd2f329485 | ||
|
|
75577ec0bd | ||
|
|
7366bcda71 | ||
|
|
23e43cfad3 | ||
|
|
ad9a8085aa | ||
|
|
2f23e8f23d | ||
|
|
4c07b8a236 | ||
|
|
571bd586fa | ||
|
|
eac2d88873 | ||
|
|
93c793f393 | ||
|
|
1aa97b63f9 | ||
|
|
c1b76a2b84 | ||
|
|
a1429aa723 | ||
|
|
2de7c7b19c | ||
|
|
7383bd2c48 | ||
|
|
a05d65099b | ||
|
|
c6db929d12 | ||
|
|
dc88f6c51a | ||
|
|
d69fb0e26d | ||
|
|
4b2d53d3f4 | ||
|
|
e3fa8b6d72 | ||
|
|
5c6a9f7306 | ||
|
|
71e33dbf66 | ||
|
|
d468ab1575 | ||
|
|
74482af471 | ||
|
|
0b8b092cb9 | ||
|
|
3cdfaef942 | ||
|
|
fcf441a190 | ||
|
|
5a1c4ad99c | ||
|
|
d9cb72f22e | ||
|
|
58eb37124e | ||
|
|
afeeda3a8d | ||
|
|
fece90d2bd | ||
|
|
357a85fa3d | ||
|
|
f34158caa6 | ||
|
|
1bb343e49a | ||
|
|
dffa5d4161 | ||
|
|
13590b08a8 | ||
|
|
6e14ce209d | ||
|
|
72b8c2247e | ||
|
|
925504a928 | ||
|
|
236d67707f | ||
|
|
753f432c95 | ||
|
|
c824bc51b2 | ||
|
|
39ee540b55 | ||
|
|
903b214051 | ||
|
|
ac0daf5fe7 | ||
|
|
80e38a07e9 | ||
|
|
d2598e09f7 | ||
|
|
28aab47150 | ||
|
|
81bda67ae4 | ||
|
|
25bbd1ff85 | ||
|
|
164d695a5f | ||
|
|
57e4a3e77c | ||
|
|
a6ac532b2b | ||
|
|
4f14722e14 | ||
|
|
9a6eece7a1 | ||
|
|
fd65d0a9a7 | ||
|
|
48500fe8a4 | ||
|
|
8d8d9e4bee | ||
|
|
dcbddf9f23 | ||
|
|
7449c0a61a | ||
|
|
c95b8ccb32 | ||
|
|
2c5bfe8e33 | ||
|
|
a3bbd97333 | ||
|
|
4ea488951d | ||
|
|
481424d5a6 | ||
|
|
fe82e96cc1 | ||
|
|
976258c959 | ||
|
|
83cf0689e2 | ||
|
|
c911cb4423 | ||
|
|
4eadef8b65 | ||
|
|
4e081358ff | ||
|
|
209ec0b435 | ||
|
|
6d363abb54 | ||
|
|
6f8b84aeda | ||
|
|
5b8c5da33a | ||
|
|
b6ef0f95cb | ||
|
|
cce1480a42 | ||
|
|
44fbe9f2d6 | ||
|
|
29db6c7d67 | ||
|
|
26e9b56961 | ||
|
|
979271cfb5 | ||
|
|
69f0b00ed3 | ||
|
|
c1a1839457 | ||
|
|
dd4b53800e | ||
|
|
1fc94528fc | ||
|
|
bb1a817980 | ||
|
|
53305acbc7 | ||
|
|
d0f1bae0bd | ||
|
|
c0cf3b1bb7 | ||
|
|
ce67b668d5 | ||
|
|
3273cfd0e1 | ||
|
|
fd992a6514 | ||
|
|
550d681fe1 | ||
|
|
7d29226953 | ||
|
|
38da72ca91 | ||
|
|
eab11361cb | ||
|
|
b281bba36f | ||
|
|
5e38573aed | ||
|
|
da7b6d487c | ||
|
|
6bf4e5f4bb | ||
|
|
213f532a3c | ||
|
|
45bd88e4d2 | ||
|
|
4eb8658459 | ||
|
|
b37118fee2 | ||
|
|
026caba68a | ||
|
|
2003f8801a | ||
|
|
473bacf13a | ||
|
|
8b3f2bc61a | ||
|
|
3aa373c33c | ||
|
|
9b6263e583 | ||
|
|
3e066d08ce | ||
|
|
aa48e28162 | ||
|
|
dc660ed94a | ||
|
|
e02ecf9553 | ||
|
|
23acc0926f | ||
|
|
3fc1cd18d5 | ||
|
|
ebe29b403e | ||
|
|
dcba3312dd | ||
|
|
7fddeeec37 | ||
|
|
b5341b023f | ||
|
|
bbb7443ef2 | ||
|
|
22df347bb9 | ||
|
|
9aed6b8f35 | ||
|
|
9e7ec9f1bd | ||
|
|
373f43eac5 | ||
|
|
6c91b2791a | ||
|
|
bde62a431f | ||
|
|
615a074540 | ||
|
|
09b335ac46 | ||
|
|
2701880c77 | ||
|
|
24c8f2fb38 | ||
|
|
c3ec158ac3 | ||
|
|
b3690222d0 | ||
|
|
4d7583785b | ||
|
|
17ad1a15db | ||
|
|
4c89de9e76 | ||
|
|
5f25af41f9 | ||
|
|
3a3ee357fc | ||
|
|
08a6d27903 | ||
|
|
33f7675aac | ||
|
|
1178a0a611 | ||
|
|
96ded77bec | ||
|
|
e83ca8cb2b | ||
|
|
e507176d39 | ||
|
|
4e554b8bee | ||
|
|
bc649caa99 | ||
|
|
f7a4c7b616 | ||
|
|
2c7be5882c | ||
|
|
6107d268f7 | ||
|
|
7760699155 | ||
|
|
acf349c72e | ||
|
|
8096e5b882 | ||
|
|
873cfc7dc2 | ||
|
|
038174bc7e | ||
|
|
14881096bb | ||
|
|
ed1905d8f4 | ||
|
|
72c0a2efa3 | ||
|
|
e599d48713 | ||
|
|
7f44634d4f | ||
|
|
44170caac6 | ||
|
|
adedfadd92 | ||
|
|
6b01d0c8fe | ||
|
|
d4d96f59ab | ||
|
|
a1bf7ed6bd | ||
|
|
306e20efc9 | ||
|
|
f593f6e0a8 | ||
|
|
74646a4318 | ||
|
|
8bfcba8832 | ||
|
|
4ba5621a4d | ||
|
|
1f928324c2 | ||
|
|
3771872cd2 | ||
|
|
f359a60343 | ||
|
|
f53afd7bc9 | ||
|
|
e7dcc2ab29 | ||
|
|
0118b9e591 | ||
|
|
ffe42f9777 | ||
|
|
5a467599e9 | ||
|
|
c56e78484a | ||
|
|
1ee0d4a09e | ||
|
|
ffdce5820b | ||
|
|
9fed504f37 | ||
|
|
6c5799be0d | ||
|
|
b6747a0340 | ||
|
|
cd6df02e30 | ||
|
|
edbef6a36f | ||
|
|
b6a0016f5f | ||
|
|
e740c17837 | ||
|
|
7eb949f109 | ||
|
|
02394e310d | ||
|
|
ef83832819 | ||
|
|
a82101ab30 | ||
|
|
007c78930e | ||
|
|
300c83512c | ||
|
|
b674872c56 | ||
|
|
12a7680275 | ||
|
|
c9cf7c942b | ||
|
|
8e0326c8f8 | ||
|
|
13972119a8 | ||
|
|
acf165a119 | ||
|
|
bdff7c6069 | ||
|
|
e2e3376c87 | ||
|
|
3c613088e5 | ||
|
|
7e9ece50a0 | ||
|
|
af81b6536a | ||
|
|
4cd3ecf81f | ||
|
|
31f6b9e08e | ||
|
|
02de920cb3 | ||
|
|
84c0905297 | ||
|
|
250583f859 | ||
|
|
ee7d42196d | ||
|
|
a397de2b9f | ||
|
|
0610df9400 | ||
|
|
ed583deb31 | ||
|
|
e039048fc6 | ||
|
|
f2ea9650c4 | ||
|
|
1e89057006 | ||
|
|
019bb4842f | ||
|
|
4cb45beded | ||
|
|
8a2059f087 | ||
|
|
a6b105a2e1 | ||
|
|
6c14a6a06c | ||
|
|
cddd5d0026 | ||
|
|
78dea91e1d | ||
|
|
3df591ec52 | ||
|
|
1c4032caa6 | ||
|
|
465c422171 | ||
|
|
284e8dc6f5 | ||
|
|
3fc905c82e | ||
|
|
55a42b88ae | ||
|
|
bd26162e4a | ||
|
|
62e7e33406 | ||
|
|
2f0ddcec3f | ||
|
|
7cdfa68e0e | ||
|
|
f8939a964d | ||
|
|
7830e5dda5 | ||
|
|
6aa2f22294 | ||
|
|
50b14e3d44 | ||
|
|
e09c2192c2 | ||
|
|
b725d2cc62 | ||
|
|
abf3f617a4 | ||
|
|
1eda7e66fe | ||
|
|
b5000531c4 | ||
|
|
d4f95e752b | ||
|
|
e31c611f70 | ||
|
|
085481bee6 | ||
|
|
cf610fbe49 | ||
|
|
b681eb3cd2 | ||
|
|
f8ffdf0e81 | ||
|
|
ba38bce1da | ||
|
|
3a39b05fe4 | ||
|
|
27d2982b28 | ||
|
|
33e4d97be5 | ||
|
|
654064d7c5 | ||
|
|
aeb0da9e0d | ||
|
|
cb1a2fe067 | ||
|
|
7ad5016966 | ||
|
|
155b768f73 |
No files matched your search
@@ -1,32 +0,0 @@
|
||||
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
|
||||
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
|
||||
|
||||
name: Node.js CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [10.x, 12.x, 14.x, 15.x]
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- run: npm ci
|
||||
- run: npm install discord.js --save
|
||||
- run: npm install js-yaml
|
||||
- run: npm run build --if-present
|
||||
- run: node index.js
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const yaml = require('js-yaml');
|
||||
const YAML = require('yaml');
|
||||
const db = require('../Structures/Database.js');
|
||||
|
||||
class APIServer {
|
||||
constructor(client) {
|
||||
this.client = client;
|
||||
this.app = express();
|
||||
|
||||
try {
|
||||
const apiCfg = yaml.load(fs.readFileSync('./Configs/api.yml', 'utf8')).API;
|
||||
this.config = apiCfg;
|
||||
} catch (e) {
|
||||
console.error('[API] Failed to load api.yml, defaulting to disabled.');
|
||||
this.config = { Enabled: false };
|
||||
}
|
||||
|
||||
if (!this.config.Enabled) return;
|
||||
|
||||
this.app.use(cors());
|
||||
this.app.use(express.json());
|
||||
|
||||
this.app.use((req, res, next) => {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || authHeader !== `Bearer ${this.config.SecretKey}`) {
|
||||
return res.status(401).json({ error: 'Unauthorized. Invalid Secret Key.' });
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
this.setupRoutes();
|
||||
}
|
||||
|
||||
start(port) {
|
||||
const listenPort = port || this.config.Port || 3000;
|
||||
this.app.listen(listenPort, () => {
|
||||
console.log(`[API] Server running on port ${listenPort}`);
|
||||
});
|
||||
}
|
||||
|
||||
setupRoutes() {
|
||||
this.app.get('/api/stats', async (req, res) => {
|
||||
try {
|
||||
if (!this.client.user) {
|
||||
return res.json({ success: false, error: 'Bot is still starting up.' });
|
||||
}
|
||||
|
||||
let userCount = 0;
|
||||
this.client.guilds.cache.forEach(guild => {
|
||||
userCount += guild.memberCount;
|
||||
});
|
||||
|
||||
const allTickets = db.getAllTickets() || [];
|
||||
const openTickets = allTickets.filter(t => t.open).length;
|
||||
const closedTickets = allTickets.filter(t => !t.open).length;
|
||||
|
||||
const totalMem = os.totalmem();
|
||||
const freeMem = os.freemem();
|
||||
const usedMem = totalMem - freeMem;
|
||||
const ramPercent = Math.round((usedMem / totalMem) * 100);
|
||||
const cpuLoad = os.loadavg()[0].toFixed(2);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
bot: {
|
||||
username: this.client.user.username,
|
||||
id: this.client.user.id,
|
||||
avatar: this.client.user.displayAvatarURL(),
|
||||
version: require('../package.json').version,
|
||||
ping: this.client.ws.ping,
|
||||
uptime: process.uptime(),
|
||||
},
|
||||
servers: this.client.guilds.cache.size,
|
||||
users: userCount,
|
||||
tickets: {
|
||||
total: allTickets.length,
|
||||
open: openTickets,
|
||||
closed: closedTickets
|
||||
},
|
||||
hosting: {
|
||||
ram_used: (usedMem / 1024 / 1024 / 1024).toFixed(2) + ' GB',
|
||||
ram_total: (totalMem / 1024 / 1024 / 1024).toFixed(2) + ' GB',
|
||||
ram_percent: ramPercent,
|
||||
cpu_load: cpuLoad,
|
||||
uptime: Math.floor(os.uptime() / 86400) + ' Days'
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[API] Error fetching stats:', err);
|
||||
res.status(500).json({ success: false, error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
this.app.get('/api/configs/:file', (req, res) => {
|
||||
const validFiles = ['supportbot', 'ticket-panel', 'commands', 'messages', 'supportbot-ai'];
|
||||
const file = req.params.file;
|
||||
if (!validFiles.includes(file)) return res.status(400).json({ success: false, error: 'Invalid file' });
|
||||
try {
|
||||
const configData = fs.readFileSync(`./Configs/${file}.yml`, 'utf8');
|
||||
res.json({ success: true, data: configData });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: 'Failed to read config' });
|
||||
}
|
||||
});
|
||||
|
||||
this.app.put('/api/configs/raw', (req, res) => {
|
||||
const validFiles = ['supportbot', 'ticket-panel', 'commands', 'messages', 'supportbot-ai'];
|
||||
const file = req.body.filename;
|
||||
const content = req.body.content;
|
||||
if (!validFiles.includes(file)) return res.status(400).json({ success: false, error: 'Invalid file' });
|
||||
try {
|
||||
fs.writeFileSync(`./Configs/${file}.yml`, content);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: 'Failed to write config' });
|
||||
}
|
||||
});
|
||||
|
||||
this.app.get('/api/configs/json/:file', (req, res) => {
|
||||
const validFiles = ['supportbot', 'ticket-panel', 'commands', 'messages', 'supportbot-ai'];
|
||||
const file = req.params.file;
|
||||
if (!validFiles.includes(file)) return res.status(400).json({ success: false, error: 'Invalid file' });
|
||||
try {
|
||||
const configData = yaml.load(fs.readFileSync(`./Configs/${file}.yml`, 'utf8'));
|
||||
res.json({ success: true, data: configData });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: 'Failed to parse config' });
|
||||
}
|
||||
});
|
||||
|
||||
this.app.post('/api/configs/update-fields/multi', (req, res) => {
|
||||
const updates = req.body;
|
||||
if (!updates || typeof updates !== 'object') return res.status(400).json({ success: false, error: 'Invalid updates' });
|
||||
try {
|
||||
for (const [keyPath, value] of Object.entries(updates)) {
|
||||
const [fileName, path] = keyPath.split(':');
|
||||
const fileContent = fs.readFileSync(`./Configs/${fileName}.yml`, 'utf8');
|
||||
const doc = YAML.parseDocument(fileContent);
|
||||
const keys = path.split('.');
|
||||
doc.setIn(keys, value);
|
||||
fs.writeFileSync(`./Configs/${fileName}.yml`, doc.toString());
|
||||
}
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('[API] Update failed:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
this.app.post('/api/addons/install', async (req, res) => {
|
||||
const { url, filename } = req.body;
|
||||
if (!url || !filename) return res.status(400).json({ success: false, error: 'Missing url or filename' });
|
||||
|
||||
try {
|
||||
const axios = require('axios');
|
||||
const response = await axios({
|
||||
method: 'get',
|
||||
url: url,
|
||||
responseType: 'stream'
|
||||
});
|
||||
|
||||
// Ensure Addons directory exists
|
||||
if (!fs.existsSync('./Addons')) {
|
||||
fs.mkdirSync('./Addons');
|
||||
}
|
||||
|
||||
const writer = fs.createWriteStream(`./Addons/${filename}`);
|
||||
response.data.pipe(writer);
|
||||
|
||||
writer.on('finish', () => {
|
||||
res.json({ success: true, message: `Addon ${filename} installed successfully.` });
|
||||
});
|
||||
|
||||
writer.on('error', (err) => {
|
||||
console.error('[API] Download failed:', err);
|
||||
res.status(500).json({ success: false, error: 'Failed to write addon file' });
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.error('[API] Addon install failed:', err);
|
||||
res.status(500).json({ success: false, error: 'Failed to download addon' });
|
||||
}
|
||||
});
|
||||
|
||||
this.app.post('/api/addons/push', (req, res) => {
|
||||
const { filename, content } = req.body;
|
||||
if (!filename || !content) return res.status(400).json({ success: false, error: 'Missing filename or content' });
|
||||
|
||||
const sanitizedFilename = filename.replace(/[^a-z0-9_.-]/gi, '_');
|
||||
|
||||
try {
|
||||
if (!fs.existsSync('./Addons')) {
|
||||
fs.mkdirSync('./Addons');
|
||||
}
|
||||
fs.writeFileSync(`./Addons/${sanitizedFilename}`, content);
|
||||
res.json({ success: true, message: `Addon ${sanitizedFilename} deployed successfully.` });
|
||||
} catch (err) {
|
||||
console.error('[API] Push failed:', err);
|
||||
res.status(500).json({ success: false, error: 'Failed to write addon file' });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Nexus Updater API ---
|
||||
this.app.post('/api/system/update', async (req, res) => {
|
||||
const { url, version } = req.body;
|
||||
if (!url) return res.status(400).json({ success: false, error: 'Missing update URL' });
|
||||
|
||||
try {
|
||||
const axios = require('axios');
|
||||
const { execSync } = require('child_process');
|
||||
const path = require('path');
|
||||
|
||||
console.log(`[Updater] Starting update to ${version || 'latest'}...`);
|
||||
|
||||
// 1. Download
|
||||
const tempZip = `./update_${Date.now()}.zip`;
|
||||
const response = await axios({ method: 'get', url: url, responseType: 'stream' });
|
||||
const writer = fs.createWriteStream(tempZip);
|
||||
response.data.pipe(writer);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
writer.on('finish', resolve);
|
||||
writer.on('error', reject);
|
||||
});
|
||||
|
||||
// 2. Extract to temp dir
|
||||
const tempDir = `./temp_update_${Date.now()}`;
|
||||
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
|
||||
|
||||
const isWindows = process.platform === 'win32';
|
||||
try {
|
||||
if (isWindows) {
|
||||
execSync(`powershell -Command "Expand-Archive -Path '${tempZip}' -DestinationPath '${tempDir}' -Force"`);
|
||||
} else {
|
||||
execSync(`unzip -o "${tempZip}" -d "${tempDir}"`);
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`Extraction failed. Ensure ${isWindows ? 'PowerShell' : 'unzip'} is installed. ${e.message}`);
|
||||
}
|
||||
|
||||
// Identify inner directory (sometimes zips contain a root folder)
|
||||
let sourcePath = tempDir;
|
||||
const items = fs.readdirSync(tempDir);
|
||||
if (items.length === 1 && fs.statSync(path.join(tempDir, items[0])).isDirectory()) {
|
||||
sourcePath = path.join(tempDir, items[0]);
|
||||
}
|
||||
|
||||
// 3. Smart Config Merge
|
||||
const configFiles = ['supportbot', 'commands', 'messages', 'ticket-panel', 'supportbot-ai'];
|
||||
configFiles.forEach(cf => {
|
||||
const currentPath = `./Configs/${cf}.yml`;
|
||||
const newPath = path.join(sourcePath, 'Configs', `${cf}.yml`);
|
||||
|
||||
if (fs.existsSync(currentPath) && fs.existsSync(newPath)) {
|
||||
const currentCfg = yaml.load(fs.readFileSync(currentPath, 'utf8'));
|
||||
const newCfg = yaml.load(fs.readFileSync(newPath, 'utf8'));
|
||||
|
||||
const merge = (target, source) => {
|
||||
for (const key of Object.keys(source)) {
|
||||
if (source[key] instanceof Object && !Array.isArray(source[key]) && target[key]) {
|
||||
merge(target[key], source[key]);
|
||||
} else if (target[key] === undefined) {
|
||||
target[key] = source[key];
|
||||
console.log(`[Updater] Added missing key: ${key} to ${cf}.yml`);
|
||||
}
|
||||
}
|
||||
};
|
||||
merge(currentCfg, newCfg);
|
||||
fs.writeFileSync(currentPath, YAML.stringify(currentCfg));
|
||||
}
|
||||
});
|
||||
|
||||
// 4. Overwrite Core Folders
|
||||
const coreFolders = ['API', 'Commands', 'Events', 'Structures'];
|
||||
coreFolders.forEach(folder => {
|
||||
const src = path.join(sourcePath, folder);
|
||||
if (fs.existsSync(src)) {
|
||||
if (isWindows) {
|
||||
execSync(`xcopy "${src}" ".\\${folder}" /E /I /Y`);
|
||||
} else {
|
||||
execSync(`cp -R "${src}/"* "./${folder}/"`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 5. Update package.json (version only)
|
||||
const newPkgPath = path.join(sourcePath, 'package.json');
|
||||
if (fs.existsSync(newPkgPath)) {
|
||||
const currentPkg = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
|
||||
const newPkg = JSON.parse(fs.readFileSync(newPkgPath, 'utf8'));
|
||||
currentPkg.version = newPkg.version;
|
||||
fs.writeFileSync('./package.json', JSON.stringify(currentPkg, null, 2));
|
||||
}
|
||||
|
||||
fs.unlinkSync(tempZip);
|
||||
if (isWindows) {
|
||||
execSync(`rmdir /s /q "${tempDir}"`);
|
||||
} else {
|
||||
execSync(`rm -rf "${tempDir}"`);
|
||||
}
|
||||
|
||||
res.json({ success: true, message: 'Update installed successfully. Bot is restarting...' });
|
||||
|
||||
// Reboot
|
||||
setTimeout(() => process.exit(0), 1000);
|
||||
|
||||
} catch (err) {
|
||||
console.error('[Updater] Update failed:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Transcript API ---
|
||||
this.app.get('/api/system/transcripts', (req, res) => {
|
||||
const transcriptDir = './Data/Transcripts';
|
||||
try {
|
||||
if (!fs.existsSync(transcriptDir)) {
|
||||
return res.json({ success: true, data: [] });
|
||||
}
|
||||
const files = fs.readdirSync(transcriptDir);
|
||||
const transcripts = files
|
||||
.filter(f => f.endsWith('-transcript.html'))
|
||||
.map(f => {
|
||||
const stats = fs.statSync(`${transcriptDir}/${f}`);
|
||||
return {
|
||||
id: f.replace('-transcript.html', ''),
|
||||
filename: f,
|
||||
createdAt: stats.mtime
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.createdAt - a.createdAt);
|
||||
res.json({ success: true, data: transcripts });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: 'Failed to list transcripts' });
|
||||
}
|
||||
});
|
||||
|
||||
this.app.get('/api/system/transcripts/:id', (req, res) => {
|
||||
const id = req.params.id.replace(/[^0-9]/g, ''); // Sanitize ID
|
||||
const filePath = `./Data/Transcripts/${id}-transcript.html`;
|
||||
try {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return res.status(404).json({ success: false, error: 'Transcript not found' });
|
||||
}
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
res.json({ success: true, data: content });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: 'Failed to read transcript' });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = APIServer;
|
||||
@@ -0,0 +1,26 @@
|
||||
const Discord = require("discord.js");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const { Command } = require('../Structures/Addon.js'); // Adjust the path as needed
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
|
||||
module.exports = new Command({
|
||||
name: "addon",
|
||||
description: "This is a sample addon!",
|
||||
options: [],
|
||||
permissions: ["Administrator"],
|
||||
|
||||
async run(interaction) {
|
||||
let disableCommand = true;
|
||||
|
||||
const PingEmbed = new Discord.EmbedBuilder()
|
||||
.setDescription(
|
||||
`This is a sample addon.\n\nPong! \`${interaction.client.ws.ping} ms\``
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
interaction.reply({
|
||||
embeds: [PingEmbed],
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Example (default) Addon
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
// Your Addon Config file! Saved in /Addons/Settings/YourAddonConig.yml
|
||||
// const exampleaddon = yaml.load(fs.readFileSync('./Addons/Settings/YourAddonConig.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: "hello",
|
||||
description: "hello",
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
const Embed = new Discord.MessageEmbed()
|
||||
.setDescription("Hello World!")
|
||||
.setColor(supportbot.InfoColour)
|
||||
|
||||
message.channel.send({
|
||||
embeds: [Embed]
|
||||
})
|
||||
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
// SupportBot | Emerald Services
|
||||
// AI Command (Consolidated)
|
||||
|
||||
const fs = require("fs");
|
||||
const { ApplicationCommandOptionType, ApplicationCommandType, EmbedBuilder, MessageFlags } = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
const supportbotai = yaml.load(fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"));
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
const AIDatabase = require("../../Structures/AIDatabase.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.AI?.Command || "ai",
|
||||
description: cmdconfig.AI?.Description || "Manage SupportBot AI settings and memory.",
|
||||
type: ApplicationCommandType.ChatInput,
|
||||
options: [
|
||||
{
|
||||
name: cmdconfig.AI?.Train?.Command || "train",
|
||||
description: cmdconfig.AI?.Train?.Description || "Train the AI by adding knowledge to its database.",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: "content",
|
||||
description: "The text/knowledge you want the bot to learn",
|
||||
type: ApplicationCommandOptionType.String,
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: cmdconfig.AI?.Knowledge?.Command || "knowledge",
|
||||
description: cmdconfig.AI?.Knowledge?.Description || "Manage the AI knowledge base.",
|
||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
||||
options: [
|
||||
{
|
||||
name: cmdconfig.AI?.Knowledge?.Clear?.Command || "clear",
|
||||
description: cmdconfig.AI?.Knowledge?.Clear?.Description || "Clear all trained knowledge from the AI.",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: cmdconfig.AI?.Memory?.Command || "memory",
|
||||
description: cmdconfig.AI?.Memory?.Description || "Manage the AI conversational memory.",
|
||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
||||
options: [
|
||||
{
|
||||
name: cmdconfig.AI?.Memory?.Clear?.Command || "clear",
|
||||
description: cmdconfig.AI?.Memory?.Clear?.Description || "Clear recent conversation memory for this channel.",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
permissions: cmdconfig.AI?.Permission || ["Administrator"],
|
||||
|
||||
async run(interaction) {
|
||||
if (!supportbotai.Enabled) {
|
||||
return interaction.reply({
|
||||
content: "SupportBot AI is currently disabled.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const subcommandGroup = interaction.options.getSubcommandGroup(false);
|
||||
const subcommand = interaction.options.getSubcommand(false);
|
||||
|
||||
try {
|
||||
if (subcommand === "train" || subcommand === cmdconfig.AI?.Train?.Command) {
|
||||
const content = interaction.options.getString("content");
|
||||
|
||||
AIDatabase.addKnowledge({
|
||||
sourceType: "user_command",
|
||||
sourceName: interaction.user.tag,
|
||||
title: "Trained Knowledge",
|
||||
content: content,
|
||||
});
|
||||
|
||||
const SuccessEmbed = new EmbedBuilder()
|
||||
.setDescription(`✅ **Knowledge Added!**\n\nThe AI has learned the following information:\n\`\`\`${content}\`\`\``)
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
return interaction.reply({ embeds: [SuccessEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
|
||||
if (subcommandGroup === (cmdconfig.AI?.Knowledge?.Command || "knowledge")) {
|
||||
if (subcommand === (cmdconfig.AI?.Knowledge?.Clear?.Command || "clear")) {
|
||||
AIDatabase.clearKnowledge();
|
||||
|
||||
const SuccessEmbed = new EmbedBuilder()
|
||||
.setDescription(`✅ **Knowledge Cleared!**\n\nAll manually trained knowledge has been wiped from the database.`)
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
return interaction.reply({ embeds: [SuccessEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
}
|
||||
|
||||
if (subcommandGroup === (cmdconfig.AI?.Memory?.Command || "memory")) {
|
||||
if (subcommand === (cmdconfig.AI?.Memory?.Clear?.Command || "clear")) {
|
||||
AIDatabase.clearConversations(interaction.channel.id);
|
||||
|
||||
const SuccessEmbed = new EmbedBuilder()
|
||||
.setDescription(`✅ **Memory Cleared!**\n\nThe AI's recent conversation memory in this channel has been wiped. It will no longer remember previous messages sent here.`)
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
return interaction.reply({ embeds: [SuccessEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error("AI Command Error:", error);
|
||||
const ErrorEmbed = new EmbedBuilder()
|
||||
.setDescription(`❌ **Error:** Failed to process the AI command.`)
|
||||
.setColor(supportbot.Embed.Colours.Error);
|
||||
|
||||
return interaction.reply({ embeds: [ErrorEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
const fs = require("fs");
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Help.Command,
|
||||
description: cmdconfig.Help.Description,
|
||||
type: Discord.ApplicationCommandType.ChatInput,
|
||||
options: [],
|
||||
permissions: cmdconfig.Help.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
const { getRole } = interaction.client;
|
||||
let SupportStaff = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
let Admin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
if (!SupportStaff || !Admin) {
|
||||
return interaction.reply(
|
||||
"Some roles seem to be missing!\nPlease check for errors when starting the bot."
|
||||
);
|
||||
}
|
||||
|
||||
// Separate regular commands and addon commands
|
||||
let botCommands = "";
|
||||
let addonCommands = "";
|
||||
|
||||
interaction.client.commands.forEach((command) => {
|
||||
if (command.permissions) {
|
||||
if (command.addon) {
|
||||
addonCommands += `\`${command.name}\` `;
|
||||
} else {
|
||||
botCommands += `\`${command.name}\` `;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Create embed
|
||||
const HelpEmbed1 = new Discord.EmbedBuilder()
|
||||
.setTitle(supportbot.General.Name + " Commands")
|
||||
.setThumbnail(interaction.user.displayAvatarURL())
|
||||
.setColor(supportbot.Embed.Colours.General)
|
||||
.addFields({
|
||||
name: "🖥️ Commands\n",
|
||||
value: botCommands || "No commands available.",
|
||||
inline: false,
|
||||
});
|
||||
|
||||
HelpEmbed1.setFooter({
|
||||
text: supportbot.Embed.Footer,
|
||||
iconURL: interaction.user.displayAvatarURL(),
|
||||
});
|
||||
|
||||
interaction.reply({
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
embeds: [HelpEmbed1],
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Info Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const supportbot = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot.yml", "utf8")
|
||||
);
|
||||
|
||||
const cmdconfig = yaml.load(
|
||||
fs.readFileSync("./Configs/commands.yml", "utf8")
|
||||
);
|
||||
|
||||
const msgconfig = yaml.load(
|
||||
fs.readFileSync("./Configs/messages.yml", "utf8")
|
||||
);
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Info.Command,
|
||||
description: cmdconfig.Info.Description,
|
||||
options: [],
|
||||
permissions: cmdconfig.Info.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
let disableCommand = true;
|
||||
|
||||
const InfoButton = new Discord.ButtonBuilder()
|
||||
.setLabel(msgconfig.Info.Button)
|
||||
.setURL(msgconfig.Info.URL)
|
||||
.setStyle("Link");
|
||||
|
||||
const inforow = new Discord.ActionRowBuilder().addComponents(InfoButton);
|
||||
|
||||
const InfoEmbed = new Discord.EmbedBuilder()
|
||||
.setURL(msgconfig.Info.URL)
|
||||
.setTitle(msgconfig.Info.Title)
|
||||
.setDescription(msgconfig.Info.Description)
|
||||
.setColor(msgconfig.Info.Colour)
|
||||
|
||||
interaction.reply({
|
||||
embeds: [InfoEmbed],
|
||||
components: [inforow],
|
||||
});
|
||||
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Ping Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
const supportbot = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot.yml", "utf8")
|
||||
);
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Ping.Command,
|
||||
description: cmdconfig.Ping.Description,
|
||||
options: [],
|
||||
permissions: cmdconfig.Ping.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
let disableCommand = true;
|
||||
|
||||
const PingEmbed = new Discord.EmbedBuilder()
|
||||
.setDescription(
|
||||
`:ping_pong: **Ping:** \`${interaction.client.ws.ping} ms\``
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
interaction.reply({
|
||||
embeds: [PingEmbed],
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,527 @@
|
||||
const {
|
||||
ModalBuilder,
|
||||
TextInputBuilder,
|
||||
TextInputStyle,
|
||||
ApplicationCommandType,
|
||||
ActionRowBuilder,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ApplicationCommandOptionType,
|
||||
MessageFlags,
|
||||
ContainerBuilder,
|
||||
TextDisplayBuilder,
|
||||
SeparatorBuilder,
|
||||
ThumbnailBuilder,
|
||||
MediaGalleryBuilder,
|
||||
MediaGalleryItemBuilder,
|
||||
} = require("discord.js");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const db = require("../../Structures/Database.js");
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
const clockedInUsers = new Set();
|
||||
|
||||
function safeGetProfile(userId) {
|
||||
try {
|
||||
if (typeof db.getProfile !== "function") {
|
||||
console.error("db.getProfile is not a function");
|
||||
return {
|
||||
bio: "",
|
||||
timezone: "",
|
||||
clockedIn: false,
|
||||
};
|
||||
}
|
||||
|
||||
const profile = db.getProfile(userId);
|
||||
|
||||
return {
|
||||
bio: profile?.bio || "",
|
||||
timezone: profile?.timezone || "",
|
||||
clockedIn: Boolean(profile?.clockedIn),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error getting profile:", error);
|
||||
return {
|
||||
bio: "",
|
||||
timezone: "",
|
||||
clockedIn: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function safeSetClockedIn(userId, value) {
|
||||
try {
|
||||
if (typeof db.setClockedIn !== "function") {
|
||||
console.error("db.setClockedIn is not a function");
|
||||
return false;
|
||||
}
|
||||
|
||||
db.setClockedIn(userId, value);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error setting clocked in status:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function buildProfileContainer({
|
||||
viewingUser,
|
||||
viewingUserId,
|
||||
bio,
|
||||
timezone,
|
||||
clockedIn,
|
||||
isStaff,
|
||||
}) {
|
||||
const container = new ContainerBuilder();
|
||||
|
||||
if (supportbot.Embed?.Colours?.General) {
|
||||
container.setAccentColor(
|
||||
parseInt(String(supportbot.Embed.Colours.General).replace("#", ""), 16),
|
||||
);
|
||||
}
|
||||
|
||||
const avatarUrl = viewingUser.displayAvatarURL({ size: 128, extension: "png" });
|
||||
|
||||
const gallery = new MediaGalleryBuilder().addItems(
|
||||
new MediaGalleryItemBuilder().setURL(avatarUrl)
|
||||
);
|
||||
|
||||
container.addMediaGalleryComponents(gallery);
|
||||
|
||||
container.addTextDisplayComponents(
|
||||
new TextDisplayBuilder().setContent(`## ${viewingUser.username}'s Profile`)
|
||||
);
|
||||
|
||||
container.addSeparatorComponents(new SeparatorBuilder().setDivider(true));
|
||||
|
||||
container.addTextDisplayComponents(
|
||||
new TextDisplayBuilder().setContent(
|
||||
[
|
||||
`**Bio:** ${bio || "No bio set."}`,
|
||||
`**Timezone:** ${timezone || "No timezone set."}`,
|
||||
...(isStaff
|
||||
? [`**Clocked In:** ${clockedIn ? "✅ Clocked In" : "❌ Clocked Out"}`]
|
||||
: []),
|
||||
].join("\n")
|
||||
)
|
||||
);
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
function buildProfileButtons({ isOwnProfile, isStaff, clockedIn }) {
|
||||
const row = new ActionRowBuilder();
|
||||
|
||||
if (isOwnProfile) {
|
||||
row.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId("editProfile")
|
||||
.setLabel("Edit Profile")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
);
|
||||
|
||||
if (isStaff) {
|
||||
row.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId("clockInOut")
|
||||
.setLabel(clockedIn ? "Clock Out" : "Clock In")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (isStaff && supportbot.Ticket?.ClaimTickets?.Enabled) {
|
||||
row.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId("viewTicketStats")
|
||||
.setLabel("View Ticket Stats")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
);
|
||||
}
|
||||
|
||||
return row.components.length ? [row] : [];
|
||||
}
|
||||
|
||||
function buildTicketStatsContainer(viewingUserId, ticketsClaimed, ticketsOpen, avgMinutes) {
|
||||
const container = new ContainerBuilder();
|
||||
|
||||
if (supportbot.Embed?.Colours?.General) {
|
||||
container.setAccentColor(
|
||||
parseInt(String(supportbot.Embed.Colours.General).replace("#", ""), 16),
|
||||
);
|
||||
}
|
||||
|
||||
container.addTextDisplayComponents(
|
||||
new TextDisplayBuilder().setContent(`# ${msgconfig.TicketStats.Title || "Ticket Stats"}`),
|
||||
);
|
||||
|
||||
container.addSeparatorComponents(new SeparatorBuilder().setDivider(true));
|
||||
|
||||
container.addTextDisplayComponents(
|
||||
new TextDisplayBuilder().setContent(
|
||||
[
|
||||
`> Ticket stats for <@${viewingUserId}>`,
|
||||
``,
|
||||
`**${msgconfig.TicketStats.OpenTickets || "Open Tickets"}:** ${ticketsOpen.length}`,
|
||||
`**${msgconfig.TicketStats.TotalTickets || "Total Tickets"}:** ${ticketsClaimed.length}`,
|
||||
`**${msgconfig.TicketStats.ResponseTime || "Average Response Time"}:** ${avgMinutes} minutes`,
|
||||
].join("\n"),
|
||||
),
|
||||
);
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
function buildOpenTicketsContainer(ticketsOpen) {
|
||||
const container = new ContainerBuilder();
|
||||
|
||||
if (supportbot.Embed?.Colours?.General) {
|
||||
container.setAccentColor(
|
||||
parseInt(String(supportbot.Embed.Colours.General).replace("#", ""), 16),
|
||||
);
|
||||
}
|
||||
|
||||
container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`# Active Tickets`));
|
||||
|
||||
container.addSeparatorComponents(new SeparatorBuilder().setDivider(true));
|
||||
|
||||
container.addTextDisplayComponents(
|
||||
new TextDisplayBuilder().setContent(
|
||||
ticketsOpen.length ? ticketsOpen.map((t) => `<#${t.id}>`).join("\n") : "No active tickets.",
|
||||
),
|
||||
);
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Profile.Command,
|
||||
description: cmdconfig.Profile.Description,
|
||||
type: ApplicationCommandType.ChatInput,
|
||||
permissions: cmdconfig.Profile.Permission,
|
||||
options: [
|
||||
{
|
||||
name: "user",
|
||||
description: "The user to view the profile of",
|
||||
type: ApplicationCommandOptionType.User,
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
|
||||
async run(interaction) {
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
|
||||
try {
|
||||
const viewingUser = interaction.options.getUser("user") || interaction.user;
|
||||
const viewingUserId = viewingUser.id;
|
||||
const interactionUserId = interaction.user.id;
|
||||
|
||||
const member = await interaction.guild.members.fetch(viewingUserId);
|
||||
const { getRole } = interaction.client;
|
||||
|
||||
const Staff = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
const Admin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
|
||||
if (!Staff || !Admin) {
|
||||
return interaction.editReply({
|
||||
content: "Some roles seem to be missing!\nPlease check for errors when starting the bot.",
|
||||
});
|
||||
}
|
||||
|
||||
const isStaff = member.roles.cache.has(Staff.id) || member.roles.cache.has(Admin.id);
|
||||
const isOwnProfile = interactionUserId === viewingUserId;
|
||||
|
||||
if (typeof db.ensureProfile === "function") {
|
||||
db.ensureProfile(viewingUserId);
|
||||
}
|
||||
|
||||
let { bio, timezone, clockedIn } = safeGetProfile(viewingUserId);
|
||||
|
||||
const profileContainer = buildProfileContainer({
|
||||
viewingUser,
|
||||
viewingUserId,
|
||||
bio,
|
||||
timezone,
|
||||
clockedIn,
|
||||
isStaff,
|
||||
});
|
||||
|
||||
const buttonRows = buildProfileButtons({
|
||||
isOwnProfile,
|
||||
isStaff,
|
||||
clockedIn,
|
||||
});
|
||||
|
||||
await interaction.editReply({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [profileContainer, ...buttonRows],
|
||||
});
|
||||
|
||||
const filter = (i) =>
|
||||
[
|
||||
"editProfile",
|
||||
"clockInOut",
|
||||
"viewTicketStats",
|
||||
"showOpenTickets",
|
||||
"backToStats",
|
||||
"backToProfile",
|
||||
].includes(i.customId) && i.user.id === interactionUserId;
|
||||
|
||||
const collector = interaction.channel.createMessageComponentCollector({
|
||||
filter,
|
||||
time: 60000,
|
||||
});
|
||||
|
||||
collector.on("collect", async (i) => {
|
||||
if (i.customId === "editProfile") {
|
||||
const modal = new ModalBuilder()
|
||||
.setCustomId("editProfileModal")
|
||||
.setTitle("Edit Profile")
|
||||
.addComponents(
|
||||
new ActionRowBuilder().addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId("bio")
|
||||
.setLabel("Bio")
|
||||
.setStyle(TextInputStyle.Paragraph)
|
||||
.setPlaceholder("Enter your bio")
|
||||
.setValue(String(bio || ""))
|
||||
.setRequired(false),
|
||||
),
|
||||
new ActionRowBuilder().addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId("timezone")
|
||||
.setLabel("Timezone")
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setPlaceholder("Enter your timezone")
|
||||
.setValue(String(timezone || ""))
|
||||
.setRequired(false),
|
||||
),
|
||||
);
|
||||
|
||||
return i.showModal(modal);
|
||||
}
|
||||
|
||||
if (i.customId === "clockInOut") {
|
||||
const newStatus = !clockedIn;
|
||||
const saved = safeSetClockedIn(viewingUserId, newStatus);
|
||||
|
||||
if (!saved) {
|
||||
return i.reply({
|
||||
content:
|
||||
"Could not update clock in status because the profile database is not available.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
clockedIn = newStatus;
|
||||
|
||||
if (newStatus) clockedInUsers.add(viewingUserId);
|
||||
else clockedInUsers.delete(viewingUserId);
|
||||
|
||||
const updatedProfileContainer = buildProfileContainer({
|
||||
viewingUser,
|
||||
viewingUserId,
|
||||
bio,
|
||||
timezone,
|
||||
clockedIn,
|
||||
isStaff,
|
||||
});
|
||||
|
||||
const updatedButtonRows = buildProfileButtons({
|
||||
isOwnProfile,
|
||||
isStaff,
|
||||
clockedIn,
|
||||
});
|
||||
|
||||
await i.update({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [updatedProfileContainer, ...updatedButtonRows],
|
||||
});
|
||||
|
||||
return interaction.followUp({
|
||||
content: newStatus
|
||||
? "You have successfully clocked in."
|
||||
: "You have successfully clocked out.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (i.customId === "viewTicketStats") {
|
||||
let TicketData = { tickets: [] };
|
||||
|
||||
try {
|
||||
TicketData = JSON.parse(fs.readFileSync("./Data/TicketData.json", "utf8"));
|
||||
} catch (error) {
|
||||
console.error("Error reading TicketData.json:", error);
|
||||
}
|
||||
|
||||
const ticketsClaimed = TicketData.tickets.filter((t) => t.claimedBy === viewingUserId);
|
||||
const ticketsOpen = ticketsClaimed.filter((t) => t.open);
|
||||
const totalTickets = ticketsClaimed.length;
|
||||
|
||||
let totalResponseTime = 0;
|
||||
let responseCount = 0;
|
||||
|
||||
ticketsClaimed.forEach((t) => {
|
||||
if (t.claimedAt && t.createdAt) {
|
||||
totalResponseTime += new Date(t.claimedAt) - new Date(t.createdAt);
|
||||
responseCount++;
|
||||
}
|
||||
});
|
||||
|
||||
const avgMinutes = responseCount
|
||||
? Math.round(totalResponseTime / responseCount / 60000)
|
||||
: 0;
|
||||
|
||||
const statsContainer = buildTicketStatsContainer(
|
||||
viewingUserId,
|
||||
ticketsClaimed,
|
||||
ticketsOpen,
|
||||
avgMinutes,
|
||||
);
|
||||
|
||||
const statsRow = new ActionRowBuilder().addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId("showOpenTickets")
|
||||
.setLabel("Show Open Tickets")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId("backToProfile")
|
||||
.setLabel("Back to Profile")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
);
|
||||
|
||||
return i.update({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [statsContainer, statsRow],
|
||||
});
|
||||
}
|
||||
|
||||
if (i.customId === "showOpenTickets") {
|
||||
let TicketData = { tickets: [] };
|
||||
|
||||
try {
|
||||
TicketData = JSON.parse(fs.readFileSync("./Data/TicketData.json", "utf8"));
|
||||
} catch (error) {
|
||||
console.error("Error reading TicketData.json:", error);
|
||||
}
|
||||
|
||||
const ticketsOpen = TicketData.tickets.filter(
|
||||
(t) => t.claimedBy === viewingUserId && t.open,
|
||||
);
|
||||
|
||||
const openContainer = buildOpenTicketsContainer(ticketsOpen);
|
||||
|
||||
const backRow = new ActionRowBuilder().addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId("backToStats")
|
||||
.setLabel("Back to Stats")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
);
|
||||
|
||||
return i.update({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [openContainer, backRow],
|
||||
});
|
||||
}
|
||||
|
||||
if (i.customId === "backToStats") {
|
||||
let TicketData = { tickets: [] };
|
||||
|
||||
try {
|
||||
TicketData = JSON.parse(fs.readFileSync("./Data/TicketData.json", "utf8"));
|
||||
} catch (error) {
|
||||
console.error("Error reading TicketData.json:", error);
|
||||
}
|
||||
|
||||
const ticketsClaimed = TicketData.tickets.filter((t) => t.claimedBy === viewingUserId);
|
||||
const ticketsOpen = ticketsClaimed.filter((t) => t.open);
|
||||
|
||||
let totalResponseTime = 0;
|
||||
let responseCount = 0;
|
||||
|
||||
ticketsClaimed.forEach((t) => {
|
||||
if (t.claimedAt && t.createdAt) {
|
||||
totalResponseTime += new Date(t.claimedAt) - new Date(t.createdAt);
|
||||
responseCount++;
|
||||
}
|
||||
});
|
||||
|
||||
const avgMinutes = responseCount
|
||||
? Math.round(totalResponseTime / responseCount / 60000)
|
||||
: 0;
|
||||
|
||||
const statsContainer = buildTicketStatsContainer(
|
||||
viewingUserId,
|
||||
ticketsClaimed,
|
||||
ticketsOpen,
|
||||
avgMinutes,
|
||||
);
|
||||
|
||||
const statsRow = new ActionRowBuilder().addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId("showOpenTickets")
|
||||
.setLabel("Show Open Tickets")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId("backToProfile")
|
||||
.setLabel("Back to Profile")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
);
|
||||
|
||||
return i.update({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [statsContainer, statsRow],
|
||||
});
|
||||
}
|
||||
|
||||
if (i.customId === "backToProfile") {
|
||||
const updatedProfileContainer = buildProfileContainer({
|
||||
viewingUser,
|
||||
viewingUserId,
|
||||
bio,
|
||||
timezone,
|
||||
clockedIn,
|
||||
isStaff,
|
||||
});
|
||||
|
||||
const updatedButtonRows = buildProfileButtons({
|
||||
isOwnProfile,
|
||||
isStaff,
|
||||
clockedIn,
|
||||
});
|
||||
|
||||
return i.update({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [updatedProfileContainer, ...updatedButtonRows],
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error executing profile command:", error);
|
||||
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
return interaction
|
||||
.editReply({
|
||||
content: "An error occurred while loading the profile.",
|
||||
components: [],
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
return interaction
|
||||
.reply({
|
||||
content: "An error occurred while loading the profile.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
module.exports.clockedInUsers = clockedInUsers;
|
||||
@@ -0,0 +1,206 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Translate Command
|
||||
|
||||
const fs = require("fs");
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const { translate } = require("@vitalets/google-translate-api");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
const LANGUAGES = [
|
||||
{ name: "Auto Detect", value: "auto" },
|
||||
{ name: "English", value: "en" },
|
||||
{ name: "Spanish", value: "es" },
|
||||
{ name: "French", value: "fr" },
|
||||
{ name: "German", value: "de" },
|
||||
{ name: "Italian", value: "it" },
|
||||
{ name: "Portuguese", value: "pt" },
|
||||
{ name: "Dutch", value: "nl" },
|
||||
{ name: "Polish", value: "pl" },
|
||||
{ name: "Russian", value: "ru" },
|
||||
{ name: "Ukrainian", value: "uk" },
|
||||
{ name: "Turkish", value: "tr" },
|
||||
{ name: "Arabic", value: "ar" },
|
||||
{ name: "Hebrew", value: "he" },
|
||||
{ name: "Hindi", value: "hi" },
|
||||
{ name: "Japanese", value: "ja" },
|
||||
{ name: "Korean", value: "ko" },
|
||||
{ name: "Chinese (Simplified)", value: "zh-cn" },
|
||||
{ name: "Chinese (Traditional)", value: "zh-tw" },
|
||||
{ name: "Thai", value: "th" },
|
||||
{ name: "Vietnamese", value: "vi" },
|
||||
{ name: "Indonesian", value: "id" },
|
||||
{ name: "Greek", value: "el" },
|
||||
{ name: "Swedish", value: "sv" },
|
||||
{ name: "Romanian", value: "ro" },
|
||||
];
|
||||
|
||||
function buildContainer(title, lines = [], color = null) {
|
||||
const container = new Discord.ContainerBuilder();
|
||||
|
||||
if (color) {
|
||||
container.setAccentColor(parseInt(color.replace("#", ""), 16));
|
||||
}
|
||||
|
||||
container.addTextDisplayComponents(new Discord.TextDisplayBuilder().setContent(`## ${title}`));
|
||||
|
||||
container.addSeparatorComponents(new Discord.SeparatorBuilder().setDivider(true));
|
||||
|
||||
container.addTextDisplayComponents(new Discord.TextDisplayBuilder().setContent(lines.join("\n")));
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
function trim(text, max = 1800) {
|
||||
if (text.length <= max) return text;
|
||||
return text.substring(0, max) + "...";
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Translate.Command,
|
||||
description: cmdconfig.Translate.Description,
|
||||
type: Discord.ApplicationCommandType.ChatInput,
|
||||
|
||||
options: [
|
||||
{
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
name: "from",
|
||||
description: "Language to translate FROM",
|
||||
required: true,
|
||||
choices: LANGUAGES,
|
||||
},
|
||||
{
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
name: "to",
|
||||
description: "Language to translate TO",
|
||||
required: true,
|
||||
choices: LANGUAGES.filter((l) => l.value !== "auto"),
|
||||
},
|
||||
{
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
name: "text",
|
||||
description: "Text to translate",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
|
||||
permissions: cmdconfig.Translate.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
const { getRole, getChannel } = interaction.client;
|
||||
|
||||
const Staff = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
|
||||
const Admin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
|
||||
if (!Staff || !Admin) {
|
||||
return interaction.reply({
|
||||
content: "Some roles seem to be missing!",
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!interaction.member.roles.cache.has(Staff.id) &&
|
||||
!interaction.member.roles.cache.has(Admin.id)
|
||||
) {
|
||||
return interaction.reply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2 | Discord.MessageFlags.Ephemeral,
|
||||
components: [
|
||||
buildContainer(
|
||||
"Invalid Permissions",
|
||||
[
|
||||
msgconfig.Error.IncorrectPerms,
|
||||
"",
|
||||
`Required role: \`${supportbot.Roles.StaffMember.Staff}\` or \`${supportbot.Roles.StaffMember.Admin}\``,
|
||||
],
|
||||
supportbot.Embed.Colours.Warn,
|
||||
),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: Discord.MessageFlags.Ephemeral });
|
||||
|
||||
const fromLang = interaction.options.getString("from");
|
||||
const toLang = interaction.options.getString("to");
|
||||
const text = interaction.options.getString("text");
|
||||
|
||||
const translateLog = await getChannel(supportbot.Translate?.TranslateLog, interaction.guild);
|
||||
|
||||
let result;
|
||||
|
||||
try {
|
||||
result = await translate(text, {
|
||||
from: fromLang === "auto" ? undefined : fromLang,
|
||||
to: toLang,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Translate error:", err);
|
||||
|
||||
return interaction.editReply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [
|
||||
buildContainer(
|
||||
"Translation Failed",
|
||||
["The translation service returned an error."],
|
||||
supportbot.Embed.Colours.Warn,
|
||||
),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const detectedLanguage = result.from?.language?.iso || result.from?.language || "unknown";
|
||||
|
||||
const container = buildContainer(
|
||||
"Translation",
|
||||
[
|
||||
`**Requested By:** <@${interaction.user.id}>`,
|
||||
`**From:** \`${fromLang === "auto" ? detectedLanguage : fromLang}\``,
|
||||
`**To:** \`${toLang}\``,
|
||||
"",
|
||||
"**Original Text**",
|
||||
trim(text),
|
||||
"",
|
||||
"**Translated Text**",
|
||||
trim(result.text),
|
||||
],
|
||||
supportbot.Embed.Colours.Success,
|
||||
);
|
||||
|
||||
await interaction.editReply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [container],
|
||||
});
|
||||
|
||||
if (translateLog) {
|
||||
const logContainer = buildContainer(
|
||||
"Translation Log",
|
||||
[
|
||||
`User: <@${interaction.user.id}>`,
|
||||
`Channel: <#${interaction.channel.id}>`,
|
||||
`From: ${fromLang}`,
|
||||
`To: ${toLang}`,
|
||||
"",
|
||||
trim(text),
|
||||
"",
|
||||
trim(result.text),
|
||||
],
|
||||
supportbot.Embed.Colours.General,
|
||||
);
|
||||
|
||||
translateLog
|
||||
.send({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [logContainer],
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
const fs = require("fs");
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
const path = require("path");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
const DB = require("../../Structures/Database.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: "suggest",
|
||||
description: cmdconfig.Suggestion?.Description || "Submit a new suggestion",
|
||||
type: Discord.ApplicationCommandType.ChatInput,
|
||||
options: [
|
||||
{
|
||||
name: "text",
|
||||
description: "Your suggestion text",
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
required: true
|
||||
}
|
||||
],
|
||||
|
||||
async run(interaction) {
|
||||
const suggestion = interaction.options.getString("text");
|
||||
const mode = supportbot.Suggestions.Mode || "Channel";
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.addFields(
|
||||
{ name: "Suggestion", value: suggestion, inline: true },
|
||||
{ name: "From", value: `<@${interaction.user.id}>` },
|
||||
{ name: `${supportbot.Suggestions.UpvoteEmoji} ${supportbot.Suggestions.UpvoteTitle}`, value: "0", inline: true },
|
||||
{ name: `${supportbot.Suggestions.DownvoteEmoji} ${supportbot.Suggestions.DownvoteTitle}`, value: "0", inline: true }
|
||||
)
|
||||
.setThumbnail(interaction.user.displayAvatarURL())
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
const row = new Discord.ActionRowBuilder().addComponents(
|
||||
new Discord.ButtonBuilder()
|
||||
.setCustomId("upvote")
|
||||
.setEmoji(supportbot.Suggestions.UpvoteEmoji)
|
||||
.setStyle(supportbot.Suggestions.Buttons.Upvote),
|
||||
new Discord.ButtonBuilder()
|
||||
.setCustomId("downvote")
|
||||
.setEmoji(supportbot.Suggestions.DownvoteEmoji)
|
||||
.setStyle(supportbot.Suggestions.Buttons.Downvote),
|
||||
new Discord.ButtonBuilder()
|
||||
.setCustomId("removevote")
|
||||
.setLabel(supportbot.Suggestions.Buttons.RemoveVote_Title)
|
||||
.setStyle(supportbot.Suggestions.Buttons.RemoveVote)
|
||||
);
|
||||
|
||||
if (mode === "Forum") {
|
||||
const forum = await interaction.guild.channels
|
||||
.fetch(supportbot.Suggestions.ForumChannel)
|
||||
.catch(() => null);
|
||||
|
||||
if (!forum || forum.type !== Discord.ChannelType.GuildForum) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("⚠ Missing Forum Channel")
|
||||
.setDescription(msgconfig.Error.MissingChannel)
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const appliedTags = supportbot.Suggestions.Tags?.Created
|
||||
? [supportbot.Suggestions.Tags.Created]
|
||||
: [];
|
||||
|
||||
const thread = await forum.threads.create({
|
||||
name: suggestion.slice(0, 100),
|
||||
message: {
|
||||
content: "\u200B",
|
||||
embeds: [embed],
|
||||
components: [row]
|
||||
},
|
||||
appliedTags,
|
||||
autoArchiveDuration: Discord.ThreadAutoArchiveDuration.OneDay,
|
||||
reason: "New Suggestion"
|
||||
});
|
||||
|
||||
embed.setFooter({
|
||||
text: `${supportbot.Embed.Footer} | Suggestion ID: ${thread.id}`,
|
||||
iconURL: interaction.user.displayAvatarURL()
|
||||
});
|
||||
const starter = await thread.fetchStarterMessage();
|
||||
await starter.edit({ embeds: [embed], components: [row] });
|
||||
|
||||
DB.add(thread.id, interaction.user.id, suggestion);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle(msgconfig.Suggestions.Sent_Title)
|
||||
.setDescription(`${msgconfig.Suggestions.Sent}`)
|
||||
.addFields({ name: 'Posted in:', value: `<#${forum.id}>` })
|
||||
.setColor(supportbot.Embed.Colours.Success)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- Channel Mode ----------
|
||||
const channel = await interaction.guild.channels
|
||||
.fetch(supportbot.Suggestions.Channel)
|
||||
.catch(() => null);
|
||||
|
||||
if (!channel) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("⚠ Missing Suggestion Channel")
|
||||
.setDescription(msgconfig.Error.MissingChannel)
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const message = await channel.send({ embeds: [embed], components: [row] });
|
||||
|
||||
embed.setFooter({
|
||||
text: `${supportbot.Embed.Footer} | Suggestion ID: ${message.id}`,
|
||||
iconURL: interaction.user.displayAvatarURL()
|
||||
});
|
||||
await message.edit({ embeds: [embed], components: [row] });
|
||||
|
||||
DB.add(message.id, interaction.user.id, suggestion);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle(msgconfig.Suggestions.Sent_Title)
|
||||
.setDescription(`${msgconfig.Suggestions.Sent}`)
|
||||
.addFields({ name: 'Posted in:', value: `<#${channel.id}>` })
|
||||
.setColor(supportbot.Embed.Colours.Success)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
const Discord = require("discord.js");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
const SuggestionDB = require("../../Structures/Database.js");
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.SuggestionAdmin.Command,
|
||||
description: cmdconfig.SuggestionAdmin.Description,
|
||||
type: Discord.ApplicationCommandType.ChatInput,
|
||||
permissions: cmdconfig.SuggestionAdmin.Permission,
|
||||
options: [
|
||||
{
|
||||
name: "status",
|
||||
description: "New status",
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
required: true,
|
||||
choices: [
|
||||
{ name: "Solved", value: "Solved" },
|
||||
{ name: "Denied", value: "Denied" },
|
||||
{ name: "Considering", value: "Considering" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "id",
|
||||
description: "Message ID (required in Channel mode)",
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
required: false
|
||||
}
|
||||
],
|
||||
|
||||
async run(interaction) {
|
||||
const status = interaction.options.getString("status");
|
||||
const idOption = interaction.options.getString("id");
|
||||
const mode = supportbot.Suggestions.Mode || "Channel";
|
||||
|
||||
const { getRole } = interaction.client;
|
||||
const staffRole = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
const adminRole = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
if (
|
||||
!interaction.member.roles.cache.has(staffRole?.id) &&
|
||||
!interaction.member.roles.cache.has(adminRole?.id)
|
||||
) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Invalid Permissions!")
|
||||
.setDescription(
|
||||
`${msgconfig.Error.IncorrectPerms}\nRequired: ${supportbot.Roles.StaffMember.Staff} or ${supportbot.Roles.StaffMember.Admin}`
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Warn)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (mode === "Forum") {
|
||||
const thread = interaction.channel;
|
||||
if (!thread.isThread() || thread.parentId !== supportbot.Suggestions.ForumChannel) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Not a Suggestion Thread")
|
||||
.setDescription(msgconfig.Error.MissingChannel)
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const tagMap = {
|
||||
Solved: supportbot.Suggestions.Tags.Solved,
|
||||
Denied: supportbot.Suggestions.Tags.Denied,
|
||||
Considering: supportbot.Suggestions.Tags.Considering
|
||||
};
|
||||
const tagId = tagMap[status];
|
||||
if (!tagId) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Tag Missing")
|
||||
.setDescription("No forum tag configured for this status.")
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
await thread.setAppliedTags([tagId]).catch(() => null);
|
||||
SuggestionDB.setStatus(thread.id, status);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Suggestion Updated")
|
||||
.setDescription(`Status set to **${status}**.`)
|
||||
.setColor(supportbot.Embed.Colours.Success)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (!idOption) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Message ID Required")
|
||||
.setDescription("Provide the suggestion’s message ID when in Channel mode.")
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const channel = await interaction.guild.channels
|
||||
.fetch(supportbot.Suggestions.Channel)
|
||||
.catch(() => null);
|
||||
if (!channel) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Missing Suggestion Channel")
|
||||
.setDescription(msgconfig.Error.MissingChannel)
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const targetMsg = await channel.messages.fetch(idOption).catch(() => null);
|
||||
if (!targetMsg) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Message Not Found")
|
||||
.setDescription("Could not fetch a suggestion with that ID.")
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const oldEmbed = targetMsg.embeds[0];
|
||||
if (!oldEmbed) {
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("No Embed Found")
|
||||
.setDescription("The target message has no suggestion embed.")
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const colorMap = {
|
||||
Solved: supportbot.Embed.Colours.Success,
|
||||
Denied: supportbot.Embed.Colours.Error,
|
||||
Considering: supportbot.Embed.Colours.Warn
|
||||
};
|
||||
|
||||
const newEmbed = Discord.EmbedBuilder.from(oldEmbed)
|
||||
.setColor(colorMap[status])
|
||||
.addFields({ name: "Status", value: status, inline: true });
|
||||
|
||||
await targetMsg.edit({ embeds: [newEmbed], components: targetMsg.components });
|
||||
SuggestionDB.setStatus(idOption, status);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [
|
||||
new Discord.EmbedBuilder()
|
||||
.setTitle("Suggestion Updated")
|
||||
.setDescription(`Suggestion **${idOption}** marked as **${status}**.`)
|
||||
.setColor(supportbot.Embed.Colours.Success)
|
||||
],
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Info Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
|
||||
async function asyncForEach(array, callback) {
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
await callback(array[index], index, array);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.TicketAdd,
|
||||
description: cmdconfig.TicketAddDesc,
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
let SupportStaff = message.guild.roles.cache.find(SupportTeam => SupportTeam.name === supportbot.Staff) || message.guild.roles.cache.find(SupportTeam => SupportTeam.id === supportbot.Staff)
|
||||
let Admins = message.guild.roles.cache.find(AdminUser => AdminUser.name === supportbot.Admin) || message.guild.roles.cache.find(AdminUser => AdminUser.id === supportbot.Admin)
|
||||
|
||||
const NoPerms = new Discord.MessageEmbed()
|
||||
.setTitle("Invalid Permissions!")
|
||||
.setDescription(`${supportbot.IncorrectPerms}\n\nRole Required: \`${supportbot.Staff}\` or \`${supportbot.Admin}\``)
|
||||
.setColor(supportbot.WarningColour)
|
||||
|
||||
if (message.member.roles.cache.has(SupportStaff.id) || message.member.roles.cache.has(Admins.id)) {
|
||||
if (!message.channel.name.startsWith( `${supportbot.TicketChannel}-` )) {
|
||||
const Exists = new Discord.MessageEmbed()
|
||||
.setTitle("No Ticket Found!")
|
||||
.setDescription(`${supportbot.NoValidTicket}`)
|
||||
.setColor(supportbot.WarningColour);
|
||||
message.channel.send({ embeds: [Exists] });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let uMember = message.mentions.users.first();
|
||||
const UserNotExist = new Discord.MessageEmbed()
|
||||
.setTitle("User Not Found!")
|
||||
.setDescription(`${supportbot.UserNotFound}\n\nTry Again:\`${supportbot.Prefix}${cmdconfig.TicketAdd} <user#0000>\``)
|
||||
.setColor(supportbot.ErrorColour)
|
||||
|
||||
if (!uMember) return message.channel.send({ embeds: [UserNotExist] });
|
||||
|
||||
message.channel.permissionOverwrites.edit(uMember, {
|
||||
VIEW_CHANNEL: true,
|
||||
READ_MESSAGE_HISTORY: true,
|
||||
SEND_MESSAGES: true,
|
||||
});
|
||||
|
||||
const Complete = new Discord.MessageEmbed()
|
||||
.setTitle("User Added!")
|
||||
.setDescription(supportbot.AddedUser.replace(/%user%/g, uMember.id))
|
||||
.setTimestamp()
|
||||
.setColor(supportbot.EmbedColour)
|
||||
message.channel.send({ embeds: [Complete] });
|
||||
} else {
|
||||
|
||||
return message.channel.send({ embeds: [NoPerms] });
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Info Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
|
||||
async function asyncForEach(array, callback) {
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
await callback(array[index], index, array);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.TicketRemove,
|
||||
description: cmdconfig.TicketRemoveDesc,
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
let SupportStaff = message.guild.roles.cache.find(SupportTeam => SupportTeam.name === supportbot.Staff) || message.guild.roles.cache.find(SupportTeam => SupportTeam.id === supportbot.Staff)
|
||||
let Admins = message.guild.roles.cache.find(AdminUser => AdminUser.name === supportbot.Admin) || message.guild.roles.cache.find(AdminUser => AdminUser.id === supportbot.Admin)
|
||||
|
||||
const NoPerms = new Discord.MessageEmbed()
|
||||
.setTitle("Invalid Permissions!")
|
||||
.setDescription(`${supportbot.IncorrectPerms}\n\nRole Required: \`${supportbot.Staff}\` or \`${supportbot.Admin}\``)
|
||||
.setColor(supportbot.WarningColour)
|
||||
|
||||
if (message.member.roles.cache.has(SupportStaff.id) || message.member.roles.cache.has(Admins.id)) {
|
||||
if (!message.channel.name.startsWith( `${supportbot.TicketChannel}-` )) {
|
||||
const Exists = new Discord.MessageEmbed()
|
||||
.setTitle("No Ticket Found!")
|
||||
.setDescription(`${supportbot.NoValidTicket}`)
|
||||
.setColor(supportbot.WarningColour);
|
||||
message.channel.send({ embeds: [Exists] });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let uMember = message.mentions.users.first();
|
||||
const UserNotExist = new Discord.MessageEmbed()
|
||||
.setTitle("User Not Found!")
|
||||
.setDescription(`${supportbot.UserNotFound}\n\nTry Again:\`${supportbot.Prefix}${cmdconfig.TicketRemove} <user#0000>\``)
|
||||
.setColor(supportbot.ErrorColour)
|
||||
|
||||
if (!uMember) return message.channel.send({ embeds: [UserNotExist] });
|
||||
|
||||
message.channel.permissionOverwrites.edit(uMember, {
|
||||
VIEW_CHANNEL: false,
|
||||
READ_MESSAGE_HISTORY: false,
|
||||
SEND_MESSAGES: false,
|
||||
});
|
||||
|
||||
const Complete = new Discord.MessageEmbed()
|
||||
.setTitle("User Removed!")
|
||||
.setDescription(supportbot.RemovedUser.replace(/%user%/g, uMember.id))
|
||||
.setTimestamp()
|
||||
.setColor(supportbot.EmbedColour)
|
||||
message.channel.send({ embeds: [Complete] });
|
||||
} else {
|
||||
|
||||
return message.channel.send({ embeds: [NoPerms] });
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
@@ -0,0 +1,493 @@
|
||||
|
||||
|
||||
const fs = require("fs");
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const db = require("../../Structures/Database.js");
|
||||
const TicketManager = require("../../Structures/TicketManager.js");
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
function getDepartmentConfig(departmentKey) {
|
||||
return supportbot.Ticket?.DepartmentSystem?.Departments?.[departmentKey] || null;
|
||||
}
|
||||
|
||||
function getTicketUserId(ticket) {
|
||||
return ticket?.user || ticket?.user_id || null;
|
||||
}
|
||||
|
||||
function buildContainer(title, lines = []) {
|
||||
const container = new Discord.ContainerBuilder();
|
||||
|
||||
if (supportbot.Embed?.Colours?.General) {
|
||||
container.setAccentColor(
|
||||
parseInt(String(supportbot.Embed.Colours.General).replace("#", ""), 16),
|
||||
);
|
||||
}
|
||||
|
||||
container.addTextDisplayComponents(new Discord.TextDisplayBuilder().setContent(`## ${title}`));
|
||||
|
||||
container.addSeparatorComponents(new Discord.SeparatorBuilder().setDivider(true));
|
||||
|
||||
if (lines.length > 0) {
|
||||
container.addTextDisplayComponents(
|
||||
new Discord.TextDisplayBuilder().setContent(lines.join("\n")),
|
||||
);
|
||||
}
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
function buildReviewSummaryContainer(ticket, rating, comment) {
|
||||
const departmentConfig = ticket.department ? getDepartmentConfig(ticket.department) : null;
|
||||
const departmentName = departmentConfig?.Name || ticket.department || null;
|
||||
const departmentEmoji = departmentConfig?.Emoji || "🎫";
|
||||
|
||||
const claimedByEnabled = supportbot.Ticket?.ClaimTickets?.Enabled === true;
|
||||
const claimedBy = claimedByEnabled && ticket.claimedBy ? `<@${ticket.claimedBy}>` : null;
|
||||
|
||||
const ticketUserId = getTicketUserId(ticket);
|
||||
const lines = [
|
||||
`**${msgconfig.ReviewSystem.ReviewEmbed.ReviewedByTitle}** ${ticketUserId ? `<@${ticketUserId}>` : "Unknown User"}`,
|
||||
];
|
||||
|
||||
if (claimedBy) {
|
||||
lines.unshift(`**${msgconfig.ReviewSystem.ReviewEmbed.ReviewedStaffTitle}** ${claimedBy}`);
|
||||
}
|
||||
|
||||
if (supportbot.Ticket?.DepartmentSystem?.Enabled === true && departmentName) {
|
||||
lines.push(`**Department** ${departmentEmoji} ${departmentName}`);
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
lines.push(`**${msgconfig.ReviewSystem.ReviewEmbed.RatingTitle}**`);
|
||||
lines.push(`${msgconfig.ReviewSystem.ReviewEmbed.ReviewEmoji.repeat(Number(rating))}`);
|
||||
lines.push("");
|
||||
lines.push(`**${msgconfig.ReviewSystem.ReviewEmbed.CommentTitle}**`);
|
||||
lines.push(comment || "No Comment Provided");
|
||||
|
||||
const container = new Discord.ContainerBuilder();
|
||||
|
||||
if (msgconfig.ReviewSystem?.ReviewEmbed?.Color) {
|
||||
container.setAccentColor(
|
||||
parseInt(String(msgconfig.ReviewSystem.ReviewEmbed.Color).replace("#", ""), 16),
|
||||
);
|
||||
} else if (supportbot.Embed?.Colours?.General) {
|
||||
container.setAccentColor(
|
||||
parseInt(String(supportbot.Embed.Colours.General).replace("#", ""), 16),
|
||||
);
|
||||
}
|
||||
|
||||
container.addTextDisplayComponents(
|
||||
new Discord.TextDisplayBuilder().setContent(`## ${msgconfig.ReviewSystem.ReviewEmbed.Title}`),
|
||||
);
|
||||
|
||||
container.addSeparatorComponents(new Discord.SeparatorBuilder().setDivider(true));
|
||||
|
||||
container.addTextDisplayComponents(new Discord.TextDisplayBuilder().setContent(lines.join("\n")));
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
async function collectReview(interaction, ticket) {
|
||||
const ticketUserId = getTicketUserId(ticket);
|
||||
if (!ticketUserId) return null;
|
||||
|
||||
const ratingContainer = buildContainer(msgconfig.ReviewSystem.Rate.Title, [
|
||||
msgconfig.ReviewSystem.Rate.Description,
|
||||
"",
|
||||
]);
|
||||
|
||||
const ratingRow = new Discord.ActionRowBuilder().addComponents(
|
||||
new Discord.StringSelectMenuBuilder()
|
||||
.setCustomId(`closeReviewRating:${interaction.id}`)
|
||||
.setPlaceholder("Select a rating")
|
||||
.addOptions([
|
||||
{ label: msgconfig.ReviewSystem.Stars.One, value: "1" },
|
||||
{ label: msgconfig.ReviewSystem.Stars.Two, value: "2" },
|
||||
{ label: msgconfig.ReviewSystem.Stars.Three, value: "3" },
|
||||
{ label: msgconfig.ReviewSystem.Stars.Four, value: "4" },
|
||||
{ label: msgconfig.ReviewSystem.Stars.Five, value: "5" },
|
||||
]),
|
||||
);
|
||||
|
||||
ratingContainer.addActionRowComponents(ratingRow);
|
||||
|
||||
const ratingPrompt = await interaction.followUp({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [ratingContainer],
|
||||
});
|
||||
|
||||
let rating = null;
|
||||
|
||||
try {
|
||||
const ratingInteraction = await ratingPrompt.awaitMessageComponent({
|
||||
componentType: Discord.ComponentType.StringSelect,
|
||||
time: 120000,
|
||||
filter: (i) =>
|
||||
i.customId === `closeReviewRating:${interaction.id}` && i.user.id === ticketUserId,
|
||||
});
|
||||
|
||||
rating = ratingInteraction.values[0];
|
||||
await ratingInteraction.deferUpdate().catch(() => {});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const commentContainer = buildContainer(msgconfig.ReviewSystem.Comment.Title, [
|
||||
msgconfig.ReviewSystem.Comment.Description,
|
||||
"",
|
||||
]);
|
||||
|
||||
const commentRow = new Discord.ActionRowBuilder().addComponents(
|
||||
new Discord.ButtonBuilder()
|
||||
.setCustomId(`closeReviewWrite:${interaction.id}`)
|
||||
.setLabel("Write Comment")
|
||||
.setStyle(Discord.ButtonStyle.Secondary),
|
||||
new Discord.ButtonBuilder()
|
||||
.setCustomId(`closeReviewSkip:${interaction.id}`)
|
||||
.setLabel("Skip Comment")
|
||||
.setStyle(Discord.ButtonStyle.Danger),
|
||||
);
|
||||
|
||||
commentContainer.addActionRowComponents(commentRow);
|
||||
|
||||
const commentPrompt = await interaction.followUp({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [commentContainer],
|
||||
});
|
||||
|
||||
let comment = "No Comment Provided";
|
||||
|
||||
try {
|
||||
const buttonInteraction = await commentPrompt.awaitMessageComponent({
|
||||
componentType: Discord.ComponentType.Button,
|
||||
time: 120000,
|
||||
filter: (i) =>
|
||||
(i.customId === `closeReviewWrite:${interaction.id}` ||
|
||||
i.customId === `closeReviewSkip:${interaction.id}`) &&
|
||||
i.user.id === ticketUserId,
|
||||
});
|
||||
|
||||
if (buttonInteraction.customId === `closeReviewSkip:${interaction.id}`) {
|
||||
await buttonInteraction.deferUpdate().catch(() => {});
|
||||
return { rating, comment };
|
||||
}
|
||||
|
||||
await buttonInteraction
|
||||
.update({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [
|
||||
buildContainer(msgconfig.ReviewSystem.Comment.Title, [
|
||||
`Requested from: <@${ticketUserId}>`,
|
||||
"",
|
||||
"Please send your review comment in the channel now.",
|
||||
"Type `no` to skip.",
|
||||
]),
|
||||
],
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
const collected = await interaction.channel.awaitMessages({
|
||||
max: 1,
|
||||
time: 120000,
|
||||
filter: (m) => m.author.id === ticketUserId,
|
||||
});
|
||||
|
||||
const message = collected.first();
|
||||
|
||||
if (message) {
|
||||
const rawComment = message.content?.trim();
|
||||
if (rawComment && rawComment.toLowerCase() !== "no") {
|
||||
comment = rawComment;
|
||||
}
|
||||
|
||||
await message.delete().catch(() => {});
|
||||
}
|
||||
} catch {
|
||||
return { rating, comment };
|
||||
}
|
||||
|
||||
return { rating, comment };
|
||||
}
|
||||
|
||||
function getTranscriptAttachmentFromResult(result) {
|
||||
if (!result) return null;
|
||||
|
||||
if (typeof result === "string") {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (result.filePath) return result.filePath;
|
||||
if (result.attachment) return result.attachment;
|
||||
if (result.path) return result.path;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function maybeDMTranscript(interaction, ticket, transcriptResult) {
|
||||
if (supportbot.Ticket?.UserManagement?.DMTranscript !== true) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ticketUserId = getTicketUserId(ticket);
|
||||
if (!ticketUserId) return;
|
||||
|
||||
const ticketUser = await interaction.client.users.fetch(ticketUserId).catch(() => null);
|
||||
|
||||
if (!ticketUser) return;
|
||||
|
||||
const attachmentPath = getTranscriptAttachmentFromResult(transcriptResult);
|
||||
if (!attachmentPath) return;
|
||||
|
||||
try {
|
||||
await ticketUser.send({
|
||||
content: `Here is a copy of your ticket transcript from \`${interaction.guild.name}\`.`,
|
||||
files: [attachmentPath],
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to DM transcript to user:", error);
|
||||
}
|
||||
}
|
||||
|
||||
async function collectCloseConfirmation(interaction, ticket, reason) {
|
||||
const ticketUserId = getTicketUserId(ticket);
|
||||
|
||||
const lines = [
|
||||
"Are you sure you want to close this ticket?",
|
||||
"",
|
||||
`**Ticket:** ${interaction.channel.name}`,
|
||||
`**Reason:** ${reason || "No Reason Provided."}`,
|
||||
];
|
||||
|
||||
if (ticketUserId) {
|
||||
lines.push(`**Ticket User:** <@${ticketUserId}>`);
|
||||
}
|
||||
|
||||
if (supportbot.Ticket?.ReviewSystem?.Enabled === true) {
|
||||
lines.push("");
|
||||
lines.push("A review will be requested before the ticket is closed.");
|
||||
}
|
||||
|
||||
const confirmContainer = buildContainer("Close Confirmation", lines);
|
||||
|
||||
const confirmRow = new Discord.ActionRowBuilder().addComponents(
|
||||
new Discord.ButtonBuilder()
|
||||
.setCustomId(`confirmClose:${interaction.id}`)
|
||||
.setLabel("Confirm Close")
|
||||
.setStyle(Discord.ButtonStyle.Danger),
|
||||
new Discord.ButtonBuilder()
|
||||
.setCustomId(`cancelClose:${interaction.id}`)
|
||||
.setLabel("Cancel")
|
||||
.setStyle(Discord.ButtonStyle.Secondary),
|
||||
);
|
||||
|
||||
confirmContainer.addActionRowComponents(confirmRow);
|
||||
|
||||
const confirmMessage = await interaction.editReply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [confirmContainer],
|
||||
});
|
||||
|
||||
try {
|
||||
const buttonInteraction = await confirmMessage.awaitMessageComponent({
|
||||
componentType: Discord.ComponentType.Button,
|
||||
time: 120000,
|
||||
filter: (i) =>
|
||||
(i.customId === `confirmClose:${interaction.id}` ||
|
||||
i.customId === `cancelClose:${interaction.id}`) &&
|
||||
i.user.id === interaction.user.id,
|
||||
});
|
||||
|
||||
if (buttonInteraction.customId === `cancelClose:${interaction.id}`) {
|
||||
await buttonInteraction
|
||||
.update({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [
|
||||
buildContainer("Close Cancelled", ["The ticket close process has been cancelled."]),
|
||||
],
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
await buttonInteraction.deferUpdate().catch(() => {});
|
||||
return true;
|
||||
} catch {
|
||||
await interaction
|
||||
.editReply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [buildContainer("Close Cancelled", ["The close confirmation timed out."])],
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function postReview(interaction, ticket, reviewData) {
|
||||
const { getChannel } = interaction.client;
|
||||
const reviewChannel = await getChannel(supportbot.Ticket.ReviewSystem.Channel, interaction.guild);
|
||||
|
||||
if (!reviewChannel || !reviewData) return;
|
||||
|
||||
const reviewContainer = buildReviewSummaryContainer(
|
||||
ticket,
|
||||
reviewData.rating,
|
||||
reviewData.comment,
|
||||
);
|
||||
|
||||
await reviewChannel
|
||||
.send({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [reviewContainer],
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
async function handleCloseTicket(interaction, reason, ticket) {
|
||||
try {
|
||||
if (typeof db.updateTicketStatus === "function") {
|
||||
db.updateTicketStatus(interaction.channel.id, "closed");
|
||||
}
|
||||
|
||||
const transcriptResult = await TicketManager.createTranscript(interaction, ticket, reason);
|
||||
|
||||
await maybeDMTranscript(interaction, ticket, transcriptResult);
|
||||
|
||||
await interaction
|
||||
.editReply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [
|
||||
buildContainer("Ticket Closed", [
|
||||
`**Ticket:** ${interaction.channel.name}`,
|
||||
`**Closed By:** <@${interaction.user.id}>`,
|
||||
`**Reason:** ${reason || "No Reason Provided."}`,
|
||||
]),
|
||||
],
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
await interaction.channel.delete().catch(() => {});
|
||||
} catch (err) {
|
||||
console.error("Error handling ticket close:", err);
|
||||
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
await interaction
|
||||
.editReply({
|
||||
content: "An error occurred while closing the ticket.",
|
||||
components: [],
|
||||
})
|
||||
.catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction
|
||||
.reply({
|
||||
content: "An error occurred while closing the ticket.",
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.CloseTicket.Command,
|
||||
description: cmdconfig.CloseTicket.Description,
|
||||
type: Discord.ApplicationCommandType.ChatInput,
|
||||
options: [
|
||||
{
|
||||
name: "reason",
|
||||
description: "Ticket Close Reason",
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
},
|
||||
],
|
||||
permissions: cmdconfig.CloseTicket.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
const { getRole } = interaction.client;
|
||||
|
||||
if (supportbot.Ticket.Close.StaffOnly) {
|
||||
const SupportStaff = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
const Admin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
|
||||
if (!SupportStaff || !Admin) {
|
||||
return interaction.reply({
|
||||
content: "Some roles seem to be missing! Please check for errors when starting the bot.",
|
||||
flags: Discord.MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!interaction.member.roles.cache.has(SupportStaff.id) &&
|
||||
!interaction.member.roles.cache.has(Admin.id)
|
||||
) {
|
||||
return interaction.reply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2 | Discord.MessageFlags.Ephemeral,
|
||||
components: [
|
||||
buildContainer("Invalid Permissions!", [
|
||||
msgconfig.Error.IncorrectPerms,
|
||||
"",
|
||||
`Role Required: \`${supportbot.Roles.StaffMember.Staff}\` or \`${supportbot.Roles.StaffMember.Admin}\``,
|
||||
]),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const isThread = interaction.channel.type === Discord.ChannelType.PrivateThread;
|
||||
|
||||
if (
|
||||
(supportbot.Ticket.TicketType === "threads" && !isThread) ||
|
||||
(supportbot.Ticket.TicketType === "channels" &&
|
||||
interaction.channel.type !== Discord.ChannelType.GuildText)
|
||||
) {
|
||||
return interaction.reply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2 | Discord.MessageFlags.Ephemeral,
|
||||
components: [
|
||||
buildContainer("Invalid Channel!", [
|
||||
`This command can only be used in a ${
|
||||
supportbot.Ticket.TicketType === "threads" ? "ticket thread" : "ticket channel"
|
||||
}.`,
|
||||
]),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: Discord.MessageFlags.Ephemeral });
|
||||
|
||||
const ticket = db.getTicket(interaction.channel.id);
|
||||
|
||||
if (!ticket) {
|
||||
return interaction.editReply({
|
||||
flags: Discord.MessageFlags.IsComponentsV2,
|
||||
components: [buildContainer("No Ticket Found!", [msgconfig.Error.NoValidTicket])],
|
||||
});
|
||||
}
|
||||
|
||||
const reason = interaction.options?.getString("reason") || "No Reason Provided.";
|
||||
|
||||
const confirmed = await collectCloseConfirmation(interaction, ticket, reason);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (supportbot.Ticket?.ReviewSystem?.Enabled === true) {
|
||||
const reviewData = await collectReview(interaction, ticket);
|
||||
|
||||
if (reviewData) {
|
||||
await postReview(interaction, ticket, reviewData);
|
||||
}
|
||||
|
||||
await handleCloseTicket(interaction, reason, ticket);
|
||||
return;
|
||||
}
|
||||
|
||||
await handleCloseTicket(interaction, reason, ticket);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,664 @@
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const {
|
||||
EmbedBuilder,
|
||||
ApplicationCommandOptionType,
|
||||
ApplicationCommandType,
|
||||
ChannelType,
|
||||
MessageFlags,
|
||||
ModalBuilder,
|
||||
ActionRowBuilder,
|
||||
TextInputBuilder,
|
||||
TextInputStyle,
|
||||
} = require("discord.js");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
|
||||
const TicketManager = require("../../Structures/TicketManager.js");
|
||||
const Command = require("../../Structures/Command.js");
|
||||
const db = require("../../Structures/Database.js");
|
||||
|
||||
function getDepartments() {
|
||||
return supportbot.Ticket?.DepartmentSystem?.Departments || {};
|
||||
}
|
||||
|
||||
function getPriorities() {
|
||||
return supportbot.Ticket?.PrioritySystem?.Priorities || {};
|
||||
}
|
||||
|
||||
function prioritiesEnabled() {
|
||||
return (
|
||||
supportbot.Ticket?.TicketType !== "threads" &&
|
||||
supportbot.Ticket?.PrioritySystem?.Enabled === true
|
||||
);
|
||||
}
|
||||
|
||||
function departmentsEnabled() {
|
||||
return (
|
||||
supportbot.Ticket?.TicketType !== "threads" &&
|
||||
supportbot.Ticket?.DepartmentSystem?.Enabled === true
|
||||
);
|
||||
}
|
||||
|
||||
function buildTicketChannelName(ticketNumberID, priorityKey, departmentConfig) {
|
||||
const defaultPrefix = supportbot.Ticket?.ChannelPrefix || supportbot.Ticket?.Channel || "ticket-";
|
||||
|
||||
const departmentPrefix = departmentConfig?.ChannelPrefix || defaultPrefix;
|
||||
|
||||
const safePrefix = String(departmentPrefix).trim() || "ticket-";
|
||||
const baseName = `${safePrefix}${ticketNumberID}`;
|
||||
|
||||
if (!prioritiesEnabled() || !priorityKey) {
|
||||
return baseName;
|
||||
}
|
||||
|
||||
return `${baseName}-${String(priorityKey).toLowerCase()}`;
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.TicketManage?.Command || "ticketmanage",
|
||||
description: cmdconfig.TicketManage?.Description || "Manage tickets",
|
||||
type: ApplicationCommandType.ChatInput,
|
||||
permissions: cmdconfig.TicketManage?.Permission || ["ManageChannels"],
|
||||
|
||||
options: [
|
||||
{
|
||||
name: "transfer",
|
||||
description: "Transfer a ticket to another department",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: "department",
|
||||
description: "Department to transfer this ticket to",
|
||||
type: ApplicationCommandOptionType.String,
|
||||
required: true,
|
||||
choices: Object.entries(getDepartments())
|
||||
.slice(0, 25)
|
||||
.map(([key, dept]) => ({
|
||||
name: dept.Name || key,
|
||||
value: key,
|
||||
})),
|
||||
},
|
||||
{
|
||||
name: "priority",
|
||||
description: "Optional new priority",
|
||||
type: ApplicationCommandOptionType.String,
|
||||
required: false,
|
||||
choices: Object.entries(getPriorities())
|
||||
.slice(0, 25)
|
||||
.map(([key, priority]) => ({
|
||||
name: priority.Name || key,
|
||||
value: key,
|
||||
})),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "priority",
|
||||
description: "Change a ticket priority",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: "level",
|
||||
description: "New priority level",
|
||||
type: ApplicationCommandOptionType.String,
|
||||
required: true,
|
||||
choices: Object.entries(getPriorities())
|
||||
.slice(0, 25)
|
||||
.map(([key, priority]) => ({
|
||||
name: priority.Name || key,
|
||||
value: key,
|
||||
})),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: cmdconfig.TicketManage?.ForceAdd?.Command || "forceadd",
|
||||
description:
|
||||
cmdconfig.TicketManage?.ForceAdd?.Description || "Force add a user to the current ticket",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: "user",
|
||||
description: "The user to add",
|
||||
type: ApplicationCommandOptionType.User,
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: cmdconfig.TicketManage?.ForceRemove?.Command || "forceremove",
|
||||
description:
|
||||
cmdconfig.TicketManage?.ForceRemove?.Description || "Remove a user from the current ticket",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: "user",
|
||||
description: "The user to remove",
|
||||
type: ApplicationCommandOptionType.User,
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: cmdconfig.TicketManage?.Rename?.Command || "rename",
|
||||
description: cmdconfig.TicketManage?.Rename?.Description || "Rename the current ticket",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [],
|
||||
},
|
||||
{
|
||||
name: cmdconfig.TicketManage?.Close?.Command || "close",
|
||||
description: cmdconfig.TicketManage?.Close?.Description || "Close the current ticket",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: "reason",
|
||||
description: "Reason for closing the ticket",
|
||||
type: ApplicationCommandOptionType.String,
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
async run(interaction) {
|
||||
try {
|
||||
const subcommand = interaction.options.getSubcommand(false);
|
||||
const ticket = db.getTicket(interaction.channel.id);
|
||||
|
||||
if (!ticket) {
|
||||
return interaction.reply({
|
||||
content: "This channel is not a ticket.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const { getRole } = interaction.client;
|
||||
|
||||
let SupportStaff = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
let Admin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
let Moderator = await getRole(supportbot.Roles.StaffMember.Moderator, interaction.guild);
|
||||
|
||||
if (!SupportStaff || !Admin || !Moderator) {
|
||||
const missingRolesEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Error.InvalidChannel || "Required roles are missing!")
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [missingRolesEmbed],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const NoPerms = new EmbedBuilder()
|
||||
.setDescription(
|
||||
msgconfig.Error.IncorrectPerms || "You do not have the correct permissions!",
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
|
||||
if (
|
||||
!interaction.member.roles.cache.has(Admin.id) &&
|
||||
!interaction.member.roles.cache.has(Moderator.id) &&
|
||||
(!supportbot.Roles?.Mod?.AllowSupportStaff || !interaction.member.roles.cache.has(SupportStaff.id))
|
||||
) {
|
||||
return interaction.reply({
|
||||
embeds: [NoPerms],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (subcommand === "transfer") {
|
||||
if (!departmentsEnabled()) {
|
||||
return interaction.reply({
|
||||
content: "Departments are disabled, or ticket mode is set to threads.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (interaction.channel.type !== ChannelType.GuildText) {
|
||||
return interaction.reply({
|
||||
content: "Ticket transfer only works for ticket channels.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const departmentKey = interaction.options.getString("department");
|
||||
const requestedPriority = interaction.options.getString("priority");
|
||||
|
||||
const departments = getDepartments();
|
||||
const departmentConfig = departments[departmentKey];
|
||||
|
||||
if (!departmentConfig) {
|
||||
return interaction.reply({
|
||||
content: "That department does not exist.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const targetCategoryId = departmentConfig.Category;
|
||||
const targetRoleId = departmentConfig.Role || null;
|
||||
|
||||
if (!targetCategoryId) {
|
||||
return interaction.reply({
|
||||
content: "That department does not have a category configured.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const targetCategory = interaction.guild.channels.cache.get(targetCategoryId);
|
||||
if (!targetCategory) {
|
||||
return interaction.reply({
|
||||
content: "The target department category could not be found.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
let finalPriority = ticket.priority || null;
|
||||
|
||||
if (requestedPriority) {
|
||||
finalPriority = requestedPriority;
|
||||
} else if (!finalPriority && departmentConfig.DefaultPriority) {
|
||||
finalPriority = departmentConfig.DefaultPriority;
|
||||
}
|
||||
|
||||
const oldDepartmentKey = ticket.department || null;
|
||||
const oldDepartmentConfig = oldDepartmentKey ? departments[oldDepartmentKey] : null;
|
||||
const oldRoleId = oldDepartmentConfig?.Role || null;
|
||||
|
||||
await interaction.channel.setParent(targetCategory.id);
|
||||
|
||||
if (oldRoleId && oldRoleId !== targetRoleId) {
|
||||
await interaction.channel.permissionOverwrites.delete(oldRoleId).catch(() => { });
|
||||
}
|
||||
|
||||
if (targetRoleId) {
|
||||
await interaction.channel.permissionOverwrites.create(targetRoleId, {
|
||||
ViewChannel: true,
|
||||
SendMessages: true,
|
||||
ReadMessageHistory: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof db.updateTicketDepartment === "function") {
|
||||
db.updateTicketDepartment(interaction.channel.id, departmentKey);
|
||||
}
|
||||
|
||||
if (finalPriority && typeof db.updateTicketPriority === "function") {
|
||||
db.updateTicketPriority(interaction.channel.id, finalPriority);
|
||||
}
|
||||
|
||||
const ticketNumber = ticket.number || interaction.channel.name.replace(/\D/g, "");
|
||||
|
||||
const newChannelName = buildTicketChannelName(
|
||||
ticketNumber,
|
||||
finalPriority,
|
||||
departmentConfig,
|
||||
);
|
||||
|
||||
if (interaction.channel.name !== newChannelName) {
|
||||
await interaction.channel.setName(newChannelName).catch(() => { });
|
||||
}
|
||||
|
||||
const deptEmoji = departmentConfig.Emoji || "🎫";
|
||||
const deptName = departmentConfig.Name || departmentKey;
|
||||
|
||||
let description = `> **Department:** ${deptEmoji} ${deptName}`;
|
||||
|
||||
if (finalPriority && prioritiesEnabled()) {
|
||||
const priorityConfig = getPriorities()[finalPriority];
|
||||
const priorityEmoji = priorityConfig?.Emoji || "🟡";
|
||||
const priorityName = priorityConfig?.Name || finalPriority;
|
||||
description += `\n> **Priority:** ${priorityEmoji} ${priorityName}`;
|
||||
}
|
||||
|
||||
description += `\n> **Transferred By:** <@${interaction.user.id}>`;
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle("Ticket Updated")
|
||||
.setDescription(description)
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [embed],
|
||||
});
|
||||
}
|
||||
|
||||
if (subcommand === "priority") {
|
||||
if (!prioritiesEnabled()) {
|
||||
return interaction.reply({
|
||||
content: "Priority is disabled, or ticket mode is set to threads.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const level = interaction.options.getString("level");
|
||||
const priorityConfig = getPriorities()[level];
|
||||
|
||||
if (!priorityConfig) {
|
||||
return interaction.reply({
|
||||
content: "That priority does not exist.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof db.updateTicketPriority === "function") {
|
||||
db.updateTicketPriority(interaction.channel.id, level);
|
||||
}
|
||||
|
||||
const departments = getDepartments();
|
||||
const departmentConfig = ticket.department ? departments[ticket.department] : null;
|
||||
const ticketNumber = ticket.number || interaction.channel.name.replace(/\D/g, "");
|
||||
|
||||
const newChannelName = buildTicketChannelName(ticketNumber, level, departmentConfig);
|
||||
|
||||
if (interaction.channel.name !== newChannelName) {
|
||||
await interaction.channel.setName(newChannelName).catch(() => { });
|
||||
}
|
||||
|
||||
const priorityEmoji = priorityConfig.Emoji || "🟡";
|
||||
const priorityName = priorityConfig.Name || level;
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle("Ticket Updated")
|
||||
.setDescription(
|
||||
`> **Priority:** ${priorityEmoji} ${priorityName}\n> **Updated By:** <@${interaction.user.id}>`,
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [embed],
|
||||
});
|
||||
}
|
||||
|
||||
if (subcommand === (cmdconfig.TicketManage?.ForceAdd?.Command || "forceadd")) {
|
||||
const userToAdd = interaction.options.getUser("user");
|
||||
const ticketChannel = interaction.channel;
|
||||
|
||||
if (
|
||||
(supportbot.Ticket.TicketType === "threads" && !ticketChannel.isThread()) ||
|
||||
(supportbot.Ticket.TicketType === "channels" &&
|
||||
ticketChannel.type !== ChannelType.GuildText)
|
||||
) {
|
||||
const onlyInTicket = new EmbedBuilder()
|
||||
.setTitle(msgconfig.ForceAddUser.NotInTicket_Title)
|
||||
.setDescription(msgconfig.ForceAddUser.NotInTicket_Description)
|
||||
.setColor(supportbot.Embed.Colours.Error);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [onlyInTicket],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const ticketRow = db.getTicket(ticketChannel.id);
|
||||
if (!ticketRow) {
|
||||
const notFound = new EmbedBuilder()
|
||||
.setTitle(msgconfig.ForceAddUser.NotInTicket_Title)
|
||||
.setDescription(msgconfig.ForceAddUser.NotInTicket_Description)
|
||||
.setColor(supportbot.Embed.Colours.Error);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [notFound],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
if (supportbot.Ticket.TicketType === "threads") {
|
||||
const botMember = await ticketChannel.members
|
||||
.fetch(interaction.client.user.id)
|
||||
.catch(() => null);
|
||||
|
||||
if (!botMember) await ticketChannel.join();
|
||||
|
||||
await new Promise((res) => setTimeout(res, 1000));
|
||||
await ticketChannel.members.add(userToAdd.id);
|
||||
} else {
|
||||
await ticketChannel.permissionOverwrites.create(userToAdd.id, {
|
||||
ViewChannel: true,
|
||||
SendMessages: true,
|
||||
ReadMessageHistory: true,
|
||||
});
|
||||
}
|
||||
|
||||
db.addUserToTicket(ticketChannel.id, userToAdd.id);
|
||||
|
||||
const addedEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.ForceAddUser.Added_Title)
|
||||
.setDescription(
|
||||
msgconfig.ForceAddUser.Added_Description.replace("%username%", userToAdd.username),
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
await interaction.reply({
|
||||
embeds: [addedEmbed],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
|
||||
if (supportbot.Ticket?.UserManagement?.DMOnAdd !== false) {
|
||||
const addedToTicketEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.ForceAddUser.AddedToTicket_Title)
|
||||
.setDescription(
|
||||
msgconfig.ForceAddUser.AddedToTicket_Description.replace(
|
||||
"%channel_link%",
|
||||
`[${ticketChannel.name}](https://discord.com/channels/${ticketChannel.guild.id}/${ticketChannel.id})`,
|
||||
),
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
await userToAdd.send({ embeds: [addedToTicketEmbed] }).catch(() => { });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error adding user to the ticket:", err);
|
||||
|
||||
const errorEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.ForceAddUser.Error_Title)
|
||||
.setDescription(msgconfig.ForceAddUser.Error_Adding)
|
||||
.setColor(supportbot.Embed.Colours.Error);
|
||||
|
||||
await interaction.reply({
|
||||
embeds: [errorEmbed],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === (cmdconfig.TicketManage?.ForceRemove?.Command || "forceremove")) {
|
||||
const userToRemove = interaction.options.getUser("user");
|
||||
const ticketChannel = interaction.channel;
|
||||
|
||||
if (
|
||||
(supportbot.Ticket.TicketType === "threads" && !ticketChannel.isThread()) ||
|
||||
(supportbot.Ticket.TicketType === "channels" &&
|
||||
ticketChannel.type !== ChannelType.GuildText)
|
||||
) {
|
||||
const onlyInTicket = new EmbedBuilder()
|
||||
.setTitle(msgconfig.RemoveUser.NotInTicket_Title)
|
||||
.setDescription(msgconfig.RemoveUser.NotInTicket_Description)
|
||||
.setColor(supportbot.Embed.Colours.Error);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [onlyInTicket],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
if (supportbot.Ticket.TicketType === "threads") {
|
||||
await ticketChannel.members.remove(userToRemove.id);
|
||||
} else {
|
||||
await ticketChannel.permissionOverwrites.delete(userToRemove.id);
|
||||
}
|
||||
|
||||
db.removeUserFromTicket(ticketChannel.id, userToRemove.id);
|
||||
|
||||
const removedEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.RemoveUser.Removed_Title)
|
||||
.setDescription(msgconfig.RemoveUser.Removed_Message)
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
await interaction.reply({
|
||||
embeds: [removedEmbed],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
|
||||
if (supportbot.Ticket?.UserManagement?.DMOnRemove !== false) {
|
||||
const removedFromTicketEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.RemoveUser.RemovedFromTicket_Title)
|
||||
.setDescription(
|
||||
msgconfig.RemoveUser.RemovedFromTicket_Description.replace(
|
||||
"%channel_link%",
|
||||
`[${ticketChannel.name}](https://discord.com/channels/${ticketChannel.guild.id}/${ticketChannel.id})`,
|
||||
),
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
await userToRemove.send({ embeds: [removedFromTicketEmbed] }).catch(() => { });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error removing user from the ticket:", err);
|
||||
|
||||
const errorEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.RemoveUser.Error_Title)
|
||||
.setDescription(msgconfig.RemoveUser.Error_Removing)
|
||||
.setColor(supportbot.Embed.Colours.Error);
|
||||
|
||||
await interaction.reply({
|
||||
embeds: [errorEmbed],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === (cmdconfig.TicketManage?.Rename?.Command || "rename")) {
|
||||
const modal = new ModalBuilder()
|
||||
.setCustomId("renameTicketModal")
|
||||
.setTitle("Rename Channel")
|
||||
.addComponents(
|
||||
new ActionRowBuilder().addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId("renameTicket")
|
||||
.setLabel("New Channel Name")
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setRequired(true),
|
||||
),
|
||||
);
|
||||
|
||||
return interaction.showModal(modal);
|
||||
}
|
||||
|
||||
if (subcommand === (cmdconfig.TicketManage?.Close?.Command || "close")) {
|
||||
const reason = interaction.options.getString("reason") || "Closed by staff.";
|
||||
|
||||
if (supportbot.Ticket.Close.StaffOnly) {
|
||||
let CloseSupportStaff = await getRole(
|
||||
supportbot.Roles.StaffMember.Staff,
|
||||
interaction.guild,
|
||||
);
|
||||
let CloseAdmin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
|
||||
if (!CloseSupportStaff || !CloseAdmin) {
|
||||
return interaction.reply({
|
||||
content:
|
||||
"Some roles seem to be missing! Please check for errors when starting the bot.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const noClosePerms = new EmbedBuilder()
|
||||
.setTitle("Invalid Permissions!")
|
||||
.setDescription(
|
||||
`${msgconfig.Error.IncorrectPerms}\n\nRole Required: \`${supportbot.Roles.StaffMember.Staff}\` or \`${supportbot.Roles.StaffMember.Admin}\``,
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
|
||||
if (
|
||||
!interaction.member.roles.cache.has(CloseSupportStaff.id) &&
|
||||
!interaction.member.roles.cache.has(CloseAdmin.id)
|
||||
) {
|
||||
return interaction.reply({
|
||||
embeds: [noClosePerms],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const isThread = interaction.channel.type === ChannelType.PrivateThread;
|
||||
|
||||
if (
|
||||
(supportbot.Ticket.TicketType === "threads" && !isThread) ||
|
||||
(supportbot.Ticket.TicketType === "channels" &&
|
||||
interaction.channel.type !== ChannelType.GuildText)
|
||||
) {
|
||||
const notTicketChannel = new EmbedBuilder()
|
||||
.setTitle("Invalid Channel!")
|
||||
.setDescription(
|
||||
`This command can only be used in a ${supportbot.Ticket.TicketType === "threads" ? "ticket thread" : "ticket channel"}.`,
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [notTicketChannel],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
|
||||
const ticketData = db.getTicket(interaction.channel.id);
|
||||
|
||||
if (!ticketData) {
|
||||
const exists = new EmbedBuilder()
|
||||
.setTitle("No Ticket Found!")
|
||||
.setDescription(msgconfig.Error.NoValidTicket)
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
|
||||
return interaction.followUp({
|
||||
embeds: [exists],
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await TicketManager.createTranscript(interaction, ticketData, reason);
|
||||
|
||||
await interaction.followUp({
|
||||
content: "Ticket closed successfully.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
|
||||
await interaction.channel.delete().catch(() => { });
|
||||
} catch (err) {
|
||||
console.error("Error closing ticket:", err);
|
||||
|
||||
await interaction.followUp({
|
||||
content: "An error occurred while closing the ticket.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return interaction.reply({
|
||||
content: "Unknown ticket management action.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error in ticket manage command:", error);
|
||||
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
return interaction.reply({
|
||||
content: "An error occurred while managing the ticket.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,342 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Ticket Panel Command
|
||||
|
||||
const fs = require("fs");
|
||||
const {
|
||||
ApplicationCommandType,
|
||||
ActionRowBuilder,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
MessageFlags,
|
||||
ContainerBuilder,
|
||||
TextDisplayBuilder,
|
||||
MediaGalleryBuilder,
|
||||
SeparatorBuilder,
|
||||
SectionBuilder,
|
||||
StringSelectMenuBuilder,
|
||||
ThumbnailBuilder,
|
||||
EmbedBuilder,
|
||||
} = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const panelconfig = yaml.load(fs.readFileSync("./Configs/ticket-panel.yml", "utf8"));
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
const db = require("../../Structures/Database.js");
|
||||
|
||||
function parseButtonStyle(style) {
|
||||
switch (String(style || "1")) {
|
||||
case "1":
|
||||
return ButtonStyle.Primary;
|
||||
case "2":
|
||||
return ButtonStyle.Secondary;
|
||||
case "3":
|
||||
return ButtonStyle.Danger;
|
||||
case "4":
|
||||
return ButtonStyle.Success;
|
||||
default:
|
||||
return ButtonStyle.Primary;
|
||||
}
|
||||
}
|
||||
|
||||
function getPanelMessage(key, fallback) {
|
||||
return panelconfig.Messages?.[key] || fallback;
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.TicketPanel.Command,
|
||||
description: cmdconfig.TicketPanel.Description,
|
||||
type: ApplicationCommandType.ChatInput,
|
||||
options: [],
|
||||
permissions: cmdconfig.TicketPanel.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
if (!panelconfig.Panel) {
|
||||
console.log(
|
||||
"\u001b[31m",
|
||||
`[TICKET PANEL]`,
|
||||
"\u001b[33m",
|
||||
"Ticket Panel is not setup, You can set this in",
|
||||
`\u001b[31m`,
|
||||
"/Configs/ticket-panel.yml",
|
||||
`\n `,
|
||||
);
|
||||
|
||||
return interaction.reply({
|
||||
content: getPanelMessage(
|
||||
"NotConfigured",
|
||||
"Ticket Panel is not set up. Please configure it in `/Configs/ticket-panel.yml`.",
|
||||
),
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const { getChannel } = interaction.client;
|
||||
|
||||
const channel = await getChannel(supportbot.Ticket.TicketHome, interaction.guild);
|
||||
|
||||
if (!channel) {
|
||||
console.log(`[TICKET PANEL] TicketHome channel not found. Please check your config file.`);
|
||||
return interaction.reply({
|
||||
content: getPanelMessage(
|
||||
"InvalidChannel",
|
||||
"TicketHome channel not found. Please check your config file.",
|
||||
),
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
|
||||
const panelRow = db.getTicketPanel();
|
||||
|
||||
if (panelRow) {
|
||||
try {
|
||||
const oldMessage = await channel.messages.fetch(panelRow.message_id);
|
||||
if (oldMessage) {
|
||||
await oldMessage.delete().catch(() => { });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`[TICKET PANEL] Previous panel message not found, creating a new one.`);
|
||||
}
|
||||
}
|
||||
|
||||
const departmentSystem = supportbot.Ticket?.DepartmentSystem || {};
|
||||
const prioritySystem = supportbot.Ticket?.PrioritySystem || {};
|
||||
const usingThreads = supportbot.Ticket?.TicketType === "threads";
|
||||
|
||||
const departmentsEnabled = departmentSystem.Enabled === true && !usingThreads;
|
||||
const prioritiesEnabled = prioritySystem.Enabled === true && !usingThreads;
|
||||
const departments = departmentSystem.Departments || {};
|
||||
|
||||
if (usingThreads && (departmentSystem.Enabled || prioritySystem.Enabled)) {
|
||||
console.log(
|
||||
"[SupportBot] Departments and Priority are disabled because TicketType is set to 'threads'.",
|
||||
);
|
||||
}
|
||||
|
||||
const departmentOptions = Object.entries(departments)
|
||||
.slice(0, 25)
|
||||
.map(([key, dept]) => ({
|
||||
label: dept.Name || key,
|
||||
description:
|
||||
dept.PanelDescription ||
|
||||
dept.Description ||
|
||||
panelconfig.DepartmentMenu?.DefaultDescription ||
|
||||
`Open a ${String(dept.Name || key).toLowerCase()} ticket`,
|
||||
value: key,
|
||||
emoji:
|
||||
dept.Emoji ||
|
||||
panelconfig.DepartmentMenu?.DefaultEmoji ||
|
||||
panelconfig.Button?.Emoji ||
|
||||
undefined,
|
||||
}));
|
||||
|
||||
const shouldUseDepartments = departmentsEnabled && departmentOptions.length > 0;
|
||||
|
||||
let openerComponent;
|
||||
|
||||
if (shouldUseDepartments) {
|
||||
openerComponent = new StringSelectMenuBuilder()
|
||||
.setCustomId(panelconfig.DepartmentMenu?.CustomId || "ticketdepartmentselect")
|
||||
.setPlaceholder(
|
||||
panelconfig.DepartmentMenu?.Placeholder ||
|
||||
departmentSystem.Placeholder ||
|
||||
panelconfig.Button?.Text ||
|
||||
"Choose a ticket department",
|
||||
)
|
||||
.addOptions(departmentOptions);
|
||||
} else {
|
||||
openerComponent = new ButtonBuilder()
|
||||
.setCustomId(panelconfig.Button?.CustomId || "createticket")
|
||||
.setLabel(panelconfig.Button?.Text || "Create Ticket")
|
||||
.setStyle(parseButtonStyle(panelconfig.Button?.Color));
|
||||
|
||||
if (panelconfig.Button?.Emoji) {
|
||||
openerComponent.setEmoji(panelconfig.Button.Emoji);
|
||||
}
|
||||
}
|
||||
|
||||
const panelContainer = new ContainerBuilder();
|
||||
|
||||
if (panelconfig.Style?.Color) {
|
||||
panelContainer.setAccentColor(parseInt(String(panelconfig.Style.Color).replace("#", ""), 16));
|
||||
}
|
||||
|
||||
const layout = String(panelconfig.Style?.Layout || "3");
|
||||
const showImage = panelconfig.Settings?.Image === true && !!panelconfig.Style?.Image;
|
||||
const showTopTitle = panelconfig.Settings?.TopTitle === true;
|
||||
const showTopDivider = panelconfig.Settings?.TopDivider === true;
|
||||
const showBottomTitle = panelconfig.Settings?.BottomTitle === true;
|
||||
const showBottomDivider = panelconfig.Settings?.BottomDivider === true;
|
||||
|
||||
const panelTitle = new TextDisplayBuilder().setContent(
|
||||
panelconfig.Style?.Title || "## SupportBot Ticket Creation",
|
||||
);
|
||||
|
||||
const rawTitle = (panelconfig.Style?.Title || "SupportBot Ticket Creation").replace(/^#+\s*/, "");
|
||||
|
||||
const panelDesc = new TextDisplayBuilder().setContent(
|
||||
panelconfig.Style?.Description || "Click on the button below to create a support ticket.",
|
||||
);
|
||||
|
||||
if (showTopTitle) {
|
||||
panelContainer.addTextDisplayComponents(panelTitle);
|
||||
}
|
||||
|
||||
if (showTopDivider) {
|
||||
panelContainer.addSeparatorComponents(new SeparatorBuilder().setDivider(true));
|
||||
}
|
||||
|
||||
if (layout === "1" || layout === "3") {
|
||||
panelContainer.addTextDisplayComponents(panelDesc);
|
||||
}
|
||||
|
||||
if (showImage && layout === "2") {
|
||||
const panelImage = new MediaGalleryBuilder().addItems([
|
||||
{
|
||||
media: {
|
||||
url: panelconfig.Style.Image,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
panelContainer.addMediaGalleryComponents(panelImage);
|
||||
}
|
||||
|
||||
if (layout === "1") {
|
||||
const middleSection = new SectionBuilder().addTextDisplayComponents(panelDesc);
|
||||
|
||||
if (!shouldUseDepartments) {
|
||||
middleSection.setButtonAccessory(openerComponent);
|
||||
panelContainer.addSectionComponents(middleSection);
|
||||
} else {
|
||||
panelContainer.addSectionComponents(middleSection);
|
||||
panelContainer.addActionRowComponents(
|
||||
new ActionRowBuilder().addComponents(openerComponent),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (showImage && layout === "3") {
|
||||
const panelImage = new MediaGalleryBuilder().addItems([
|
||||
{
|
||||
media: {
|
||||
url: panelconfig.Style.Image,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
panelContainer.addMediaGalleryComponents(panelImage);
|
||||
}
|
||||
|
||||
if (showBottomTitle) {
|
||||
panelContainer.addTextDisplayComponents(panelTitle);
|
||||
}
|
||||
|
||||
if (showBottomDivider) {
|
||||
panelContainer.addSeparatorComponents(new SeparatorBuilder().setDivider(true));
|
||||
}
|
||||
|
||||
if (layout === "2") {
|
||||
const middleSection = new SectionBuilder().addTextDisplayComponents(panelDesc);
|
||||
|
||||
if (!shouldUseDepartments) {
|
||||
middleSection.setButtonAccessory(openerComponent);
|
||||
panelContainer.addSectionComponents(middleSection);
|
||||
} else {
|
||||
panelContainer.addSectionComponents(middleSection);
|
||||
panelContainer.addActionRowComponents(
|
||||
new ActionRowBuilder().addComponents(openerComponent),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (layout === "3") {
|
||||
panelContainer.addActionRowComponents(new ActionRowBuilder().addComponents(openerComponent));
|
||||
}
|
||||
|
||||
if (layout === "4") {
|
||||
// Create a classic Discord Embed for Layout 4
|
||||
const oldEmbed = new EmbedBuilder()
|
||||
.setTitle(rawTitle)
|
||||
.setDescription(panelconfig.Style?.Description || "Click on the button below to create a support ticket.");
|
||||
|
||||
if (panelconfig.Style?.Color) {
|
||||
oldEmbed.setColor(panelconfig.Style.Color);
|
||||
}
|
||||
|
||||
if (showImage && panelconfig.Style?.Image) {
|
||||
oldEmbed.setThumbnail(panelconfig.Style.Image);
|
||||
}
|
||||
|
||||
try {
|
||||
const message = await channel.send({
|
||||
embeds: [oldEmbed],
|
||||
components: [new ActionRowBuilder().addComponents(openerComponent)],
|
||||
});
|
||||
|
||||
db.saveTicketPanel(message.id, channel.id);
|
||||
|
||||
return interaction.reply({
|
||||
content: shouldUseDepartments
|
||||
? getPanelMessage(
|
||||
"PanelSentWithDepartments",
|
||||
"Ticket panel message with department selection has been sent!",
|
||||
)
|
||||
: getPanelMessage("PanelSent", "Ticket panel message has been sent!"),
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log("Error sending message:", e);
|
||||
return interaction.reply({
|
||||
content: getPanelMessage(
|
||||
"SendError",
|
||||
"An error occurred while sending the ticket panel message.",
|
||||
),
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (showImage && layout === "1") {
|
||||
const panelImage = new MediaGalleryBuilder().addItems([
|
||||
{
|
||||
media: {
|
||||
url: panelconfig.Style.Image,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
panelContainer.addMediaGalleryComponents(panelImage);
|
||||
}
|
||||
|
||||
try {
|
||||
const message = await channel.send({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [panelContainer],
|
||||
});
|
||||
|
||||
db.saveTicketPanel(message.id, channel.id);
|
||||
|
||||
return interaction.reply({
|
||||
content: shouldUseDepartments
|
||||
? getPanelMessage(
|
||||
"PanelSentWithDepartments",
|
||||
"Ticket panel message with department selection has been sent!",
|
||||
)
|
||||
: getPanelMessage("PanelSent", "Ticket panel message has been sent!"),
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log("Error sending message:", e);
|
||||
return interaction.reply({
|
||||
content: getPanelMessage(
|
||||
"SendError",
|
||||
"An error occurred while sending the ticket panel message.",
|
||||
),
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,468 @@
|
||||
const {
|
||||
ApplicationCommandType,
|
||||
ApplicationCommandOptionType,
|
||||
ActionRowBuilder,
|
||||
ButtonBuilder,
|
||||
EmbedBuilder,
|
||||
StringSelectMenuBuilder,
|
||||
ModalBuilder,
|
||||
TextInputBuilder,
|
||||
TextInputStyle,
|
||||
ButtonStyle,
|
||||
ComponentType,
|
||||
MessageFlags,
|
||||
} = require('discord.js');
|
||||
const Command = require('../../Structures/Command.js');
|
||||
const fs = require('fs');
|
||||
const yaml = require('js-yaml');
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync('./Configs/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Configs/commands.yml', 'utf8'));
|
||||
const msgconfig = yaml.load(fs.readFileSync('./Configs/messages.yml', 'utf8'));
|
||||
|
||||
function parseColor(color) {
|
||||
if (!color) return 0x5865F2;
|
||||
if (typeof color === 'number') return color;
|
||||
if (typeof color !== 'string') return 0x5865F2;
|
||||
color = color.replace('#', '');
|
||||
if (/^[0-9A-F]{6}$/i.test(color)) {
|
||||
return parseInt(color, 16);
|
||||
}
|
||||
return 0x5865F2;
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Embed.Command,
|
||||
description: cmdconfig.Embed.Description,
|
||||
type: ApplicationCommandType.ChatInput,
|
||||
options: [
|
||||
{
|
||||
name: 'channel',
|
||||
description: 'Select channel to send the message',
|
||||
type: ApplicationCommandOptionType.Channel,
|
||||
required: true
|
||||
}
|
||||
],
|
||||
permissions: cmdconfig.Embed.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
const { getRole } = interaction.client;
|
||||
let SupportStaff = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
let Admin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
|
||||
if (!SupportStaff || !Admin) {
|
||||
return interaction.reply('Some roles seem to be missing!\nPlease check for errors when starting the bot.');
|
||||
}
|
||||
|
||||
if (!interaction.member.roles.cache.has(SupportStaff.id) &&
|
||||
!interaction.member.roles.cache.has(Admin.id)) {
|
||||
const NoPerms = new EmbedBuilder()
|
||||
.setTitle('Invalid Permissions!')
|
||||
.setDescription(`${msgconfig.Error.IncorrectPerms}\n\nRole Required: \`${supportbot.Roles.StaffMember.Staff}\` or \`${supportbot.Roles.StaffMember.Admin}\``)
|
||||
.setColor(0xFF0000);
|
||||
return interaction.reply({ embeds: [NoPerms], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
|
||||
const channel = interaction.options.getChannel('channel');
|
||||
|
||||
const messageData = {
|
||||
type: 'embed',
|
||||
title: 'New Embed',
|
||||
description: 'Click the buttons below to edit this embed',
|
||||
color: 0x5865F2,
|
||||
fields: [],
|
||||
footer: null,
|
||||
thumbnail: null,
|
||||
image: null,
|
||||
timestamp: false
|
||||
};
|
||||
|
||||
function createEmbed() {
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle(messageData.title)
|
||||
.setDescription(messageData.description)
|
||||
.setColor(messageData.color);
|
||||
|
||||
if (messageData.fields.length > 0) {
|
||||
embed.addFields(messageData.fields);
|
||||
}
|
||||
if (messageData.footer) {
|
||||
embed.setFooter({ text: messageData.footer });
|
||||
}
|
||||
if (messageData.thumbnail) {
|
||||
embed.setThumbnail(messageData.thumbnail);
|
||||
}
|
||||
if (messageData.image) {
|
||||
embed.setImage(messageData.image);
|
||||
}
|
||||
if (messageData.timestamp) {
|
||||
embed.setTimestamp();
|
||||
}
|
||||
|
||||
return embed;
|
||||
}
|
||||
|
||||
const typeRow = new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new StringSelectMenuBuilder()
|
||||
.setCustomId('message_type')
|
||||
.setPlaceholder('Select message type')
|
||||
.addOptions([
|
||||
{
|
||||
label: 'Embed Message',
|
||||
description: 'Send as an embedded message',
|
||||
value: 'embed'
|
||||
},
|
||||
{
|
||||
label: 'Text Message',
|
||||
description: 'Send as a plain text message',
|
||||
value: 'text'
|
||||
}
|
||||
])
|
||||
);
|
||||
|
||||
function createButtons(messageType) {
|
||||
const buttons = [];
|
||||
|
||||
if (messageType === 'embed') {
|
||||
const row1 = new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId('edit_title')
|
||||
.setLabel('Edit Title')
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId('edit_description')
|
||||
.setLabel('Edit Description')
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId('edit_color')
|
||||
.setLabel('Edit Color')
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId('add_field')
|
||||
.setLabel('Add Field')
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
);
|
||||
|
||||
const row2 = new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId('edit_footer')
|
||||
.setLabel('Edit Footer')
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId('edit_image')
|
||||
.setLabel('Add Image')
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId('edit_thumbnail')
|
||||
.setLabel('Add Thumbnail')
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId('toggle_timestamp')
|
||||
.setLabel('Toggle Timestamp')
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
);
|
||||
|
||||
buttons.push(row1, row2);
|
||||
} else {
|
||||
const textRow = new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId('edit_description')
|
||||
.setLabel('Edit Text')
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
);
|
||||
|
||||
buttons.push(textRow);
|
||||
}
|
||||
|
||||
// Send button always shows
|
||||
const sendRow = new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId('send_message')
|
||||
.setLabel('Send')
|
||||
.setStyle(ButtonStyle.Success)
|
||||
);
|
||||
|
||||
buttons.push(sendRow);
|
||||
return buttons;
|
||||
}
|
||||
|
||||
async function updatePreview(i) {
|
||||
if (messageData.type === 'embed') {
|
||||
await i.update({
|
||||
content: 'Customize your message:',
|
||||
embeds: [createEmbed()],
|
||||
components: [typeRow, ...createButtons('embed')]
|
||||
});
|
||||
} else {
|
||||
await i.update({
|
||||
content: messageData.description,
|
||||
embeds: [],
|
||||
components: [typeRow, ...createButtons('text')]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const message = await interaction.reply({
|
||||
content: messageData.type === 'text' ? messageData.description : 'Customize your message:',
|
||||
components: [typeRow, ...createButtons(messageData.type)],
|
||||
embeds: messageData.type === 'embed' ? [createEmbed()] : [],
|
||||
flags: MessageFlags.Ephemeral
|
||||
});
|
||||
|
||||
const collector = message.createMessageComponentCollector({
|
||||
time: 900000
|
||||
});
|
||||
|
||||
collector.on('collect', async (i) => {
|
||||
if (i.user.id !== interaction.user.id) {
|
||||
return i.reply({
|
||||
content: 'You cannot edit this message.',
|
||||
flags: MessageFlags.Ephemeral
|
||||
});
|
||||
}
|
||||
|
||||
switch (i.customId) {
|
||||
case 'message_type':
|
||||
messageData.type = i.values[0];
|
||||
await updatePreview(i);
|
||||
break;
|
||||
|
||||
case 'edit_description':
|
||||
const descModal = new ModalBuilder()
|
||||
.setCustomId('desc_modal')
|
||||
.setTitle(messageData.type === 'embed' ? 'Edit Description' : 'Edit Text');
|
||||
|
||||
descModal.addComponents(
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('desc_input')
|
||||
.setLabel(messageData.type === 'embed' ? 'Description' : 'Message Text')
|
||||
.setStyle(TextInputStyle.Paragraph)
|
||||
.setValue(messageData.description)
|
||||
.setMaxLength(4000)
|
||||
)
|
||||
);
|
||||
|
||||
await i.showModal(descModal);
|
||||
break;
|
||||
|
||||
case 'edit_title':
|
||||
const titleModal = new ModalBuilder()
|
||||
.setCustomId('title_modal')
|
||||
.setTitle('Edit Title');
|
||||
|
||||
titleModal.addComponents(
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('title_input')
|
||||
.setLabel('Title')
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setValue(messageData.title)
|
||||
.setMaxLength(256)
|
||||
)
|
||||
);
|
||||
|
||||
await i.showModal(titleModal);
|
||||
break;
|
||||
|
||||
case 'edit_color':
|
||||
const colorModal = new ModalBuilder()
|
||||
.setCustomId('color_modal')
|
||||
.setTitle('Edit Color');
|
||||
|
||||
colorModal.addComponents(
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('color_input')
|
||||
.setLabel('Color (HEX)')
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setPlaceholder('#FF0000')
|
||||
.setMinLength(6)
|
||||
.setMaxLength(7)
|
||||
.setValue(messageData.color.toString(16).padStart(6, '0'))
|
||||
)
|
||||
);
|
||||
|
||||
await i.showModal(colorModal);
|
||||
break;
|
||||
|
||||
case 'add_field':
|
||||
const fieldModal = new ModalBuilder()
|
||||
.setCustomId('field_modal')
|
||||
.setTitle('Add Field');
|
||||
|
||||
fieldModal.addComponents(
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('field_name')
|
||||
.setLabel('Field Name')
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setMaxLength(256)
|
||||
),
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('field_value')
|
||||
.setLabel('Field Value')
|
||||
.setStyle(TextInputStyle.Paragraph)
|
||||
.setMaxLength(1024)
|
||||
),
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('field_inline')
|
||||
.setLabel('Inline? (true/false)')
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setValue('false')
|
||||
.setPlaceholder('true or false')
|
||||
)
|
||||
);
|
||||
|
||||
await i.showModal(fieldModal);
|
||||
break;
|
||||
|
||||
case 'edit_footer':
|
||||
const footerModal = new ModalBuilder()
|
||||
.setCustomId('footer_modal')
|
||||
.setTitle('Edit Footer');
|
||||
|
||||
footerModal.addComponents(
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('footer_input')
|
||||
.setLabel('Footer Text')
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setValue(messageData.footer || '')
|
||||
.setMaxLength(2048)
|
||||
)
|
||||
);
|
||||
|
||||
await i.showModal(footerModal);
|
||||
break;
|
||||
|
||||
case 'edit_image':
|
||||
const imageModal = new ModalBuilder()
|
||||
.setCustomId('image_modal')
|
||||
.setTitle('Add Image');
|
||||
|
||||
imageModal.addComponents(
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('image_input')
|
||||
.setLabel('Image URL')
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setValue(messageData.image || '')
|
||||
.setPlaceholder('https://example.com/image.png')
|
||||
)
|
||||
);
|
||||
|
||||
await i.showModal(imageModal);
|
||||
break;
|
||||
|
||||
case 'edit_thumbnail':
|
||||
const thumbnailModal = new ModalBuilder()
|
||||
.setCustomId('thumbnail_modal')
|
||||
.setTitle('Add Thumbnail');
|
||||
|
||||
thumbnailModal.addComponents(
|
||||
new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId('thumbnail_input')
|
||||
.setLabel('Thumbnail URL')
|
||||
.setStyle(TextInputStyle.Short)
|
||||
.setValue(messageData.thumbnail || '')
|
||||
.setPlaceholder('https://example.com/thumbnail.png')
|
||||
)
|
||||
);
|
||||
|
||||
await i.showModal(thumbnailModal);
|
||||
break;
|
||||
|
||||
case 'toggle_timestamp':
|
||||
messageData.timestamp = !messageData.timestamp;
|
||||
await updatePreview(i);
|
||||
break;
|
||||
|
||||
case 'send_message':
|
||||
try {
|
||||
if (messageData.type === 'embed') {
|
||||
await channel.send({ embeds: [createEmbed()] });
|
||||
} else {
|
||||
await channel.send(messageData.description);
|
||||
}
|
||||
await i.update({
|
||||
content: 'Message sent successfully!',
|
||||
components: [],
|
||||
embeds: []
|
||||
});
|
||||
collector.stop();
|
||||
} catch (error) {
|
||||
await i.reply({
|
||||
content: 'Failed to send message. Please check channel permissions.',
|
||||
flags: MessageFlags.Ephemeral
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// Handle modal submissions
|
||||
interaction.client.on('interactionCreate', async (modal) => {
|
||||
if (!modal.isModalSubmit()) return;
|
||||
if (modal.user.id !== interaction.user.id) return;
|
||||
|
||||
switch (modal.customId) {
|
||||
case 'title_modal':
|
||||
messageData.title = modal.fields.getTextInputValue('title_input');
|
||||
break;
|
||||
case 'desc_modal':
|
||||
messageData.description = modal.fields.getTextInputValue('desc_input');
|
||||
break;
|
||||
case 'color_modal':
|
||||
messageData.color = parseColor(modal.fields.getTextInputValue('color_input'));
|
||||
break;
|
||||
case 'field_modal':
|
||||
const inlineValue = modal.fields.getTextInputValue('field_inline').toLowerCase();
|
||||
messageData.fields.push({
|
||||
name: modal.fields.getTextInputValue('field_name'),
|
||||
value: modal.fields.getTextInputValue('field_value'),
|
||||
inline: inlineValue === 'true'
|
||||
});
|
||||
break;
|
||||
case 'footer_modal':
|
||||
messageData.footer = modal.fields.getTextInputValue('footer_input');
|
||||
break;
|
||||
case 'image_modal':
|
||||
messageData.image = modal.fields.getTextInputValue('image_input');
|
||||
break;
|
||||
case 'thumbnail_modal':
|
||||
messageData.thumbnail = modal.fields.getTextInputValue('thumbnail_input');
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
await updatePreview(modal);
|
||||
});
|
||||
|
||||
collector.on('end', () => {
|
||||
interaction.editReply({
|
||||
content: 'Message editor timed out.',
|
||||
components: [],
|
||||
embeds: []
|
||||
}).catch(() => {});
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
const fs = require("fs");
|
||||
const { ApplicationCommandOptionType, ApplicationCommandType, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, MessageFlags } = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
const Command = require("../../Structures/Command.js");
|
||||
|
||||
// Function to chunk array into smaller arrays
|
||||
function chunkArray(arr, size) {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < arr.length; i += size) {
|
||||
chunks.push(arr.slice(i, i + size));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Mod.Command,
|
||||
description: cmdconfig.Mod.Command,
|
||||
type: ApplicationCommandType.ChatInput,
|
||||
options: [
|
||||
{
|
||||
name: cmdconfig.Mod.TicketBlacklist.Command,
|
||||
description: cmdconfig.Mod.TicketBlacklist.Description,
|
||||
type: ApplicationCommandOptionType.SubcommandGroup,
|
||||
options: [
|
||||
{
|
||||
name: cmdconfig.Mod.TicketBlacklist.Add.Command,
|
||||
description: msgconfig.Mod.TicketBlacklist.Add.Description || "Add a user to the ticket blacklist",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: 'user',
|
||||
description: msgconfig.Mod.TicketBlacklist.Add.UserDescription || "User to blacklist",
|
||||
type: ApplicationCommandOptionType.User,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
name: 'reason',
|
||||
description: msgconfig.Mod.TicketBlacklist.Add.ReasonDescription || "Reason for blacklisting",
|
||||
type: ApplicationCommandOptionType.String,
|
||||
required: false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
name: cmdconfig.Mod.TicketBlacklist.Remove.Command,
|
||||
description: msgconfig.Mod.TicketBlacklist.Remove.Description || "Remove a user from the ticket blacklist",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
options: [
|
||||
{
|
||||
name: 'user',
|
||||
description: msgconfig.Mod.TicketBlacklist.Remove.UserDescription || "User to remove from blacklist",
|
||||
type: ApplicationCommandOptionType.User,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
name: 'reason',
|
||||
description: msgconfig.Mod.TicketBlacklist.Remove.ReasonDescription || "Reason for removing from blacklist",
|
||||
type: ApplicationCommandOptionType.String,
|
||||
required: false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "view",
|
||||
description: msgconfig.Mod.TicketBlacklist.View.Description || "View all blacklisted users",
|
||||
type: ApplicationCommandOptionType.Subcommand,
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
permissions: cmdconfig.Mod.Permission,
|
||||
|
||||
async run(interaction) {
|
||||
const { getRole } = interaction.client;
|
||||
|
||||
let SupportStaff = await getRole(supportbot.Roles.StaffMember.Staff, interaction.guild);
|
||||
let Admin = await getRole(supportbot.Roles.StaffMember.Admin, interaction.guild);
|
||||
let Moderator = await getRole(supportbot.Roles.StaffMember.Moderator, interaction.guild);
|
||||
|
||||
if (!SupportStaff || !Admin || !Moderator) {
|
||||
const missingRolesEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Error.InvalidChannel || "Required roles are missing!")
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
return interaction.reply({ embeds: [missingRolesEmbed] });
|
||||
}
|
||||
|
||||
const NoPerms = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Error.IncorrectPerms || "You do not have the correct permissions!")
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
|
||||
if (!interaction.member.roles.cache.has(Admin.id) && !interaction.member.roles.cache.has(Moderator.id) && (!supportbot.Mod.AllowSupportStaff || !interaction.member.roles.cache.has(SupportStaff.id))) {
|
||||
return interaction.reply({ embeds: [NoPerms] });
|
||||
}
|
||||
|
||||
const subcommand = interaction.options.getSubcommand(false);
|
||||
const user = interaction.options.getUser('user');
|
||||
const reason = interaction.options.getString('reason') || "No reason provided";
|
||||
|
||||
try {
|
||||
let blacklistedUsers;
|
||||
try {
|
||||
blacklistedUsers = JSON.parse(fs.readFileSync("./Data/BlacklistedUsers.json", "utf8")).blacklistedUsers;
|
||||
if (!Array.isArray(blacklistedUsers)) {
|
||||
blacklistedUsers = [];
|
||||
}
|
||||
} catch (error) {
|
||||
blacklistedUsers = [];
|
||||
}
|
||||
|
||||
if (subcommand === cmdconfig.Mod.TicketBlacklist.Add.Command) {
|
||||
if (blacklistedUsers.includes(user.id)) {
|
||||
const alreadyBlacklistedEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Mod.TicketBlacklist.Add.AlreadyBlacklisted.replace("{userTag}", user.tag) || ":x: User is already blacklisted.")
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
return interaction.reply({ embeds: [alreadyBlacklistedEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
|
||||
blacklistedUsers.push(user.id);
|
||||
fs.writeFileSync("./Data/BlacklistedUsers.json", JSON.stringify({ "blacklistedUsers": blacklistedUsers }, null, 4));
|
||||
|
||||
const successEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Mod.TicketBlacklist.Add.Success.replace("{userTag}", user.tag) || ":white_check_mark: User has been blacklisted.")
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
const blacklistChannel = interaction.guild.channels.cache.get(supportbot.Ticket.Log.TicketBlacklistLog);
|
||||
if (blacklistChannel) {
|
||||
const blacklistLogEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.TicketBlacklistLog.Title || "Ticket Blacklist Log")
|
||||
.setColor(msgconfig.TicketBlacklistLog.Colour || supportbot.Embed.Colours.Success)
|
||||
.setFooter({ text: supportbot.Embed.Footer, iconURL: interaction.user.displayAvatarURL() })
|
||||
.setDescription(`> **User:** ${user.tag} (\`${user.id}\`)\n> **Actioned by:** <@${interaction.user.id}>`)
|
||||
.addFields({ name: "Action", value: "\`\`\`Removed from blacklist\`\`\`", inline: false })
|
||||
.addFields({ name: "Reason", value: `\`\`\`${reason}\`\`\``, inline: false });
|
||||
|
||||
blacklistChannel.send({ embeds: [blacklistLogEmbed] });
|
||||
}
|
||||
|
||||
return interaction.reply({
|
||||
embeds: [successEmbed],
|
||||
flags: MessageFlags.Ephemeral
|
||||
});
|
||||
|
||||
} else if (subcommand === cmdconfig.Mod.TicketBlacklist.Remove.Command) {
|
||||
if (!blacklistedUsers.includes(user.id)) {
|
||||
const notBlacklistedEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Mod.TicketBlacklist.Remove.NotBlacklisted.replace("{userTag}", user.tag) || ":x: User is not blacklisted.")
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
return interaction.reply({ embeds: [notBlacklistedEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
|
||||
blacklistedUsers = blacklistedUsers.filter(id => id !== user.id);
|
||||
fs.writeFileSync("./Data/BlacklistedUsers.json", JSON.stringify({ "blacklistedUsers": blacklistedUsers }, null, 4));
|
||||
|
||||
const removedEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Mod.TicketBlacklist.Remove.Success.replace("{userTag}", user.tag) || ":white_check_mark: User has been removed from the blacklist.")
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
|
||||
const blacklistChannel = interaction.guild.channels.cache.get(supportbot.Ticket.Log.TicketBlacklistLog);
|
||||
if (blacklistChannel) {
|
||||
const blacklistLogEmbed = new EmbedBuilder()
|
||||
.setTitle(msgconfig.TicketBlacklistLog.Title || "Ticket Blacklist Log")
|
||||
.setColor(msgconfig.TicketBlacklistLog.Colour || supportbot.Embed.Colours.Success)
|
||||
.setFooter({ text: supportbot.Embed.Footer, iconURL: interaction.user.displayAvatarURL() })
|
||||
.setDescription(`> **User:** ${user.tag} (\`${user.id}\`)\n> **Actioned by:** <@${interaction.user.id}>`)
|
||||
.addFields({ name: "Action", value: "\`\`\`Removed from blacklist\`\`\`", inline: false })
|
||||
.addFields({ name: "Reason", value: `\`\`\`${reason}\`\`\``, inline: false });
|
||||
|
||||
blacklistChannel.send({ embeds: [blacklistLogEmbed] });
|
||||
}
|
||||
|
||||
return interaction.reply({ embeds: [removedEmbed], flags: MessageFlags.Ephemeral });
|
||||
|
||||
} else if (subcommand === "view") {
|
||||
if (blacklistedUsers.length === 0) {
|
||||
const noBlacklistedUsersEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Mod.TicketBlacklist.View.NoBlacklistedUsers || "No users are blacklisted.")
|
||||
.setColor(supportbot.Embed.Colours.Success);
|
||||
return interaction.reply({ embeds: [noBlacklistedUsersEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
|
||||
const chunkedUsers = chunkArray(blacklistedUsers, 5);
|
||||
let currentPage = 0;
|
||||
|
||||
const createEmbed = (page) => {
|
||||
return new EmbedBuilder()
|
||||
.setTitle(msgconfig.Mod.TicketBlacklist.View.EmbedTitle || "Blacklisted Users")
|
||||
.setDescription(chunkedUsers[page].map(id => `<@${id}>`).join("\n"))
|
||||
.setColor(supportbot.Embed.Colours.Success)
|
||||
.setFooter({ text: `Page ${page + 1} of ${chunkedUsers.length}` });
|
||||
};
|
||||
|
||||
const buttons = new ActionRowBuilder()
|
||||
.addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId('previous')
|
||||
.setLabel('Previous')
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setDisabled(currentPage === 0),
|
||||
new ButtonBuilder()
|
||||
.setCustomId('next')
|
||||
.setLabel('Next')
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setDisabled(currentPage === chunkedUsers.length - 1)
|
||||
);
|
||||
|
||||
const response = await interaction.reply({
|
||||
embeds: [createEmbed(currentPage)],
|
||||
components: chunkedUsers.length > 1 ? [buttons] : [],
|
||||
flags: MessageFlags.Ephemeral
|
||||
});
|
||||
|
||||
if (chunkedUsers.length <= 1) return;
|
||||
|
||||
const collector = response.createMessageComponentCollector({
|
||||
componentType: ComponentType.Button,
|
||||
time: 60000
|
||||
});
|
||||
|
||||
collector.on('collect', async (i) => {
|
||||
if (i.user.id !== interaction.user.id) {
|
||||
return i.reply({
|
||||
content: 'You cannot use these buttons.',
|
||||
flags: MessageFlags.Ephemeral
|
||||
});
|
||||
}
|
||||
|
||||
if (i.customId === 'previous' && currentPage > 0) {
|
||||
currentPage--;
|
||||
} else if (i.customId === 'next' && currentPage < chunkedUsers.length - 1) {
|
||||
currentPage++;
|
||||
}
|
||||
|
||||
buttons.components[0].setDisabled(currentPage === 0);
|
||||
buttons.components[1].setDisabled(currentPage === chunkedUsers.length - 1);
|
||||
|
||||
await i.update({
|
||||
embeds: [createEmbed(currentPage)],
|
||||
components: [buttons]
|
||||
});
|
||||
});
|
||||
|
||||
collector.on('end', () => {
|
||||
buttons.components.forEach(button => button.setDisabled(true));
|
||||
interaction.editReply({
|
||||
components: [buttons]
|
||||
}).catch(() => {});
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error in mod command:", error);
|
||||
const errorEmbed = new EmbedBuilder()
|
||||
.setDescription(msgconfig.Error.ActionFailed || "An error occurred while processing your request.")
|
||||
.setColor(supportbot.Embed.Colours.Warn);
|
||||
interaction.reply({ embeds: [errorEmbed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,237 @@
|
||||
const { Command } = require('../../Structures/Addon.js');
|
||||
const Discord = require("discord.js");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const db = require("../../Structures/Database.js");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
|
||||
async function loadSettings() {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get("SELECT data FROM settings WHERE id = 1", (err, row) => {
|
||||
if (err) return reject(err);
|
||||
if (!row) return resolve({});
|
||||
try {
|
||||
resolve(JSON.parse(row.data));
|
||||
} catch (e) {
|
||||
resolve({});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function saveSettings(settings) {
|
||||
const data = JSON.stringify(settings);
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(
|
||||
"INSERT INTO settings (id, data) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data",
|
||||
[data],
|
||||
(err) => (err ? reject(err) : resolve())
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.Settings.Command,
|
||||
description: cmdconfig.Settings.Description,
|
||||
permissions: cmdconfig.Settings.Permission,
|
||||
options: [
|
||||
{
|
||||
name: 'setstatus',
|
||||
type: Discord.ApplicationCommandOptionType.Subcommand,
|
||||
description: 'Set the bot status',
|
||||
options: [
|
||||
{
|
||||
name: 'status',
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
description: 'Choose the bot status',
|
||||
required: true,
|
||||
choices: [
|
||||
{ name: 'Online 🟢', value: 'online' },
|
||||
{ name: 'Idle 🌙', value: 'idle' },
|
||||
{ name: 'Do Not Disturb ⛔', value: 'dnd' },
|
||||
{ name: 'Invisible 👻', value: 'invisible' }
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'setactivity',
|
||||
type: Discord.ApplicationCommandOptionType.Subcommand,
|
||||
description: 'Set the bot activity',
|
||||
options: [
|
||||
{
|
||||
name: 'type',
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
description: 'Choose the activity type',
|
||||
required: true,
|
||||
choices: [
|
||||
{ name: 'Playing 🎮', value: 'PLAYING' },
|
||||
{ name: 'Watching 👀', value: 'WATCHING' },
|
||||
{ name: 'Listening 🎧', value: 'LISTENING' },
|
||||
{ name: 'Competing 🏆', value: 'COMPETING' }
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'message',
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
description: 'The activity message',
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'streammode',
|
||||
type: Discord.ApplicationCommandOptionType.Subcommand,
|
||||
description: 'Set the bot streaming status',
|
||||
options: [
|
||||
{
|
||||
name: 'toggle',
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
description: 'Turn streaming mode on or off',
|
||||
required: true,
|
||||
choices: [
|
||||
{ name: 'On', value: 'on' },
|
||||
{ name: 'Off', value: 'off' }
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'twitchurl',
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
description: 'Twitch stream URL (Required if turning on)',
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'setnickname',
|
||||
type: Discord.ApplicationCommandOptionType.Subcommand,
|
||||
description: 'Set the bot nickname',
|
||||
options: [
|
||||
{
|
||||
name: 'nickname',
|
||||
type: Discord.ApplicationCommandOptionType.String,
|
||||
description: 'The new nickname for the bot',
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
async run(interaction) {
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
const settings = await loadSettings();
|
||||
|
||||
if (subcommand === 'setstatus') {
|
||||
const status = interaction.options.getString('status');
|
||||
|
||||
try {
|
||||
interaction.client.user.setPresence({
|
||||
status: status,
|
||||
activities: interaction.client.user.presence.activities || [],
|
||||
});
|
||||
|
||||
settings.status = status;
|
||||
await saveSettings(settings);
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(`Status set to **${status.charAt(0).toUpperCase() + status.slice(1)}**`)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
return interaction.reply({ embeds: [embed], flags: Discord.MessageFlags.Ephemeral });
|
||||
} catch (error) {
|
||||
return interaction.reply({ content: `Failed to set status: ${error.message}`, flags: Discord.MessageFlags.Ephemeral });
|
||||
}
|
||||
}
|
||||
|
||||
if (subcommand === 'setactivity') {
|
||||
const activityType = interaction.options.getString('type');
|
||||
const activityMessage = interaction.options.getString('message');
|
||||
|
||||
try {
|
||||
interaction.client.user.setPresence({
|
||||
activities: [{ name: activityMessage, type: Discord.ActivityType[activityType] }],
|
||||
status: interaction.client.user.presence.status || 'online',
|
||||
});
|
||||
|
||||
settings.activity = { type: activityType, message: activityMessage };
|
||||
await saveSettings(settings);
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(`Activity set to **${activityType.toLowerCase()} ${activityMessage}**`)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
return interaction.reply({ embeds: [embed], flags: Discord.MessageFlags.Ephemeral });
|
||||
} catch (error) {
|
||||
return interaction.reply({ content: `Failed to set activity: ${error.message}`, flags: Discord.MessageFlags.Ephemeral });
|
||||
}
|
||||
} else if (subcommand === 'streammode') {
|
||||
const toggle = interaction.options.getString('toggle');
|
||||
const twitchUrl = interaction.options.getString('twitchurl');
|
||||
|
||||
if (toggle === 'on') {
|
||||
if (!twitchUrl) {
|
||||
return interaction.reply({ content: 'Please provide a Twitch URL to stream.', flags: Discord.MessageFlags.Ephemeral });
|
||||
}
|
||||
|
||||
try {
|
||||
interaction.client.user.setPresence({
|
||||
activities: [{ name: 'Streaming', type: Discord.ActivityType.Streaming, url: twitchUrl }],
|
||||
status: 'online',
|
||||
});
|
||||
|
||||
settings.streaming = { active: true, url: twitchUrl };
|
||||
await saveSettings(settings);
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(`**Streaming mode enabled!**\nStreaming: [Twitch](${twitchUrl})`)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
return interaction.reply({ embeds: [embed], flags: Discord.MessageFlags.Ephemeral });
|
||||
} catch (error) {
|
||||
return interaction.reply({ content: `Failed to enable streaming mode: ${error.message}`, flags: Discord.MessageFlags.Ephemeral });
|
||||
}
|
||||
} else if (toggle === 'off') {
|
||||
try {
|
||||
interaction.client.user.setPresence({
|
||||
activities: interaction.client.user.presence.activities.filter(a => a.type !== Discord.ActivityType.Streaming),
|
||||
status: settings.status || 'online',
|
||||
});
|
||||
|
||||
settings.streaming = { active: false };
|
||||
await saveSettings(settings);
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(`**Streaming mode disabled!**`)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
return interaction.reply({ embeds: [embed], flags: Discord.MessageFlags.Ephemeral });
|
||||
} catch (error) {
|
||||
return interaction.reply({ content: `Failed to disable streaming mode: ${error.message}`, flags: Discord.MessageFlags.Ephemeral });
|
||||
}
|
||||
}
|
||||
} else if (subcommand === 'setnickname') {
|
||||
const nickname = interaction.options.getString('nickname');
|
||||
|
||||
try {
|
||||
const guild = interaction.guild;
|
||||
const botMember = guild.members.cache.get(interaction.client.user.id);
|
||||
await botMember.setNickname(nickname);
|
||||
|
||||
settings.nickname = nickname;
|
||||
await saveSettings(settings);
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(`Bot nickname set to **${nickname}**`)
|
||||
.setColor(supportbot.Embed.Colours.General);
|
||||
|
||||
return interaction.reply({ embeds: [embed], flags: Discord.MessageFlags.Ephemeral });
|
||||
} catch (error) {
|
||||
return interaction.reply({ content: `Failed to set nickname: ${error.message}`, flags: Discord.MessageFlags.Ephemeral });
|
||||
}
|
||||
} else {
|
||||
return interaction.reply({ content: 'Invalid command usage.', flags: Discord.MessageFlags.Ephemeral });
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,174 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Close Ticket Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
const TicketNumberID = require('../Structures/TicketID.js');
|
||||
|
||||
async function asyncForEach(array, callback) {
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
await callback(array[index], index, array);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.CloseTicket,
|
||||
description: cmdconfig.CloseTicketDesc,
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
if (!message.channel.name.startsWith( `${supportbot.TicketChannel}-` )) {
|
||||
const Exists = new Discord.MessageEmbed()
|
||||
.setTitle("No Ticket Found!")
|
||||
.setDescription(`${supportbot.NoValidTicket}`)
|
||||
.setColor(supportbot.WarningColour);
|
||||
message.channel.send({ embed: Exists });
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (supportbot.CloseConfirmation) {
|
||||
const CloseTicketRequest = new Discord.MessageEmbed()
|
||||
.setTitle(`**${supportbot.ClosingTicket}**`)
|
||||
.setDescription(`Please confirm by repeating the following word.. \`${supportbot.ClosingConfirmation_Word}\` `)
|
||||
.setColor(supportbot.EmbedColour);
|
||||
|
||||
message.channel.send(CloseTicketRequest).then(m => {
|
||||
message.channel.awaitMessages( response => response.content.toLowerCase() === supportbot.ClosingConfirmation_Word, {
|
||||
max: 1,
|
||||
time: 20000,
|
||||
errors: [ 'time' ],
|
||||
|
||||
|
||||
}).then( collected => {
|
||||
let logChannel = message.guild.channels.cache.find(channel => channel.name === supportbot.TranscriptLog) || message.guild.channels.cache.find(channel => channel.id === supportbot.TranscriptLog)
|
||||
let user = message.author;
|
||||
let reason = args.join(" ") || "No Reason Provided.";
|
||||
|
||||
let name = message.channel.name;
|
||||
let ticketChannel = message.channel;
|
||||
|
||||
message.channel.send(`**${supportbot.ClosingTicket}**`)
|
||||
|
||||
.then(() => {
|
||||
const logEmbed = new Discord.MessageEmbed()
|
||||
.setTitle(supportbot.TranscriptTitle)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
.setFooter(supportbot.EmbedFooter)
|
||||
.addField("Closed By", message.author.tag)
|
||||
.addField("Reason", reason);
|
||||
|
||||
message.channel.messages.fetch({ limit: 100 }).then( msgs => {
|
||||
let html = '';
|
||||
|
||||
msgs = msgs.sort( ( a, b ) => a.createdTimestamp - b.createdTimestamp );
|
||||
html += `<strong>Server Name:</strong> ${message.guild.name}<br>`;
|
||||
html += `<strong>Ticket:</strong> ${ticketChannel.name}<br>`;
|
||||
html += `<strong>Message:</strong> ${msgs.size} Messages<br><br><br>`;
|
||||
|
||||
msgs.forEach( msg => {
|
||||
if ( msg.content ) {
|
||||
html += `<strong>User:</strong> ${msg.author.tag}<br>`;
|
||||
html += `<strong>Message:</strong> ${msg.content}<br>`;
|
||||
html += `-----<br><br>`;
|
||||
}
|
||||
});
|
||||
|
||||
logChannel.send({embeds: [logEmbed]}).catch(err => {
|
||||
message.reply(err)
|
||||
})
|
||||
|
||||
|
||||
let file = new Discord.MessageAttachment( Buffer.from( html ), `${name}.html` )
|
||||
logChannel.send({embeds: [logEmbed], files: [file]}).catch(err => {
|
||||
message.reply(err)
|
||||
})
|
||||
|
||||
message.channel.delete().catch(error => {
|
||||
if (error.code !== Discord.Constants.APIErrors.UNKNOWN_CHANNEL) {
|
||||
console.error('Failed to delete the message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
}).catch( () => {
|
||||
interaction.m.edit({content: 'The request to close the ticket has timed out.'}).then(m2 => setTimeout(() => channel.delete(3000)) );
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
if (!supportbot.CloseConfirmation) {
|
||||
|
||||
let logChannel = message.guild.channels.cache.find(channel => channel.name === supportbot.TranscriptLog) || message.guild.channels.cache.find(channel => channel.id === supportbot.TranscriptLog)
|
||||
let user = message.author;
|
||||
let reason = args.join(" ") || "No Reason Provided.";
|
||||
|
||||
let name = message.channel.name;
|
||||
let ticketChannel = message.channel;
|
||||
|
||||
message.channel.send(`**${supportbot.ClosingTicket}**`)
|
||||
|
||||
.then(() => {
|
||||
const logEmbed = new Discord.MessageEmbed()
|
||||
.setTitle(supportbot.TranscriptTitle)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
.setFooter(supportbot.EmbedFooter)
|
||||
.addField("Closed By", message.author.tag)
|
||||
.addField("Reason", reason);
|
||||
|
||||
message.channel.messages.fetch({ limit: 100 }).then( msgs => {
|
||||
let html = '';
|
||||
|
||||
msgs = msgs.sort( ( a, b ) => a.createdTimestamp - b.createdTimestamp );
|
||||
html += `<strong>Server Name:</strong> ${message.guild.name}<br>`;
|
||||
html += `<strong>Ticket:</strong> ${ticketChannel.name}<br>`;
|
||||
html += `<strong>Message:</strong> ${msgs.size} Messages<br><br><br>`;
|
||||
|
||||
msgs.forEach( msg => {
|
||||
if ( msg.content ) {
|
||||
html += `<strong>User:</strong> ${msg.author.tag}<br>`;
|
||||
html += `<strong>Message:</strong> ${msg.content}<br>`;
|
||||
html += `-----<br><br>`;
|
||||
}
|
||||
});
|
||||
|
||||
logChannel.send({embeds: [logEmbed]}).catch(err => {
|
||||
message.reply(err)
|
||||
})
|
||||
|
||||
let file = new Discord.MessageAttachment( Buffer.from( html ), `${name}.html` )
|
||||
logChannel.send({embeds: [logEmbed], files: [file]}).catch(err => {
|
||||
message.reply(err)
|
||||
})
|
||||
|
||||
message.channel.delete().catch(error => {
|
||||
if (error.code !== Discord.Constants.APIErrors.UNKNOWN_CHANNEL) {
|
||||
console.error('Failed to delete the message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
})
|
||||
|
||||
}).catch( () => {
|
||||
interaction.m.edit({content: 'The request to close the ticket has timed out.'}).then(m2 => setTimeout(() => channel.delete(3000)) );
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Close Ticket Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
const TicketNumberID = require('../Structures/TicketID.js');
|
||||
|
||||
async function asyncForEach(array, callback) {
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
await callback(array[index], index, array);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.HelpCommand,
|
||||
description: cmdconfig.HelpCommandDesc,
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
let SupportStaff = message.guild.roles.cache.find(adminRole => adminRole.name === supportbot.Staff) || message.guild.roles.cache.find(staffRole => staffRole.id === supportbot.Staff);
|
||||
let AdminStaff = message.guild.roles.cache.find(adminRole => adminRole.name === supportbot.Admin) || message.guild.roles.cache.find(adminRole => adminRole.id === supportbot.Admin);
|
||||
|
||||
if (supportbot.HelpMenu) {
|
||||
let botCommands = "";
|
||||
botCommands += `**${supportbot.Prefix}${cmdconfig.HelpCommand}** ${cmdconfig.HelpCommandDesc}\n`;
|
||||
botCommands += `**${supportbot.Prefix}${cmdconfig.InfoCommand}** ${cmdconfig.InfoCommandDesc}\n`;
|
||||
botCommands += `**${supportbot.Prefix}${cmdconfig.PingCommand}** ${cmdconfig.PingCommandDesc}\n`
|
||||
|
||||
let ticketCommands = "";
|
||||
ticketCommands += `**${supportbot.Prefix}${cmdconfig.OpenTicket}** ${cmdconfig.OpenTicketDesc}\n`;
|
||||
ticketCommands += `**${supportbot.Prefix}${cmdconfig.CloseTicket}** ${cmdconfig.CloseTicketDesc}\n`
|
||||
|
||||
let staffCommands = "";
|
||||
staffCommands += `**${supportbot.Prefix}${cmdconfig.TicketAdd}** ${cmdconfig.TicketAddDesc}\n`
|
||||
staffCommands += `**${supportbot.Prefix}${cmdconfig.TicketRemove}** ${cmdconfig.TicketRemoveDesc}\n`
|
||||
|
||||
const HelpEmbed1 = new Discord.MessageEmbed()
|
||||
.setTitle(supportbot.Name)
|
||||
.setThumbnail(message.author.displayAvatarURL())
|
||||
|
||||
.addFields(
|
||||
{ name: '🖥️ General Commands\n', value: `${botCommands}\n`, inline: false },
|
||||
{ name: '🎫 Support Commands\n', value: `${ticketCommands}\n`, inline: false },
|
||||
)
|
||||
|
||||
.setColor(supportbot.EmbedColour)
|
||||
.setFooter(supportbot.EmbedFooter, message.author.displayAvatarURL());
|
||||
|
||||
if (message.member.roles.cache.has(SupportStaff.id)) {
|
||||
HelpEmbed1.addFields(
|
||||
{ name: '🔐 Staff Commands\n', value: `${staffCommands}\n`, inline: false },
|
||||
)
|
||||
} else {
|
||||
if ((message.member.roles.cache.has(AdminStaff.id))) {
|
||||
HelpEmbed1.addFields(
|
||||
{ name: '🔐 Staff Commands\n', value: `${staffCommands}\n`, inline: false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (supportbot.SendHelpPage === "dm") {
|
||||
message.author.send({
|
||||
embeds: [HelpEmbed1]
|
||||
});
|
||||
}
|
||||
|
||||
if (supportbot.SendHelpPage === "channel") {
|
||||
message.channel.send({
|
||||
embeds: [HelpEmbed1]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Info Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.InfoCommand,
|
||||
description: cmdconfig.InfoCommandDesc,
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
const InfoButton = new Discord.MessageButton()
|
||||
.setLabel(supportbot.InfoButtonText)
|
||||
.setURL(supportbot.InfoURL)
|
||||
.setStyle('LINK')
|
||||
|
||||
const inforow = new Discord.MessageActionRow()
|
||||
.addComponents(InfoButton)
|
||||
|
||||
const InfoEmbed = new Discord.MessageEmbed()
|
||||
.setURL(supportbot.InfoURL)
|
||||
.setTitle(supportbot.InfoTitle)
|
||||
.setDescription(supportbot.AboutMe)
|
||||
.setColor(supportbot.InfoColour)
|
||||
|
||||
|
||||
message.channel.send({
|
||||
embeds: [InfoEmbed], components: [inforow]
|
||||
})
|
||||
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
# -------------------------------
|
||||
# API Server Configuration
|
||||
# -------------------------------
|
||||
|
||||
API:
|
||||
Enabled: true
|
||||
Port: 3000 # PORT NUMBER FOR YOUR BOT
|
||||
SecretKey: "PUT_RANDOM_STRING_HERE" # DO NOT SHARE THIS KEY WITH ANYONE
|
||||
@@ -0,0 +1,196 @@
|
||||
# ___ _ ___ _
|
||||
# / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
# \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
# <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
# |_| |_|
|
||||
#
|
||||
# SupportBot created by Emerald Services
|
||||
# Installed with MIT License
|
||||
#
|
||||
# Discord Support: https://discord.gg/emeraldsrv
|
||||
# Official Documentation: https://docs.emeraldsrv.com
|
||||
# Addons Marketplace: https://community.emeraldsrv.com
|
||||
#
|
||||
# Commands Configuration (commands.yml)
|
||||
|
||||
Help:
|
||||
Command: "help"
|
||||
Description: "Get a list of all the commands."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
Info:
|
||||
Command: "info"
|
||||
Description: "Get information about the **ServerName**."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
TicketPanel:
|
||||
Command: "ticketpanel"
|
||||
Description: "Create the ticket creation panel"
|
||||
Permission: ["Administrator"]
|
||||
Enabled: true
|
||||
|
||||
Profile:
|
||||
Command: "profile"
|
||||
Description: "Shows the profile for a discord member."
|
||||
Permission: ["SendMessages"]
|
||||
# Command is automatically disabled when the TicketClaims is disabled.
|
||||
|
||||
OpenTicket:
|
||||
Command: "ticket"
|
||||
Description: "Create a support ticket."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
AddUser:
|
||||
Command: "add"
|
||||
Description: "Add a user to a support ticket."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
CloseTicket:
|
||||
Command: "close"
|
||||
Description: "Close a support ticket"
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
TicketManage:
|
||||
Command: "ticketmanage"
|
||||
Description: "Manage an existing support ticket."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
Close:
|
||||
Command: "close"
|
||||
Description: "Close a support ticket."
|
||||
|
||||
ForceAdd:
|
||||
Command: "forceadd"
|
||||
Description: "Add a user to a support ticket by bypassing the invite system."
|
||||
|
||||
ForceRemove:
|
||||
Command: "forceremove"
|
||||
Description: "Remove a user from a support ticket by bypassing the normal restrictions."
|
||||
|
||||
Rename:
|
||||
Command: "rename"
|
||||
Description: "Rename a support ticket by bypassing the normal restrictions."
|
||||
|
||||
Suggestion:
|
||||
Command: "suggest"
|
||||
Description: "Create a suggestion."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
SuggestionAdmin:
|
||||
Command: "suggestadmin"
|
||||
Description: "Update a suggestion’s status."
|
||||
Permission: ['SendMessages']
|
||||
# Disable "Suggestion" to disable this command.
|
||||
|
||||
Embed:
|
||||
Command: "embed"
|
||||
Description: "Build a discord embed."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
Translate:
|
||||
Command: "translate"
|
||||
Description: "Translate something to english"
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
UserInfo:
|
||||
Command: "userinfo"
|
||||
Description: "Get info about a user."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
Ping:
|
||||
Command: "ping"
|
||||
Description: "Pong."
|
||||
Permission: ["SendMessages"]
|
||||
Enabled: true
|
||||
|
||||
# ---------------------------------------
|
||||
# Bot Moderator Commands
|
||||
# ---------------------------------------
|
||||
|
||||
Mod:
|
||||
Command: "mod"
|
||||
Description: "Execute a moderation action."
|
||||
Permission: ["BanMembers", "KickMembers"]
|
||||
Enabled: true
|
||||
|
||||
TicketBlacklist:
|
||||
Command: "ticket-blacklist"
|
||||
Description: "Blacklist a user from creating Tickets."
|
||||
|
||||
Add:
|
||||
Command: "add"
|
||||
Description: "Add a user to the blacklist."
|
||||
|
||||
Remove:
|
||||
Command: "remove"
|
||||
Description: "Remove a user from the blacklist."
|
||||
|
||||
View:
|
||||
Command: "view"
|
||||
Description: "View all blacklisted users."
|
||||
|
||||
# ---------------------------------------
|
||||
# Bot Administrator Commands
|
||||
# ---------------------------------------
|
||||
|
||||
Settings:
|
||||
Command: "settings"
|
||||
Description: "Update bot settings."
|
||||
Permission: ["Administrator"]
|
||||
Enabled: true
|
||||
|
||||
AI:
|
||||
Command: "ai"
|
||||
Description: "Manage SupportBot AI settings and memory."
|
||||
Permission: ["Administrator"]
|
||||
Enabled: true
|
||||
|
||||
Train:
|
||||
Command: "train"
|
||||
Description: "Train the AI by adding knowledge to its database."
|
||||
|
||||
Knowledge:
|
||||
Command: "knowledge"
|
||||
Description: "Manage the AI knowledge base."
|
||||
Clear:
|
||||
Command: "clear"
|
||||
Description: "Clear all trained knowledge from the AI."
|
||||
|
||||
Memory:
|
||||
Command: "memory"
|
||||
Description: "Manage the AI conversational memory."
|
||||
Clear:
|
||||
Command: "clear"
|
||||
Description: "Clear recent conversation memory for this channel."
|
||||
|
||||
# ---------------------------------------
|
||||
# Command Description Configuration
|
||||
# ---------------------------------------
|
||||
|
||||
BlacklistDesc: "Blacklist a user from creating Tickets."
|
||||
TicketAddDesc: "Add a user to a support ticket."
|
||||
TicketRemoveDesc: "Remove a user from a support ticket."
|
||||
TranslateCommandDesc: "Translates the language provided, along with the abbreviation (2 char) long language code"
|
||||
OpenTicketDesc: "Open a new support ticket."
|
||||
CloseTicketDesc: "Close your support ticket."
|
||||
InfoCommandDesc: "Get information about the brand."
|
||||
PingCommandDesc: "Pong!"
|
||||
HelpCommandDesc: "Get a list of all the commands."
|
||||
EmbedCommandDesc: "Send a message as an embed."
|
||||
SuggestCommandDesc: "Suggest a feature for the server."
|
||||
UserInfoCommandDesc: "Get info about a user."
|
||||
TicketManageDesc: "Manage an existing support ticket."
|
||||
TicketManageCloseDesc: "Close a support ticket."
|
||||
TicketManageForceAddDesc: "Add a user to a support ticket by bypassing the invite system."
|
||||
TicketManageForceRemoveDesc: "Remove a user from a support ticket by bypassing the normal restrictions."
|
||||
TicketManageForceRenameDesc: "Rename a support ticket by bypassing the normal restrictions."
|
||||
@@ -0,0 +1,333 @@
|
||||
# ___ _ ___ _
|
||||
# / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
# \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
# <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
# |_| |_|
|
||||
#
|
||||
# SupportBot created by Emerald Services
|
||||
# Installed with MIT License
|
||||
#
|
||||
# Discord Support: https://discord.gg/emeraldsrv
|
||||
# Official Documentation: https://docs.emeraldsrv.com
|
||||
# Addons Marketplace: https://community.emeraldsrv.com
|
||||
#
|
||||
# Messages Configuration (messages.yml)
|
||||
|
||||
# ----------------------------
|
||||
# Info Command
|
||||
# ----------------------------
|
||||
|
||||
Info:
|
||||
Title: "About Us"
|
||||
Description: "SupportBot is an open-sourced support system for discord. It's completely free to use with high amounts of customization to match your own brand."
|
||||
Button: "Visit Site"
|
||||
URL: "https://docs.emeraldsrv.com"
|
||||
Colour: "#45b463"
|
||||
|
||||
# ----------------------------
|
||||
# Welcome/Leave Messages
|
||||
# ----------------------------
|
||||
|
||||
Welcome:
|
||||
Enabled: true
|
||||
LayoutStyle: "modern"
|
||||
# Available Layout Styles
|
||||
# "modern" - For the new Discord v2 components
|
||||
# "classic" - Use the classic Discord look.
|
||||
|
||||
Embed:
|
||||
Colour: "#45b463"
|
||||
Title: "Welcome to ServerName"
|
||||
Message: ":smile: %joined_user% has just landed!\n\n🔨 **Server Rules:** <#1202667199853232129>"
|
||||
Icon:
|
||||
Mode: "USER" # USER | BOT | CUSTOM
|
||||
CustomURL: "https://example.com/custom.png"
|
||||
Image:
|
||||
Enabled: false
|
||||
URL: "https://example.com/banner.png"
|
||||
Buttons:
|
||||
Enabled: true
|
||||
List:
|
||||
- label: "BuiltByBit"
|
||||
style: "Link"
|
||||
url: "https://your-website.com/how-to-play-java"
|
||||
emoji: "⌨️"
|
||||
- label: "GitHub"
|
||||
style: "Link"
|
||||
url: "https://your-website.com/how-to-play-bedrock"
|
||||
emoji: "👾"
|
||||
- label: "Tebex"
|
||||
style: "Link"
|
||||
url: "https://your-store.tebex.io/"
|
||||
emoji: "🛒"
|
||||
|
||||
Modern:
|
||||
Colour: "#45b463"
|
||||
Title: "**Welcome to ServerName**"
|
||||
Body: ":smile: %joined_user% has just landed!\n\n🔨 **Server Rules:** <#1202667199853232129>"
|
||||
Icon:
|
||||
Mode: "BOT" # USER | BOT | CUSTOM
|
||||
CustomURL: "https://example.com/custom-icon.png"
|
||||
Image:
|
||||
Enabled: false
|
||||
URL: "https://example.com/banner.png"
|
||||
Buttons:
|
||||
- label: "BuiltByBit"
|
||||
style: "Link"
|
||||
url: "https://your-website.com/how-to-play-java"
|
||||
emoji: "⌨️"
|
||||
- label: "GitHub"
|
||||
style: "Link"
|
||||
url: "https://your-website.com/how-to-play-bedrock"
|
||||
emoji: "👾"
|
||||
- label: "Tebex"
|
||||
style: "Link"
|
||||
url: "https://your-store.tebex.io/"
|
||||
emoji: "🛒"
|
||||
|
||||
Leave:
|
||||
Embed:
|
||||
Colour: "#f74343"
|
||||
Title: "Goodbye!"
|
||||
Message: ":slight_frown: %left_user% has recently dropped out!"
|
||||
Thumbnail: "BOT"
|
||||
|
||||
ImageEnabled: false
|
||||
ImageURL: "https://animagelink.png/"
|
||||
|
||||
# ----------------------------
|
||||
# Suggestion Messages
|
||||
# ----------------------------
|
||||
|
||||
Suggestions:
|
||||
Sent_Title: "Suggestion Sent!"
|
||||
Sent: ":white_check_mark: **You have successfully sent a suggestion.**"
|
||||
NoSelfVote: ":x: **You cannot vote on your own suggestion.**"
|
||||
RemoveVoteButton: "Remove Vote"
|
||||
|
||||
# ----------------------------
|
||||
# Ticket Messages
|
||||
# ----------------------------
|
||||
|
||||
Ticket:
|
||||
|
||||
# Available Placeholders:
|
||||
|
||||
# %ticketusername% - User who created the ticket.
|
||||
# <@%ticketauthor%> - Tags the user who created the ticket.
|
||||
# <#%ticketid%> - Mentions the ticket channel.
|
||||
|
||||
# You can use Markdown formatting in this message:
|
||||
# # Heading 1
|
||||
# ## Heading 2
|
||||
# ### Heading 3
|
||||
# **Bold** text
|
||||
# *Italic* text
|
||||
# -# Small text
|
||||
# - Bullet points
|
||||
# Links: [text](https://example.com)
|
||||
|
||||
TicketAuthorTitle: "-# %ticketusername%'s Ticket"
|
||||
TicketTitle: "## Support Ticket"
|
||||
TicketMessage: "Hello <@%ticketauthor%>, Thank you for creating a support ticket\nPlease wait patiently whilst a member of our team reaches out to you."
|
||||
TicketThumbnail: "https://images.emojiterra.com/google/android-pie/512px/1f39f.png"
|
||||
TicketCreatedAlert: ":ticket: Ticked Created: <#%ticketid%>"
|
||||
TicketExists: "❌ Ticket already exists"
|
||||
TicketClaim: ":white_check_mark: Ticket claimed by" #The user who claimed the ticket will be added to the end of this message
|
||||
TicketUnclaim: ":white_check_mark: Ticket unclaimed by" #The user who claimed the ticket will be added to the end of this message
|
||||
|
||||
TicketArchived: ":white_check_mark: Ticket archived."
|
||||
TicketUnarchived: ":white_check_mark: Ticket unarchived."
|
||||
TicketLocked: ":lock: Ticket is locked."
|
||||
DisableInvites: "🔒 Invites have been disabled for this ticket."
|
||||
EnableInvites: "🔓 Invites have been enabled for this ticket."
|
||||
|
||||
# Available Placeholders:
|
||||
|
||||
# <@%user%> - Tags the user who was added to the ticket.
|
||||
|
||||
Blacklisted: ":x: You are not allowed to open a ticket"
|
||||
Muted: ":x: You are `Muted` and therefore not allowed to open any tickets"
|
||||
InvalidSubject: "No Reason Provided!"
|
||||
|
||||
ConfirmClose: "Please confirm closing the ticket by clicking the button below."
|
||||
CloseTimeout: "Ticket close confirmation timed out."
|
||||
|
||||
RenamedSuccess: "🏷️ Ticket renamed successfully!"
|
||||
|
||||
ClaimTickets:
|
||||
ClaimTitle: "Incoming Support Request!"
|
||||
ClaimMessage: "A new ticket has been created by <@!%user%>. Click the button below to claim this ticket."
|
||||
ClaimMessage_Edit: "<#%channel%> was claimed by <@!%user%>."
|
||||
|
||||
ClaimedTitle: "Ticket Claimed!"
|
||||
Claimed: "You have successfully claimed this ticket. <#%channel%>"
|
||||
NoPermsToClaimTitle: "Error, no permissions!"
|
||||
NoPermsToClaim: ":x: **Err!** You do not permissions to claim this ticket."
|
||||
|
||||
ReassigningTitle: "Reassigning!..."
|
||||
ReassigningMessage: "<@%user%> did not claim the ticket. **Reassigning...**"
|
||||
|
||||
TicketQuestions:
|
||||
Details:
|
||||
Title: "Ticket Details"
|
||||
Description: "Questions by <@%user%>" # Use <@%user%> to display the username.
|
||||
|
||||
AIMode:
|
||||
Title: "SupportBot AI"
|
||||
Description: "Use the buttons below to enable or disable AI chat in this ticket."
|
||||
EnabledMessage: "AI Mode has been enabled for this ticket."
|
||||
DisabledMessage: "AI Mode has been disabled for this ticket."
|
||||
|
||||
ThreadWelcomeTitle: "SupportBot AI"
|
||||
ThreadWelcomeMessage: "Hi! I’m SupportBot AI. You can chat with me here about your issue."
|
||||
|
||||
EnableButton: "Enable AI Mode"
|
||||
DisableButton: "Disable AI Mode"
|
||||
|
||||
TicketNotFound: "Ticket not found."
|
||||
EnableError: "There was an error enabling SupportBot AI."
|
||||
DisableError: "There was an error disabling SupportBot AI."
|
||||
|
||||
# ----------------------------
|
||||
# Review Messages
|
||||
# ----------------------------
|
||||
|
||||
ReviewSystem:
|
||||
Rate:
|
||||
Title: "Review us!"
|
||||
Description: "Please rate our support for this ticket (1-5 stars)."
|
||||
|
||||
Stars:
|
||||
One: "⭐ 1 Star"
|
||||
Two: "⭐⭐ 2 Stars"
|
||||
Three: "⭐⭐⭐ 3 Stars"
|
||||
Four: "⭐⭐⭐⭐ 4 Stars"
|
||||
Five: "⭐⭐⭐⭐⭐ 5 Stars"
|
||||
|
||||
Comment:
|
||||
Title: "Write a comment."
|
||||
Description: "Write a comment about your experience."
|
||||
|
||||
ReviewEmbed:
|
||||
Title: "Ticket Review"
|
||||
CommentTitle: "Comment"
|
||||
RatingTitle: "Rating"
|
||||
ReviewedStaffTitle: "Reviewed Staff:"
|
||||
ReviewedByTitle: "Reviewed By:"
|
||||
ReviewEmoji: "⭐"
|
||||
Color: "#f7a943"
|
||||
|
||||
# ----------------------------
|
||||
# Mod Command Messages
|
||||
# ----------------------------
|
||||
|
||||
Mod:
|
||||
|
||||
TicketBlacklist:
|
||||
Add:
|
||||
Description: "Add a user to the ticket blacklist"
|
||||
UserDescription: "User to blacklist"
|
||||
AlreadyBlacklisted: ":x: {userTag} is already blacklisted."
|
||||
Success: ":white_check_mark: {userTag} has been added to the blacklist. They can no longer use the ticket system."
|
||||
|
||||
Remove:
|
||||
Description: "Remove a user from the ticket blacklist"
|
||||
UserDescription: "User to remove from blacklist"
|
||||
NotBlacklisted: ":x: {userTag} is not blacklisted."
|
||||
Success: ":white_check_mark: {userTag} has been removed from the blacklist. They can now use the ticket system again."
|
||||
|
||||
View:
|
||||
Description: "View the list of all blacklisted users"
|
||||
NoBlacklistedUsers: ":information_source: There are currently no users on the blacklist."
|
||||
|
||||
|
||||
# ----------------------------
|
||||
# Logging Messages
|
||||
# ----------------------------
|
||||
|
||||
TicketLog:
|
||||
Title: "Ticket Log"
|
||||
Colour: "#0cc559"
|
||||
|
||||
TicketBlacklistLog:
|
||||
Title: "Ticket Blacklist Log"
|
||||
Colour: "#0cc559"
|
||||
|
||||
# ----------------------------
|
||||
# Misc Messages
|
||||
# ----------------------------
|
||||
|
||||
AddUser:
|
||||
NotInTicket_Title: "Ticket Invitation"
|
||||
NotInTicket_Description: "This command can only be used within a ticket thread."
|
||||
|
||||
Invite_Title: "User Invited"
|
||||
Invite_Description: "%username% has been invited to join the ticket."
|
||||
|
||||
DM_Title: "Ticket Invitation"
|
||||
DM_Description: "You have been invited to join the ticket %channelname%. Do you accept?"
|
||||
|
||||
Accept_Label: "Accept"
|
||||
Reject_Label: "Reject"
|
||||
ViewTicket_Label: "Go to Ticket"
|
||||
|
||||
Accepted_Title: "Invitation Accepted"
|
||||
Accepted_Message: "You have been added to the ticket."
|
||||
AddedToTicket_Title: "Added to Ticket"
|
||||
AddedToTicket_Description: "You have been added to the ticket %channel_link%."
|
||||
|
||||
# Added Message for inside the ticket, this informs everyone inside the ticket that the user has been added.
|
||||
Added_Title: "User Added"
|
||||
Added_Description: "Successfully added **%username%** to the ticket."
|
||||
|
||||
Declined_Title: "Invitation Declined"
|
||||
Declined_Message: "You have declined the invitation."
|
||||
|
||||
NoResponse_Title: "No Response"
|
||||
NoResponse_Message: "You did not respond in time. Please contact staff if you wish to join the ticket."
|
||||
|
||||
Error_Title: "Error"
|
||||
Error_Adding: "There was an error adding you to the ticket. Please try again."
|
||||
|
||||
DM_Error_Title: "Error"
|
||||
DM_Error_Description: "Unable to send a DM to %username%. Please ensure your DMs are enabled."
|
||||
|
||||
Unexpected_Error_Title: "Error"
|
||||
Unexpected_Error_Description: "An unexpected error occurred: %error%"
|
||||
|
||||
RemoveUser:
|
||||
NotInTicket_Title: "Error"
|
||||
NotInTicket_Description: "This command can only be used in ticket threads."
|
||||
|
||||
Removed_Title: "User Removed"
|
||||
Removed_Message: "The user has been successfully removed from the ticket."
|
||||
|
||||
RemovedFromTicket_Title: "Removed from Ticket"
|
||||
RemovedFromTicket_Description: "You have been removed from the ticket channel %channel_link%."
|
||||
|
||||
Error_Title: "Error"
|
||||
Error_Removing: "There was an error removing the user from the ticket."
|
||||
|
||||
ForceAddUser:
|
||||
NotInTicket_Title: "Not a Ticket"
|
||||
NotInTicket_Description: "This command can only be used within a ticket thread."
|
||||
|
||||
Added_Title: "User Added"
|
||||
Added_Description: "Successfully added %username% to the ticket."
|
||||
|
||||
AddedToTicket_Title: "You have been added to a Ticket"
|
||||
AddedToTicket_Description: "You have been added to the ticket channel [%channel_link%]."
|
||||
|
||||
Error_Title: "Error"
|
||||
Error_Adding: "There was an error adding the user to the ticket."
|
||||
|
||||
Error:
|
||||
IncorrectPermissions: ":x: **Error!** You do not have the correct permissions to use this command."
|
||||
MissingChannel: ":x: **Error!** Required channel not found. Please ensure it is set up correctly!"
|
||||
UserNotFound: ":x: **Error!** Specified user not found. Please check if they are in this server."
|
||||
CommandNotAllowedHere: ":warning: This command cannot be used in this channel."
|
||||
EntryAlreadyExists: ":warning: Cannot complete the action, as the entry already exists."
|
||||
EntryDoesNotExist: ":warning: Cannot complete the action, as the entry does not exist."
|
||||
ActionFailed: ":x: **Error!** An error occurred while processing your request. Please try again later."
|
||||
InvalidChannel: ":x: **Error!** The suggestions channel has not been set up correctly."
|
||||
@@ -0,0 +1,76 @@
|
||||
# -------------------------
|
||||
# SupportBot AI
|
||||
#
|
||||
# In order to use the SupportBot AI, You need to setup an OpenAI or Groq Developer Account.
|
||||
# this can be done at https://platform.openai.com/ or https://groq.com/
|
||||
# -------------------------
|
||||
|
||||
Enabled: true
|
||||
|
||||
General:
|
||||
Provider: "claude"
|
||||
Model: "claude-sonnet-4-6"
|
||||
Model_API_Key: "MODEL_API_KEY"
|
||||
# Providers Available:
|
||||
# "openai" - Use OpenAI's GPT models. Example: "gpt-5.4" "gpt-5-mini"
|
||||
# "groq" - Use Groq's GroqAI models. Example: "meta-llama/llama-4-scout-17b-16e-instruct"
|
||||
# "claude" - Use Anthropic's Claude models. Example: "claude-sonnet-4-6"
|
||||
|
||||
Tokens: 1200
|
||||
|
||||
Temperature: 0.4
|
||||
Name: "SupportBot AI"
|
||||
|
||||
PastebinAPI_Key: "PASTEBIN_API_KEY"
|
||||
PastebinAPI_URL: "https://pastebin.com/api/api_post.php"
|
||||
|
||||
Style:
|
||||
MessageType: "text"
|
||||
# Available Styles for AI:
|
||||
# "embed" - AI responses will be sent as Discord embeds.
|
||||
# "text" - AI responses will be sent as plain messages.
|
||||
# "components_v2" - AI responses will be sent with the new components style.
|
||||
|
||||
Features:
|
||||
SuggestTickets: true # Should SupportBot AI suggest creating a ticket if the user needs more help?
|
||||
|
||||
Channels:
|
||||
AIChannel: "1469028791312715902"
|
||||
|
||||
Embed:
|
||||
Color: "#45b463"
|
||||
Footer: "SupportBot AI"
|
||||
|
||||
Memory:
|
||||
Enabled: true
|
||||
StoreFacts: true
|
||||
# StoreFacts - Enables saving important facts the AI learns.
|
||||
|
||||
StoreSummaries: true
|
||||
# StoreSummaries - Enables saving conversation summaries.
|
||||
|
||||
MaxRecentMessages: 15
|
||||
# MaxRecentMessages - Number of recent messages used for context.
|
||||
|
||||
Scope: "guild" # channel | guild
|
||||
# Available Scopes for Memory:
|
||||
# "channel" - Memory is per channel only.
|
||||
# "guild" - Memory is shared across the server.
|
||||
|
||||
CustomInstructions:
|
||||
- "You are SupportBot AI made by Emerald Services"
|
||||
- "You are built with DiscordJS/NodeJS and currently running on dev build 26.0 build 2"
|
||||
- "You're current build can be found here https://github.com/Emerald-Services/SupportBot/tree/26.0"
|
||||
- "You're main build can be found here https://builtbybit.com/resources/supportbot-free-advanced-ticket-bot.8940/ and Polymart at https://polymart.org/product/518/supportbot-1-discord-ticket-bot which is version 8.4"
|
||||
- "dev build 26.0 build 2 includes all-new AI features for SupportBot such as memory system that allows you to remember facts and summaries of conversations, which can be used to provide better responses."
|
||||
- "SupportBot AI also have a new tickets AI Mode which is enabled in supportbot.ymll, which allows you to assist users in support tickets and provide better responses based on the context of the ticket."
|
||||
- "Your main purpose is to assist users in the support server and provide helpful responses to their questions and issues. Always be accurate and if you do not have answer then simply ask the person to create a ticket if they need more help."
|
||||
#- "Add custom instructions here"
|
||||
|
||||
Messages:
|
||||
ErrorResponse: "I couldn't generate a response."
|
||||
AIError: "There was an error contacting the AI provider."
|
||||
AIDisabled: "AI is currently disabled."
|
||||
MessageTooLong: "My response was too long, so I uploaded it here: {pastebin}"
|
||||
SuggestTicketText: "-# Need more help? React with 🎫 to open a ticket."
|
||||
SuggestTicketReaction : "🎫"
|
||||
@@ -0,0 +1,372 @@
|
||||
# ___ _ ___ _
|
||||
# / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
# \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
# <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
# |_| |_|
|
||||
#
|
||||
# SupportBot created by Emerald Services
|
||||
# Installed with MIT License
|
||||
#
|
||||
# Discord Support: https://discord.gg/emeraldsrv
|
||||
# Website: https://emeraldsrv.dev
|
||||
#
|
||||
# SupportBot Configuration (supportbot.yml)
|
||||
|
||||
SupportBot_Version: "v26.1.1"
|
||||
|
||||
# -------------------------
|
||||
# General
|
||||
# -------------------------
|
||||
|
||||
General:
|
||||
Name: "SupportBot"
|
||||
Token: "BOT_TOKEN"
|
||||
|
||||
Addons:
|
||||
Enabled: true
|
||||
|
||||
# -------------------------
|
||||
# Activity
|
||||
# -------------------------
|
||||
|
||||
Activity:
|
||||
Status: "SupportBot v8"
|
||||
Type: "Competing"
|
||||
StreamingURL: "https://www.twitch.tv/YOUR_TWITCH_NAME"
|
||||
|
||||
# Available Types:
|
||||
# Playing
|
||||
# Watching
|
||||
# Listening
|
||||
# Competing
|
||||
# Streaming (URL required)
|
||||
|
||||
# You can also update the activity via Discord using: /settings
|
||||
|
||||
# -------------------------
|
||||
# Embeds
|
||||
# -------------------------
|
||||
|
||||
Embed:
|
||||
Colours:
|
||||
General: "#0cc559"
|
||||
Success: "#04b545"
|
||||
Error: "#d13030"
|
||||
Warn: "#fca117"
|
||||
|
||||
Footer: "SupportBot | Developed by Emerald Development"
|
||||
|
||||
# Use 0x<hexcode> to change the colour of the embeds.
|
||||
|
||||
# -------------------------
|
||||
# Roles
|
||||
# -------------------------
|
||||
|
||||
Roles:
|
||||
AutoRole:
|
||||
Enabled: true
|
||||
Role: "ROLE_ID"
|
||||
|
||||
StaffMember:
|
||||
Staff: "ROLE_ID"
|
||||
Admin: "ROLE_ID"
|
||||
Moderator: "ROLE_ID"
|
||||
|
||||
Mod:
|
||||
AllowSupportStaff: false
|
||||
|
||||
# Allow Support Staff to use the /mod command. (More in detail customisation in commands.yml)
|
||||
|
||||
# ----------------------------
|
||||
# System Messages
|
||||
# ----------------------------
|
||||
|
||||
Welcome:
|
||||
Enabled: true
|
||||
Channel: "CHANNEL_ID"
|
||||
|
||||
Leave:
|
||||
Enabled: true
|
||||
Channel: "CHANNEL_ID"
|
||||
|
||||
# ----------------------------
|
||||
# Suggestions
|
||||
# ----------------------------
|
||||
|
||||
Suggestions:
|
||||
Mode: "Channel" # Channel or Forum
|
||||
ForumChannel: "FORUM_CHANNEL_ID" # A forum channel, disabled if mode is set to Channel.
|
||||
Channel: "CHANNEL_ID" # A text channel, disabled if mode is set to Forum.
|
||||
|
||||
UpvoteEmoji: "✅"
|
||||
DownvoteEmoji: "❌"
|
||||
|
||||
UpvoteTitle: "Yes"
|
||||
DownvoteTitle: "No"
|
||||
|
||||
OwnSuggestion: true
|
||||
|
||||
# If false this will not allow the user to vote for a suggestion they created
|
||||
# If true this will allow the user to vote for a suggestion they created
|
||||
|
||||
ShowUsers: true
|
||||
|
||||
Threads:
|
||||
Enabled: true
|
||||
Title: "Suggestion-releated Thread"
|
||||
Reason: "A thread releted to this suggestion"
|
||||
|
||||
Buttons:
|
||||
Upvote: "2"
|
||||
Downvote: "2"
|
||||
RemoveVote: "4"
|
||||
RemoveVote_Title: "Remove Vote"
|
||||
|
||||
# Available Button Styles
|
||||
# 1 - Blurple
|
||||
# 2 - Grey
|
||||
# 3 - Green
|
||||
# 4 - Red
|
||||
|
||||
Tags:
|
||||
Created: "TAG_ID"
|
||||
Considering: "TAG_ID"
|
||||
Solved: "TAG_ID"
|
||||
Denied: "TAG_ID"
|
||||
|
||||
# -------------------------
|
||||
# Tickets
|
||||
# -------------------------
|
||||
|
||||
VoiceTickets:
|
||||
Name: "%username%'s VC"
|
||||
Category: "CATEGORY_ID"
|
||||
|
||||
Ticket:
|
||||
TicketType: "channels"
|
||||
|
||||
# Available TicketTypes:
|
||||
# channels - Tickets will be created as channels in the TicketChannelsCategory
|
||||
# threads - Tickets will be created as threads through the "TicketHome" channel.
|
||||
|
||||
UserManagement:
|
||||
DMOnAdd: true # DM the user when they are added to the ticket
|
||||
DMOnRemove: true # DM the user when they are removed from the ticket
|
||||
DMTranscript: true # DM the user a transcript of the ticket when it is closed
|
||||
|
||||
TicketHome: "1469028381638000725"
|
||||
|
||||
# What is TicketHome?
|
||||
# - Channel where the Ticket creation panel is sent.
|
||||
# - Channel where ticket threads are made. (only if ticket threads is enabled above.)
|
||||
|
||||
# For TicketType: channels
|
||||
TicketChannelsCategory: "CATEGORY_ID"
|
||||
TicketChannelsCategory2: "CATEGORY_ID" # This will be used if the first category has reached the max channel limit.
|
||||
TicketArchiveCategory: "CATEGORY_ID"
|
||||
# ---
|
||||
|
||||
Channel: "ticket-" # The prefix for ticket channel names
|
||||
TicketsPerUser: 100
|
||||
TicketReason: true
|
||||
# If ticket reason is set to false, It will not prompt to create a reason
|
||||
|
||||
TicketSubject: "description"
|
||||
|
||||
# Available TicketSubjects:
|
||||
# "description" will display the ticket reason within the channel description
|
||||
# "embed" will display the ticket reason within the ticket embed
|
||||
|
||||
Timeout: 5
|
||||
# Set to true to allow all staff to access the ticket
|
||||
|
||||
Close:
|
||||
StaffOnly: true
|
||||
# Set to false is anyone is able to close a ticket.
|
||||
|
||||
Invites: # Invites is for ticket threads.
|
||||
StaffOnly: true
|
||||
|
||||
ClaimTickets:
|
||||
Enabled: false
|
||||
Channel: "CHANNEL_ID"
|
||||
# Channel where the ticket assignments are sent for staff to claim.
|
||||
|
||||
ClaimAcceptTime: 120000
|
||||
# How long the assigned user has to accept the ticket before it gets re-assigned to someone else.
|
||||
# 120000 = 2 Minutes
|
||||
# 180000 = 3 Minutes
|
||||
# 240000 = 4 Minutes
|
||||
# 300000 = 5 Minutes
|
||||
# Time in Mliseconds
|
||||
|
||||
ButtonTitle: "Claim Ticket"
|
||||
ButtonEmoji: "🎫"
|
||||
Button: "1"
|
||||
|
||||
# Available Button Styles
|
||||
# 1 - Blurple
|
||||
# 2 - Grey
|
||||
# 3 - Green
|
||||
# 4 - Red
|
||||
|
||||
ReviewSystem:
|
||||
Enabled: false
|
||||
Channel: "CHANNEL_ID"
|
||||
UseModal: true
|
||||
|
||||
Questions: # Default questions asked when a ticket is created, these are used if departments are disabled.
|
||||
Enabled: false
|
||||
List:
|
||||
- "Please provide your account email?"
|
||||
- "What is the nature of your issue?"
|
||||
- "Have you tried resolving the issue yourself?"
|
||||
|
||||
Log:
|
||||
TicketDataLog: "CHANNEL_ID"
|
||||
TickeDataTitle: "Ticket Data"
|
||||
TicketBlacklistLog: "CHANNEL_ID"
|
||||
|
||||
AIMode:
|
||||
Enabled: true
|
||||
ThreadName: "Chat with SupportBot AI"
|
||||
WelcomeMessage: "Hi! I’m SupportBot AI. You can chat with me here about your issue."
|
||||
|
||||
# -------------------------
|
||||
# Ticket Departments
|
||||
# -------------------------
|
||||
|
||||
DepartmentSystem:
|
||||
Enabled: true
|
||||
Placeholder: "Choose a ticket department"
|
||||
DefaultDepartment: "general"
|
||||
|
||||
Departments:
|
||||
general:
|
||||
Name: "General Support"
|
||||
Description: "Open a general support ticket"
|
||||
Emoji: "🎫"
|
||||
Category: "CATEGORY_ID"
|
||||
Role: "ROLE_ID"
|
||||
ChannelPrefix: "support-"
|
||||
DefaultPriority: "normal"
|
||||
Questions:
|
||||
- "What do you need help with?"
|
||||
- "When did the issue start?"
|
||||
|
||||
purchase:
|
||||
Name: "Purchase Support"
|
||||
Description: "Get help with store purchases"
|
||||
Emoji: "💳"
|
||||
Category: "CATEGORY_ID"
|
||||
Role: "ROLE_ID"
|
||||
ChannelPrefix: "purchase-"
|
||||
DefaultPriority: "high"
|
||||
Questions:
|
||||
- "What is your order ID?"
|
||||
- "What product did you purchase?"
|
||||
- "What payment issue are you having?"
|
||||
|
||||
reports:
|
||||
Name: "Player Report"
|
||||
Description: "Report a player for breaking the rules"
|
||||
Emoji: "🚨"
|
||||
Category: "CATEGORY_ID"
|
||||
Role: "ROLE_ID"
|
||||
ChannelPrefix: "report-"
|
||||
DefaultPriority: "normal"
|
||||
Questions:
|
||||
- "Who are you reporting?"
|
||||
- "What happened?"
|
||||
- "Do you have evidence?"
|
||||
|
||||
appeals:
|
||||
Name: "Ban Appeals"
|
||||
Description: "Appeal a server punishment"
|
||||
Emoji: "⚖️"
|
||||
Category: "CATEGORY_ID"
|
||||
Role: "ROLE_ID"
|
||||
ChannelPrefix: "appeals-"
|
||||
DefaultPriority: "low"
|
||||
Questions:
|
||||
- "What punishment are you appealing?"
|
||||
- "Why should it be reviewed?"
|
||||
- "Anything else staff should know?"
|
||||
|
||||
PrioritySystem:
|
||||
Enabled: false
|
||||
DefaultPriority: "Normal"
|
||||
AllowUsersToChooseOnOpen: true
|
||||
Priorities:
|
||||
low:
|
||||
Name: "Low"
|
||||
Emoji: "🟢"
|
||||
normal:
|
||||
Name: "Normal"
|
||||
Emoji: "🟡"
|
||||
high:
|
||||
Name: "High"
|
||||
Emoji: "🟠"
|
||||
urgent:
|
||||
Name: "Urgent"
|
||||
Emoji: "🔴"
|
||||
|
||||
# -------------------------
|
||||
# Buttons
|
||||
# -------------------------
|
||||
Buttons:
|
||||
General:
|
||||
Delete: "🗑️"
|
||||
DeleteStyle: "4"
|
||||
|
||||
Voice:
|
||||
TicketDeleteText: "Delete Voice Channel"
|
||||
|
||||
Tickets:
|
||||
ClaimEmoji: "🧑💻"
|
||||
ClaimStyle: "1"
|
||||
|
||||
Unarchive: "Unarchive Ticket"
|
||||
Unarchive_Emoji: "♻️"
|
||||
Unarchive_Style: "2"
|
||||
|
||||
Unlock: "Unlock Ticket"
|
||||
Unlock_Emoji: "🔓"
|
||||
Unlock_Style: "2"
|
||||
# Available Button Styles
|
||||
# 1 - Blurple
|
||||
# 2 - Grey
|
||||
# 3 - Green
|
||||
# 4 - Red
|
||||
|
||||
# -------------------------
|
||||
# Select Menus
|
||||
# -------------------------
|
||||
|
||||
SelectMenus:
|
||||
Tickets:
|
||||
PanelEmoji: "⚙️"
|
||||
|
||||
CloseEmoji: "🗑️"
|
||||
ArchiveEmoji: "♻️"
|
||||
LockEmoji: "🔐"
|
||||
RenameEmoji: "🏷️"
|
||||
VCEmoji: "🔊"
|
||||
|
||||
EnableInvitesEmoji: "📤"
|
||||
DisableInvitesEmoji: "📥"
|
||||
|
||||
# -------------------------
|
||||
# Logging
|
||||
# -------------------------
|
||||
|
||||
MessageDelete:
|
||||
Channel: "CHANNEL_ID"
|
||||
Colour: "#d92525"
|
||||
|
||||
MessageUpdate:
|
||||
Channel: "CHANNEL_ID"
|
||||
Colour: "#f2a024"
|
||||
|
||||
Translate:
|
||||
TranslateLog: "CHANNEL_ID"
|
||||
@@ -0,0 +1,65 @@
|
||||
# ___ _ ___ _
|
||||
# / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
# \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
# <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
# |_| |_|
|
||||
#
|
||||
# SupportBot created by Emerald Services
|
||||
# Installed with MIT License
|
||||
#
|
||||
# Discord Support: https://discord.gg/emeraldsrv
|
||||
# Official Documentation: https://docs.emeraldsrv.com
|
||||
# Addons Marketplace: https://community.emeraldsrv.com
|
||||
#
|
||||
# Ticket Creation Panel Configuration (ticket-panel.yml)
|
||||
|
||||
# -------------------------------
|
||||
# Ticket Panel Configuration
|
||||
# -------------------------------
|
||||
|
||||
Panel: true
|
||||
|
||||
Style:
|
||||
Title: "## SupportBot Ticket Creation"
|
||||
Description: "Click on the button to file a `Ticket` and our team will try their best to assist you in the best way we can!"
|
||||
Image: "https://i.imgur.com/dejQvkg.png"
|
||||
Color: "#45b463"
|
||||
Layout: "4"
|
||||
|
||||
# Available Layout Styles
|
||||
# "1" - Style 1 - Title & Text, Button at the top -- Image at the bottom
|
||||
# "2" - Style 2 - Title & Text, Button at the bottom -- Image at the top
|
||||
# "3" - Style 3 - The classic look - Title & Text at the top -- Image in the middle -- Button at the bottom
|
||||
# "4" - Style 4 - Classic Embed (Title & Text, Image on right, Button at bottom)
|
||||
|
||||
Button:
|
||||
Text: "Create Ticket"
|
||||
Emoji: "🎫"
|
||||
Color: "2"
|
||||
CustomId: "createticket"
|
||||
|
||||
# Available Button Styles
|
||||
# 1 - Blurple
|
||||
# 2 - Grey
|
||||
# 3 - Red
|
||||
# 4 - Green
|
||||
|
||||
DepartmentMenu:
|
||||
CustomId: "ticketdepartmentselect"
|
||||
Placeholder: "Choose a ticket department"
|
||||
DefaultDescription: "Open a support ticket"
|
||||
DefaultEmoji: "🎫"
|
||||
|
||||
Settings:
|
||||
Image: true
|
||||
TopTitle: true
|
||||
TopDivider: true
|
||||
BottomTitle: false
|
||||
BottomDivider: false
|
||||
|
||||
Messages:
|
||||
NotConfigured: "Ticket Panel is not set up. Please configure it in `/Configs/ticket-panel.yml`."
|
||||
InvalidChannel: "TicketHome channel not found. Please check your config file."
|
||||
PanelSent: "Ticket panel message has been sent!"
|
||||
PanelSentWithDepartments: "Ticket panel message with department selection has been sent!"
|
||||
SendError: "An error occurred while sending the ticket panel message."
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"blacklistedUsers": []
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1,37 +0,0 @@
|
||||
# ___ _ ___ _
|
||||
# / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
# \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
# <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
# |_| |_|
|
||||
#
|
||||
# SupportBot created by Emerald Services
|
||||
# Installed with MIT License
|
||||
#
|
||||
# Discord Support: https:#emeraldsrv.dev/discord
|
||||
# Community Resources: https:#emeraldsrv.dev/resources
|
||||
|
||||
# -------------------------------
|
||||
# Commamnd Name Configuration
|
||||
# -------------------------------
|
||||
|
||||
TicketAdd: "ticketadd"
|
||||
TicketRemove: "ticketremove"
|
||||
OpenTicket: "ticket"
|
||||
CloseTicket: "close"
|
||||
InfoCommand: "info"
|
||||
PingCommand: "ping"
|
||||
HelpCommand: "help"
|
||||
|
||||
# ---------------------------------------
|
||||
# Commamnd Description Configuration
|
||||
# ---------------------------------------
|
||||
|
||||
TicketAddDesc: "Add a user to a support ticket."
|
||||
TicketRemoveDesc: "Remove a user from a support ticket."
|
||||
OpenTicketDesc: "Open a new support ticket."
|
||||
CloseTicketDesc: "Close your support ticket."
|
||||
InfoCommandDesc: "Get information about the brand."
|
||||
PingCommandDesc: "Pong!"
|
||||
HelpCommandDesc: "Get a list of all the commands."
|
||||
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
# ___ _ ___ _
|
||||
# / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
# \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
# <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
# |_| |_|
|
||||
#
|
||||
# SupportBot created by Emerald Services
|
||||
# Installed with MIT License
|
||||
#
|
||||
# Discord Support: https:#emeraldsrv.dev/discord
|
||||
# Community Resources: https:#emeraldsrv.dev/resources
|
||||
|
||||
SupportBot_Version: "7.2 pre-3"
|
||||
|
||||
# -------------------------
|
||||
# General Configuration
|
||||
# -------------------------
|
||||
|
||||
Name: "SupportBot"
|
||||
Prefix: "!"
|
||||
Token: "BOT_TOKEN"
|
||||
|
||||
# -------------------------
|
||||
# Activity Configuration
|
||||
# -------------------------
|
||||
|
||||
BotActivity: "Need Help? -ticket"
|
||||
|
||||
StreamingURL: "https://www.twitch.tv/YOUR_TWITCH_NAME"
|
||||
# Set The ActivityType to "STREAMING" for a streaming status!
|
||||
|
||||
ActivityType: "PLAYING"
|
||||
# Activity status can either be PLAYING, WATCHING, LISTENING or STREAMING.
|
||||
|
||||
# -------------------------
|
||||
# Embed Configuration
|
||||
# -------------------------
|
||||
|
||||
EmbedColour: "#f74343"
|
||||
EmbedFooter: "SupportBot | An Advanced Ticket System"
|
||||
|
||||
ErrorColour: "#d12519"
|
||||
SuccessColour: "#04b545"
|
||||
WarningColour: "#fca117"
|
||||
|
||||
# -------------------------
|
||||
# Information Configuration
|
||||
# -------------------------
|
||||
|
||||
InfoTitle: "Information"
|
||||
AboutMe: "Hi, I'm SupportBot an advanced discord ticket bot with 100% customisation! [Download](https://emeraldsrv.dev/download)"
|
||||
|
||||
InfoButtonText: "Visit Site"
|
||||
InfoURL: "https://emeraldsrv.dev"
|
||||
InfoColour: "#f74343"
|
||||
|
||||
# -------------------------
|
||||
# Help Configuration
|
||||
# -------------------------
|
||||
|
||||
HelpMenu: true # Do not change!
|
||||
SendHelpPage: "channel" # Set to channel or dm
|
||||
|
||||
# -------------------------
|
||||
# Role Configuration
|
||||
# -------------------------
|
||||
|
||||
AutoRole: true
|
||||
AutoRole_Role: "Member"
|
||||
LockdownRole: "@everyone"
|
||||
|
||||
Staff: "Support Team"
|
||||
Admin: "Project Developer"
|
||||
TicketBlackListRole: "Blacklisted"
|
||||
|
||||
# -------------------------
|
||||
# Tickets Configuration
|
||||
# -------------------------
|
||||
|
||||
TicketCategory: "▬▬ TICKETS ▬▬"
|
||||
TicketChannel: "ticket"
|
||||
|
||||
TicketLog: "ticket-log"
|
||||
TranscriptLog: "ticket-data"
|
||||
|
||||
TranscriptTitle: "Ticket Transcript"
|
||||
TicketLog_Title: "Ticket Log"
|
||||
TicketBlackListMessage: "You are not allowed to open a ticket"
|
||||
|
||||
TicketSubject: "description"
|
||||
# "description" will displays the ticket reason within the channel description
|
||||
# "embed" will displays the ticket reason within the ticket embed
|
||||
|
||||
AllowTicketMentions: true
|
||||
# Set to true to allow the ticket to mention the author and the support team.
|
||||
# Set to false to dis-allow mentions within tickets.
|
||||
|
||||
# --- Creation Config ---
|
||||
# --- Start ---
|
||||
|
||||
# Available Placeholders:
|
||||
|
||||
# %ticketusername% - User who created the ticket.
|
||||
# <@%ticketauthor%> - Tags the user who created the ticket.
|
||||
# <#%ticketid%> - Mentions the ticket channel.
|
||||
|
||||
Ticket_Title: "Server Support | %ticketusername%"
|
||||
TicketMessage: "Hello <@%ticketauthor%>, Thank you for creating a support ticket\nPlease wait patiently whilst a member of our team reaches out to you."
|
||||
|
||||
Ticket_Thumbnail: "https://images.emojiterra.com/google/android-pie/512px/1f39f.png"
|
||||
NoTicketSubject: "No Reason Provided!"
|
||||
|
||||
TicketCreatedAlert: ":ticket: Your support ticket has been created: <#%ticketid%>"
|
||||
|
||||
AddedUser: "👍 <@%user%> has been added to this ticket"
|
||||
RemovedUser: "👍 <@%user%> has been removed from this ticket"
|
||||
|
||||
|
||||
# --- Buttons Config ---
|
||||
# --- Start ---
|
||||
|
||||
# Discord Button Colour Selection
|
||||
# PRIMARY - Blurple
|
||||
# DANGER - Red
|
||||
# SUCCESS - Green
|
||||
# Secondary - Grey
|
||||
|
||||
TicketLockReaction: "🔒"
|
||||
TicketDeleteReaction: "⛔"
|
||||
LockTicketCategory: "Archive"
|
||||
|
||||
TicketCloseEmoji: "❌"
|
||||
TicketDeleteEmoji: "⛔"
|
||||
TicketLockEmoji: "🔒"
|
||||
|
||||
TicketCloseColour: "DANGER"
|
||||
TicketDeleteColour: "DANGER"
|
||||
TicketLockColour: "PRIMARY"
|
||||
|
||||
TicketDept1Colour: "PRIMARY"
|
||||
TicketDept2Colour: "PRIMARY"
|
||||
TicketDept3Colour: "PRIMARY"
|
||||
|
||||
TicketDept1Emoji: "1️⃣"
|
||||
TicketDept2Emoji: "2️⃣"
|
||||
TicketDept3Emoji: "3️⃣"
|
||||
|
||||
TranscriptSavedMessage: "📝 **Transcript Saved!**"
|
||||
TicketLockMessage: "❌ **Ticket Locked!**"
|
||||
TicketDeleteMessage: "⚠ **Ticket Deleting!**" # Tickets deleting after 5 seconds by default.
|
||||
TicketDeleteTime: 5000 # Time must be set in miliseconds.
|
||||
|
||||
# --- Departments Config ---
|
||||
# --- Start ---
|
||||
|
||||
TicketDepartments: true
|
||||
|
||||
AllowStaff: true
|
||||
# If set to false users with the "Staff" role will not be able to view tickets
|
||||
# without a valid department role set below.
|
||||
|
||||
# Set to false to allow "Staff" to see tickets whether its a department for them or not.
|
||||
|
||||
DepartmentTitle_1: "General Support"
|
||||
DepartmentTitle_2: "Billing Support"
|
||||
DepartmentTitle_3: "Admin Team"
|
||||
# Ticket department title, This is the title for a ticket department to help users know what is available.
|
||||
|
||||
DepartmentRole_1: "Support Team"
|
||||
DepartmentRole_2: "Support Team"
|
||||
DepartmentRole_3: "Project Developer"
|
||||
# Ticket roles are the roles that will be able to gain access to tickets depending on what department has been choosen.
|
||||
|
||||
# --- Closing Config ---
|
||||
# --- Start ---
|
||||
|
||||
ClosingTicket: ":warning: You have requested to close your support ticket."
|
||||
ClosingConfirmation_Word: "confirm"
|
||||
CloseConfirmation: false
|
||||
|
||||
# ---------------------------
|
||||
# Error / Warning Messages
|
||||
# ---------------------------
|
||||
|
||||
IncorrectPerms: ":x: **Err!** You do not have the correct permissions to use this command."
|
||||
InvalidChannel: ":x: **Err!** Channel not found. Please create it!"
|
||||
UserNotFound: ":x: **Err!** This user doesn't exist, Are they in this server?"
|
||||
NoValidTicket: ":warning: You cannot execute this command here."
|
||||
TicketExists: ":warning: This ticket cannot be opened, It already exists!"
|
||||
@@ -1 +0,0 @@
|
||||
TicketPanelID: '896035054235574362'
|
||||
@@ -1,42 +0,0 @@
|
||||
# ___ _ ___ _
|
||||
# / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
# \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
# <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
# |_| |_|
|
||||
#
|
||||
# SupportBot created by Emerald Services
|
||||
# Installed with MIT License
|
||||
#
|
||||
# Discord Support: https:#emeraldsrv.dev/discord
|
||||
# Community Resources: https:#emeraldsrv.dev/resources
|
||||
|
||||
# -------------------------------
|
||||
# Ticket Panel Configuration
|
||||
# -------------------------------
|
||||
|
||||
TicketPanel: true
|
||||
|
||||
# ----------------------------------------
|
||||
# Ticket Panel Message Configuration
|
||||
# ----------------------------------------
|
||||
|
||||
Channel: "create-ticket"
|
||||
ButtonEmoji: "📩"
|
||||
ButtonLabel: "Open Ticket"
|
||||
ButtonColour: "SUCCESS"
|
||||
# Colour Options:
|
||||
# -> PRIMARY - Blurple
|
||||
# -> SECONDARY - Grey
|
||||
# -> SUCCESS - Green
|
||||
# -> DANGER - Red
|
||||
|
||||
PanelTitle: "Need Help? Create a Support Ticket."
|
||||
|
||||
TicketPanel_Description: true
|
||||
TicketPanel_Thumbnail: false
|
||||
TicketPanel_Image: false
|
||||
|
||||
PanelMessage: "Click the button to open a new support ticket."
|
||||
PanelThumbnail: "https://i.imgur.com/ieeZejl.png"
|
||||
PanelImage: "https://i.imgur.com/5NkcmDq.png"
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Emerald Services | SupportBot
|
||||
// Claude integration for SupportBot AI
|
||||
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const axios = require("axios");
|
||||
|
||||
const supportbotai = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
|
||||
);
|
||||
|
||||
function extractTextFromMessage(message) {
|
||||
if (!message) return "";
|
||||
|
||||
if (typeof message === "string") {
|
||||
return message.trim();
|
||||
}
|
||||
|
||||
if (message.text) {
|
||||
return message.text.trim();
|
||||
}
|
||||
|
||||
if (Array.isArray(message)) {
|
||||
return message
|
||||
.map((part) => {
|
||||
if (typeof part === "string") return part;
|
||||
if (part?.type === "text" && typeof part.text === "string") {
|
||||
return part.text;
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
async function chat({ messages, temperature, maxTokens }) {
|
||||
const model = supportbotai.General.Model;
|
||||
const apiKey = supportbotai.General.Model_API_Key;
|
||||
|
||||
const systemMessages = messages.filter((m) => m.role === "system");
|
||||
const systemPrompt = systemMessages.map((m) => m.content).join("\n\n");
|
||||
|
||||
const userAssistantMessages = messages.filter((m) => m.role !== "system");
|
||||
|
||||
const response = await axios.post(
|
||||
"https://api.anthropic.com/v1/messages",
|
||||
{
|
||||
model,
|
||||
system: systemPrompt || undefined,
|
||||
messages: userAssistantMessages,
|
||||
temperature: temperature || supportbotai.General.Temperature || 0.4,
|
||||
max_tokens: maxTokens || supportbotai.General.Tokens || 800,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
"x-api-key": apiKey,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const data = response.data;
|
||||
const content = extractTextFromMessage(data.content);
|
||||
|
||||
if (!content) {
|
||||
console.error("Claude raw response:", JSON.stringify(data, null, 2));
|
||||
throw new Error(
|
||||
`Claude returned empty response. stop_reason=${data?.stop_reason || "unknown"}`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
raw: data,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
chat,
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
// Emerald Services | SupportBot
|
||||
// Groq integration for SupportBot AI
|
||||
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const OpenAI = require("openai");
|
||||
|
||||
const supportbotai = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
|
||||
);
|
||||
|
||||
const client = new OpenAI({
|
||||
apiKey: supportbotai.General.Model_API_Key,
|
||||
baseURL: "https://api.groq.com/openai/v1",
|
||||
});
|
||||
|
||||
function extractTextFromMessage(message) {
|
||||
if (!message) return "";
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message.content.trim();
|
||||
}
|
||||
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content
|
||||
.map((part) => {
|
||||
if (typeof part === "string") return part;
|
||||
if (part?.type === "text" && typeof part.text === "string") {
|
||||
return part.text;
|
||||
}
|
||||
if (typeof part?.text?.value === "string") {
|
||||
return part.text.value;
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
async function chat({ messages, temperature, maxTokens }) {
|
||||
const model = supportbotai.General.Model;
|
||||
|
||||
const response = await client.chat.completions.create({
|
||||
model,
|
||||
messages,
|
||||
temperature: temperature || supportbotai.General.Temperature || 0.4,
|
||||
max_tokens: maxTokens || supportbotai.General.Tokens || 800,
|
||||
});
|
||||
|
||||
const choice = response?.choices?.[0];
|
||||
const message = choice?.message;
|
||||
const content = extractTextFromMessage(message);
|
||||
|
||||
if (!content) {
|
||||
console.error("Groq raw response:", JSON.stringify(response, null, 2));
|
||||
throw new Error(
|
||||
`Groq returned empty response. finish_reason=${choice?.finish_reason || "unknown"}`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
raw: response,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
chat,
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
// Emerald Services | SupportBot
|
||||
// Open AI integration for SupportBot AI
|
||||
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const OpenAI = require("openai");
|
||||
|
||||
const supportbotai = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
|
||||
);
|
||||
|
||||
const client = new OpenAI({
|
||||
apiKey: supportbotai.General.Model_API_Key,
|
||||
});
|
||||
|
||||
function extractTextFromMessage(message) {
|
||||
if (!message) return "";
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message.content.trim();
|
||||
}
|
||||
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content
|
||||
.map((part) => {
|
||||
if (typeof part === "string") return part;
|
||||
if (part?.type === "text" && typeof part.text === "string")
|
||||
return part.text;
|
||||
if (typeof part?.text?.value === "string") return part.text.value;
|
||||
return "";
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
async function chat({ messages, temperature, maxTokens }) {
|
||||
const model = supportbotai.General.Model;
|
||||
|
||||
const response = await client.chat.completions.create({
|
||||
model,
|
||||
messages,
|
||||
temperature: temperature || supportbotai.General.Temperature || 0.4,
|
||||
max_completion_tokens: maxTokens || supportbotai.General.Tokens || 800,
|
||||
});
|
||||
|
||||
const choice = response?.choices?.[0];
|
||||
const message = choice?.message;
|
||||
const content = extractTextFromMessage(message);
|
||||
|
||||
if (!content) {
|
||||
console.error("OpenAI raw response:", JSON.stringify(response, null, 2));
|
||||
throw new Error(
|
||||
`OpenAI returned empty response. finish_reason=${choice?.finish_reason || "unknown"}`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
raw: response,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
chat,
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
const Event = require("../Structures/Event.js");
|
||||
module.exports = new Event("guildCreate", async (client) => {
|
||||
console.log(
|
||||
`\u001b[31m`,
|
||||
`${client.user.username} is not in the correct server set in your config. Please leave all other servers and restart the bot.`
|
||||
);
|
||||
console.log(`\u001b[31m`, `${client.user.username} will now exit.`);
|
||||
return process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
module.exports = new Event("guildDelete", async (client) => {
|
||||
console.log(
|
||||
`\u001b[31m`,
|
||||
`${client.user.username} is not in the correct server set in your config. Please join the server and restart the bot.`
|
||||
);
|
||||
console.log(`\u001b[31m`, `${client.user.username} will now exit.`);
|
||||
return process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
const {
|
||||
EmbedBuilder,
|
||||
ActionRowBuilder,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
MessageFlags,
|
||||
ContainerBuilder,
|
||||
TextDisplayBuilder,
|
||||
SectionBuilder,
|
||||
ThumbnailBuilder,
|
||||
MediaGalleryBuilder
|
||||
} = require("discord.js");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
const supportbot = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot.yml", "utf8")
|
||||
);
|
||||
const msgconfig = yaml.load(
|
||||
fs.readFileSync("./Configs/messages.yml", "utf8")
|
||||
);
|
||||
|
||||
function getWelcomeThumbnail(client, member, iconCfg) {
|
||||
switch ((iconCfg?.Mode || "").toUpperCase()) {
|
||||
case "USER":
|
||||
return member.user.displayAvatarURL();
|
||||
case "BOT":
|
||||
return client.user.displayAvatarURL();
|
||||
case "CUSTOM":
|
||||
return iconCfg.CustomURL;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildModernComponents(client, member) {
|
||||
const container = new ContainerBuilder();
|
||||
|
||||
if (msgconfig.Welcome.Modern.Colour) {
|
||||
container.setAccentColor(parseInt(msgconfig.Welcome.Modern.Colour.replace("#", ""), 16));
|
||||
}
|
||||
|
||||
const section = new SectionBuilder().addTextDisplayComponents(
|
||||
new TextDisplayBuilder().setContent(
|
||||
msgconfig.Welcome.Modern.Title.replace(/%joined_user%/g, member.user)
|
||||
),
|
||||
new TextDisplayBuilder().setContent(
|
||||
msgconfig.Welcome.Modern.Body.replace(/%joined_user%/g, member.user)
|
||||
)
|
||||
);
|
||||
|
||||
const thumbUrl = getWelcomeThumbnail(client, member, msgconfig.Welcome.Modern.Icon);
|
||||
if (thumbUrl) {
|
||||
section.setThumbnailAccessory(
|
||||
new ThumbnailBuilder()
|
||||
.setURL(thumbUrl)
|
||||
);
|
||||
}
|
||||
|
||||
container.addSectionComponents(section);
|
||||
|
||||
// FIXED: Using MediaGalleryBuilder instead of TextDisplayBuilder for images
|
||||
if (msgconfig.Welcome.Modern.Image?.Enabled && msgconfig.Welcome.Modern.Image.URL) {
|
||||
container.addMediaGalleryComponents(
|
||||
new MediaGalleryBuilder().addItems([
|
||||
{
|
||||
media: {
|
||||
url: msgconfig.Welcome.Modern.Image.URL
|
||||
}
|
||||
}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
if (Array.isArray(msgconfig.Welcome.Modern.Buttons)) {
|
||||
const row = new ActionRowBuilder();
|
||||
msgconfig.Welcome.Modern.Buttons.slice(0, 5).forEach(b => {
|
||||
const btn = new ButtonBuilder()
|
||||
.setLabel(b.label)
|
||||
.setStyle(ButtonStyle[b.style])
|
||||
.setEmoji(b.emoji || null);
|
||||
if (b.style === "Link") btn.setURL(b.url);
|
||||
else if (b.customId) btn.setCustomId(b.customId);
|
||||
row.addComponents(btn);
|
||||
});
|
||||
|
||||
container.addActionRowComponents(row);
|
||||
}
|
||||
|
||||
return [container];
|
||||
}
|
||||
|
||||
module.exports = new Event("guildMemberAdd", async (client, member) => {
|
||||
if (!supportbot.Welcome.Enabled) return;
|
||||
|
||||
const WelcomeChannel =
|
||||
member.guild.channels.cache.get(supportbot.Welcome.Channel) ||
|
||||
member.guild.channels.cache.find(c => c.name === supportbot.Welcome.Channel);
|
||||
if (!WelcomeChannel) return;
|
||||
|
||||
const style = (msgconfig.Welcome.LayoutStyle || "classic").toLowerCase();
|
||||
|
||||
if (style === "classic") {
|
||||
const WelcomeEmbed = new EmbedBuilder()
|
||||
.setColor(msgconfig.Welcome.Embed.Colour)
|
||||
.setTitle(msgconfig.Welcome.Embed.Title || null)
|
||||
.setDescription(
|
||||
msgconfig.Welcome.Embed.Message.replace(/%joined_user%/g, member.user)
|
||||
)
|
||||
.setTimestamp();
|
||||
|
||||
const thumb = getWelcomeThumbnail(client, member, msgconfig.Welcome.Embed.Icon);
|
||||
if (thumb) WelcomeEmbed.setThumbnail(thumb);
|
||||
|
||||
if (msgconfig.Welcome.Embed.Image?.Enabled && msgconfig.Welcome.Embed.Image.URL) {
|
||||
WelcomeEmbed.setImage(msgconfig.Welcome.Embed.Image.URL);
|
||||
}
|
||||
|
||||
const components = [];
|
||||
if (
|
||||
msgconfig.Welcome.Embed.Buttons?.Enabled &&
|
||||
Array.isArray(msgconfig.Welcome.Embed.Buttons.List)
|
||||
) {
|
||||
const row = new ActionRowBuilder();
|
||||
msgconfig.Welcome.Embed.Buttons.List.slice(0, 5).forEach(b => {
|
||||
const btn = new ButtonBuilder()
|
||||
.setLabel(b.label)
|
||||
.setStyle(ButtonStyle[b.style])
|
||||
.setEmoji(b.emoji || null);
|
||||
if (b.style === "Link") btn.setURL(b.url);
|
||||
else if (b.customId) btn.setCustomId(b.customId);
|
||||
row.addComponents(btn);
|
||||
});
|
||||
components.push(row);
|
||||
}
|
||||
|
||||
await WelcomeChannel.send({ embeds: [WelcomeEmbed], components });
|
||||
} else if (style === "modern") {
|
||||
const components = buildModernComponents(client, member);
|
||||
if (components.length > 0) {
|
||||
await WelcomeChannel.send({
|
||||
components,
|
||||
flags: MessageFlags.IsComponentsV2
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (supportbot.Roles.AutoRole.Enabled) {
|
||||
const role =
|
||||
member.guild.roles.cache.get(supportbot.Roles.AutoRole.Role) ||
|
||||
member.guild.roles.cache.find(r => r.name === supportbot.Roles.AutoRole.Role);
|
||||
if (role) await member.roles.add(role);
|
||||
}
|
||||
|
||||
console.log("\u001b[32m", "[+]", "\u001b[33m", `${member.user.username} joined the server!`);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
const { EmbedBuilder } = require("discord.js");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
module.exports = new Event("guildMemberRemove", async (client, member) => {
|
||||
|
||||
if (!supportbot.Leave || !supportbot.Leave.Enabled) return;
|
||||
|
||||
const leaveChannel =
|
||||
member.guild.channels.cache.get(supportbot.Leave.Channel) ||
|
||||
member.guild.channels.cache.find(c => c.name === supportbot.Leave.Channel);
|
||||
|
||||
if (!leaveChannel) return;
|
||||
|
||||
const leaveEmbed = new EmbedBuilder()
|
||||
.setColor(msgconfig.Leave.Embed.Colour)
|
||||
.setTitle(msgconfig.Leave.Embed.Title)
|
||||
.setDescription(
|
||||
msgconfig.Leave.Embed.Message.replace(/%left_user%/g, member.user.toString())
|
||||
)
|
||||
.setTimestamp();
|
||||
|
||||
if (msgconfig.Leave.Embed.Thumbnail === "BOT") {
|
||||
leaveEmbed.setThumbnail(client.user.displayAvatarURL());
|
||||
} else if (msgconfig.Leave.Embed.Thumbnail === "USER") {
|
||||
leaveEmbed.setThumbnail(member.user.displayAvatarURL());
|
||||
}
|
||||
|
||||
if (msgconfig.Leave.Embed.ImageEnabled) {
|
||||
leaveEmbed.setImage(msgconfig.Leave.Embed.ImageURL);
|
||||
}
|
||||
|
||||
await leaveChannel.send({ embeds: [leaveEmbed] });
|
||||
|
||||
console.log(`[-] ${member.user.tag} left the server`);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,584 @@
|
||||
const fs = require("fs");
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
const axios = require("axios");
|
||||
|
||||
const supportbotai = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
|
||||
);
|
||||
const supportbot = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot.yml", "utf8"),
|
||||
);
|
||||
|
||||
const Event = require("../Structures/Event.js");
|
||||
const AIDatabase = require("../Structures/AIDatabase.js");
|
||||
const db = require("../Structures/Database.js");
|
||||
|
||||
const openai = require("./Models/openai.js");
|
||||
const groq = require("./Models/groq.js");
|
||||
const claude = require("./Models/claude.js");
|
||||
|
||||
const PASTEBIN_API_KEY = supportbotai.General.PastebinAPI_Key;
|
||||
const PASTEBIN_API_URL = supportbotai.General.PastebinAPI_URL;
|
||||
|
||||
const CHANNELS = [supportbotai.Channels.AIChannel].filter(Boolean);
|
||||
|
||||
async function createPaste(content) {
|
||||
try {
|
||||
if (!PASTEBIN_API_KEY || !PASTEBIN_API_URL) return null;
|
||||
|
||||
const response = await axios.post(
|
||||
PASTEBIN_API_URL,
|
||||
new URLSearchParams({
|
||||
api_dev_key: PASTEBIN_API_KEY,
|
||||
api_option: "paste",
|
||||
api_paste_code: content,
|
||||
api_paste_private: 1,
|
||||
api_paste_expire_date: "1D",
|
||||
api_paste_format: "text",
|
||||
}),
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Pastebin Error:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getProvider() {
|
||||
const provider = String(
|
||||
supportbotai.General.Provider || "openai",
|
||||
).toLowerCase();
|
||||
|
||||
switch (provider) {
|
||||
case "openai":
|
||||
return openai;
|
||||
|
||||
case "groq":
|
||||
return groq;
|
||||
|
||||
case "claude":
|
||||
return claude;
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported AI provider: ${provider}`);
|
||||
}
|
||||
}
|
||||
|
||||
function formatTicketQuestionAnswers(questionAnswers) {
|
||||
if (!Array.isArray(questionAnswers) || questionAnswers.length === 0) {
|
||||
return "No ticket question answers were saved.";
|
||||
}
|
||||
|
||||
return questionAnswers
|
||||
.map((item, index) => {
|
||||
const question = item?.question || `Question ${index + 1}`;
|
||||
const answer = item?.answer || "No answer provided";
|
||||
return `${index + 1}. ${question}\nAnswer: ${answer}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
function buildTicketContext(ticket, message) {
|
||||
if (!ticket) return "";
|
||||
|
||||
return `
|
||||
Ticket Information:
|
||||
Ticket ID: ${ticket.ticket_id || ticket.id || "Unknown"}
|
||||
Subject: ${ticket.subject || ticket.reason || "No subject provided"}
|
||||
Department: ${ticket.department || "Not set"}
|
||||
Priority: ${ticket.priority || "Not set"}
|
||||
Created By: ${ticket.user_id || ticket.user || "Unknown"}
|
||||
Current User: ${message?.author?.tag || "Unknown"} (${message?.author?.id || "Unknown"})
|
||||
|
||||
Ticket Question Answers:
|
||||
${formatTicketQuestionAnswers(ticket.questionAnswers)}
|
||||
|
||||
Use this information when helping the user with their ticket.
|
||||
Do not invent missing ticket details.
|
||||
`;
|
||||
}
|
||||
|
||||
function buildSystemPrompt(message) {
|
||||
const sections = [];
|
||||
|
||||
if (Array.isArray(supportbotai.CustomInstructions)) {
|
||||
sections.push(...supportbotai.CustomInstructions);
|
||||
}
|
||||
|
||||
sections.push(
|
||||
`I am currently powered by the ${supportbotai.General.Provider || "Unknown"} provider, running the ${supportbotai.General.Model || "Unknown"} model.`,
|
||||
);
|
||||
sections.push(
|
||||
`The current guild is: ${message.guild?.name || "Unknown Guild"}`,
|
||||
);
|
||||
sections.push(
|
||||
`The current channel is: #${message.channel?.name || "unknown-channel"}`,
|
||||
);
|
||||
|
||||
return sections.join("\n- ").replace(/^/, "- ");
|
||||
}
|
||||
|
||||
function buildConversationFromMemory(currentMessage) {
|
||||
const memoryConfig = supportbotai.Memory || {};
|
||||
const memoryEnabled = memoryConfig.Enabled !== false;
|
||||
const maxRecentMessages = memoryConfig.MaxRecentMessages || 15;
|
||||
const memoryScope = String(memoryConfig.Scope || "guild").toLowerCase();
|
||||
|
||||
const conversation = [
|
||||
{
|
||||
role: "system",
|
||||
content: buildSystemPrompt(currentMessage),
|
||||
},
|
||||
];
|
||||
|
||||
if (!memoryEnabled) return conversation;
|
||||
|
||||
const recentMessages =
|
||||
typeof AIDatabase.getRecentMessagesByScope === "function"
|
||||
? AIDatabase.getRecentMessagesByScope({
|
||||
guildId: currentMessage.guild?.id || null,
|
||||
channelId: currentMessage.channel?.id || null,
|
||||
limit: maxRecentMessages,
|
||||
scope: memoryScope,
|
||||
})
|
||||
: AIDatabase.getRecentMessages(
|
||||
currentMessage.channel?.id,
|
||||
maxRecentMessages,
|
||||
);
|
||||
|
||||
const latestSummary =
|
||||
memoryConfig.StoreSummaries !== false
|
||||
? typeof AIDatabase.getLatestSummaryByScope === "function"
|
||||
? AIDatabase.getLatestSummaryByScope({
|
||||
guildId: currentMessage.guild?.id || null,
|
||||
channelId: currentMessage.channel?.id || null,
|
||||
scope: memoryScope,
|
||||
})
|
||||
: AIDatabase.getLatestSummary(currentMessage.channel?.id)
|
||||
: null;
|
||||
|
||||
const facts =
|
||||
memoryConfig.StoreFacts !== false
|
||||
? typeof AIDatabase.getFactsByScope === "function"
|
||||
? AIDatabase.getFactsByScope({
|
||||
guildId: currentMessage.guild?.id || null,
|
||||
channelId: currentMessage.channel?.id || null,
|
||||
scope: memoryScope,
|
||||
})
|
||||
: AIDatabase.getFacts(currentMessage.channel?.id)
|
||||
: [];
|
||||
|
||||
const userFacts =
|
||||
memoryConfig.StoreFacts !== false &&
|
||||
typeof AIDatabase.getUserFactsByScope === "function"
|
||||
? AIDatabase.getUserFactsByScope({
|
||||
guildId: currentMessage.guild?.id || null,
|
||||
userId: currentMessage.author?.id || null,
|
||||
scope: memoryScope,
|
||||
})
|
||||
: memoryConfig.StoreFacts !== false &&
|
||||
typeof AIDatabase.getUserFacts === "function"
|
||||
? AIDatabase.getUserFacts(
|
||||
currentMessage.guild?.id,
|
||||
currentMessage.author?.id,
|
||||
)
|
||||
: [];
|
||||
|
||||
const knowledgeBase = typeof AIDatabase.getKnowledge === "function"
|
||||
? AIDatabase.getKnowledge(25)
|
||||
: [];
|
||||
|
||||
if (latestSummary?.summary) {
|
||||
conversation.push({
|
||||
role: "system",
|
||||
content: `Shared memory summary (${memoryScope} scope):\n${latestSummary.summary}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (facts.length > 0) {
|
||||
const factText = facts
|
||||
.map(
|
||||
(fact) => `- [${fact.fact_type}] ${fact.fact_key}: ${fact.fact_value}`,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
conversation.push({
|
||||
role: "system",
|
||||
content: `Known shared facts (${memoryScope} scope):\n${factText}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (userFacts.length > 0) {
|
||||
const userFactText = userFacts
|
||||
.map(
|
||||
(fact) => `- [${fact.fact_type}] ${fact.fact_key}: ${fact.fact_value}`,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
conversation.push({
|
||||
role: "system",
|
||||
content: `Known facts about this user across chats:\n${userFactText}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (knowledgeBase.length > 0) {
|
||||
const knowledgeText = knowledgeBase
|
||||
.map((k) => `- ${k.content}`)
|
||||
.join("\n");
|
||||
|
||||
conversation.push({
|
||||
role: "system",
|
||||
content: `Server Knowledge Base (use this to answer questions):\n${knowledgeText}`,
|
||||
});
|
||||
}
|
||||
|
||||
for (const msg of recentMessages) {
|
||||
conversation.push({
|
||||
role: msg.role === "assistant" ? "assistant" : "user",
|
||||
content: msg.content,
|
||||
});
|
||||
}
|
||||
|
||||
return conversation;
|
||||
}
|
||||
|
||||
function getTicketContextForMessage(message) {
|
||||
if (!message?.channel) return null;
|
||||
|
||||
if (typeof db.getTicketByAIChannel === "function") {
|
||||
const aiTicket = db.getTicketByAIChannel(message.channel.id);
|
||||
if (aiTicket) return aiTicket;
|
||||
}
|
||||
|
||||
if (typeof db.getTicket === "function") {
|
||||
const directTicket = db.getTicket(message.channel.id);
|
||||
if (directTicket) return directTicket;
|
||||
}
|
||||
|
||||
if (message.channel.isThread() && typeof db.getTicket === "function") {
|
||||
const parentTicket = db.getTicket(message.channel.parentId);
|
||||
if (parentTicket) return parentTicket;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getAIMessageType() {
|
||||
return String(supportbotai.Style?.MessageType || "embed").toLowerCase();
|
||||
}
|
||||
|
||||
function shouldSuggestTicket(message, ticket) {
|
||||
if (supportbotai.Features?.SuggestTickets !== true) return false;
|
||||
if (ticket) return false;
|
||||
if (message.channel.isThread()) return false;
|
||||
return CHANNELS.includes(message.channel.id);
|
||||
}
|
||||
|
||||
function getSuggestTicketText() {
|
||||
return (
|
||||
supportbotai.Messages?.SuggestTicketText ||
|
||||
"-# Need more help? React with 🎫 to open a ticket."
|
||||
);
|
||||
}
|
||||
|
||||
async function sendAIResponse({
|
||||
client,
|
||||
message,
|
||||
replyContent,
|
||||
suggestTicket = false,
|
||||
}) {
|
||||
const messageType = getAIMessageType();
|
||||
const ticketHint = suggestTicket ? `\n\n${getSuggestTicketText()}` : "";
|
||||
|
||||
if (messageType === "text") {
|
||||
return message.reply({
|
||||
content: `${replyContent}${ticketHint}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (messageType === "components_v2") {
|
||||
const {
|
||||
ContainerBuilder,
|
||||
TextDisplayBuilder,
|
||||
SeparatorBuilder,
|
||||
MessageFlags,
|
||||
} = Discord;
|
||||
|
||||
const container = new ContainerBuilder();
|
||||
|
||||
if (supportbot.Embed?.Colours?.General) {
|
||||
container.setAccentColor(
|
||||
parseInt(String(supportbot.Embed.Colours.General).replace("#", ""), 16),
|
||||
);
|
||||
}
|
||||
|
||||
const title = new TextDisplayBuilder().setContent(
|
||||
`**${supportbotai.General?.Name || "SupportBot AI"}**`,
|
||||
);
|
||||
|
||||
const body = new TextDisplayBuilder().setContent(replyContent);
|
||||
|
||||
container.addTextDisplayComponents(title);
|
||||
container.addSeparatorComponents(new SeparatorBuilder().setDivider(true));
|
||||
container.addTextDisplayComponents(body);
|
||||
|
||||
if (suggestTicket) {
|
||||
container.addSeparatorComponents(new SeparatorBuilder().setDivider(true));
|
||||
container.addTextDisplayComponents(
|
||||
new TextDisplayBuilder().setContent(getSuggestTicketText()),
|
||||
);
|
||||
}
|
||||
|
||||
return message.reply({
|
||||
flags: MessageFlags.IsComponentsV2,
|
||||
components: [container],
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setAuthor({
|
||||
name: supportbotai.General.Name,
|
||||
iconURL: client.user.displayAvatarURL(),
|
||||
})
|
||||
.setDescription(`${replyContent}${ticketHint}`)
|
||||
.setColor(supportbotai.Embed.Color)
|
||||
.setFooter({
|
||||
text: supportbotai.Embed.Footer,
|
||||
iconURL: message.author.displayAvatarURL(),
|
||||
})
|
||||
.setTimestamp();
|
||||
|
||||
return message.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
function rememberUserFacts(message) {
|
||||
if (!message?.guild || !message?.author || !message?.content) return;
|
||||
|
||||
const content = message.content.trim();
|
||||
|
||||
const nameMatch = content.match(/^my name is\s+(.+)$/i);
|
||||
if (nameMatch && typeof AIDatabase.saveUserFact === "function") {
|
||||
AIDatabase.saveUserFact({
|
||||
guildId: message.guild.id,
|
||||
userId: message.author.id,
|
||||
factType: "profile",
|
||||
factKey: "name",
|
||||
factValue: nameMatch[1].trim(),
|
||||
});
|
||||
}
|
||||
|
||||
const nicknameMatch = content.match(/^i(?:'| a)?m\s+(.+)$/i);
|
||||
if (
|
||||
nicknameMatch &&
|
||||
nicknameMatch[1] &&
|
||||
nicknameMatch[1].length <= 32 &&
|
||||
typeof AIDatabase.saveUserFact === "function"
|
||||
) {
|
||||
AIDatabase.saveUserFact({
|
||||
guildId: message.guild.id,
|
||||
userId: message.author.id,
|
||||
factType: "profile",
|
||||
factKey: "display_name",
|
||||
factValue: nicknameMatch[1].trim(),
|
||||
});
|
||||
}
|
||||
|
||||
const usesMatch = content.match(/^i use\s+(.+)$/i);
|
||||
if (usesMatch && typeof AIDatabase.saveUserFact === "function") {
|
||||
AIDatabase.saveUserFact({
|
||||
guildId: message.guild.id,
|
||||
userId: message.author.id,
|
||||
factType: "preference",
|
||||
factKey: "uses",
|
||||
factValue: usesMatch[1].trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Event("messageCreate", async (client, message) => {
|
||||
if (message.author.bot || !message.guild) return;
|
||||
|
||||
let shouldRespond =
|
||||
CHANNELS.includes(message.channelId) ||
|
||||
message.mentions.users.has(client.user.id);
|
||||
|
||||
if (!shouldRespond && message.channel.isThread()) {
|
||||
let ticket = null;
|
||||
|
||||
if (typeof db.getTicketByAIChannel === "function") {
|
||||
ticket = db.getTicketByAIChannel(message.channel.id);
|
||||
}
|
||||
|
||||
if (!ticket && typeof db.getTicket === "function") {
|
||||
ticket = db.getTicket(message.channel.id);
|
||||
}
|
||||
|
||||
if (
|
||||
!ticket &&
|
||||
message.channel.parentId &&
|
||||
typeof db.getTicket === "function"
|
||||
) {
|
||||
ticket = db.getTicket(message.channel.parentId);
|
||||
}
|
||||
|
||||
if (
|
||||
ticket &&
|
||||
ticket.aiModeEnabled &&
|
||||
ticket.aiChannelId === message.channel.id
|
||||
) {
|
||||
shouldRespond = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldRespond) return;
|
||||
|
||||
if (!supportbotai.Enabled) {
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setAuthor({
|
||||
name: supportbotai.General.Name,
|
||||
iconURL: client.user.displayAvatarURL(),
|
||||
})
|
||||
.setDescription(
|
||||
supportbotai.Messages?.AIDisabled || "AI is currently disabled.",
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Error)
|
||||
.setFooter({
|
||||
text: supportbotai.Embed.Footer,
|
||||
iconURL: message.author.displayAvatarURL(),
|
||||
});
|
||||
|
||||
return message.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const typingInterval = setInterval(() => {
|
||||
message.channel.sendTyping().catch(() => { });
|
||||
}, 5000);
|
||||
|
||||
try {
|
||||
const memoryConfig = supportbotai.Memory || {};
|
||||
const memoryEnabled = memoryConfig.Enabled !== false;
|
||||
|
||||
if (memoryEnabled) {
|
||||
AIDatabase.addMessage({
|
||||
guildId: message.guild.id,
|
||||
channelId: message.channel.id,
|
||||
userId: message.author.id,
|
||||
role: "user",
|
||||
content: message.content,
|
||||
});
|
||||
|
||||
rememberUserFacts(message);
|
||||
}
|
||||
|
||||
const ticket = getTicketContextForMessage(message);
|
||||
|
||||
const conversation = buildConversationFromMemory(message);
|
||||
|
||||
if (ticket) {
|
||||
conversation.push({
|
||||
role: "system",
|
||||
content: buildTicketContext(ticket, message),
|
||||
});
|
||||
}
|
||||
|
||||
const provider = getProvider();
|
||||
|
||||
const response = await provider.chat({
|
||||
messages: conversation,
|
||||
temperature: supportbotai.General.Temperature || 0.4,
|
||||
maxTokens: supportbotai.General.Tokens || 800,
|
||||
});
|
||||
|
||||
clearInterval(typingInterval);
|
||||
|
||||
if (!response?.content) {
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(
|
||||
supportbotai.Messages?.ErrorResponse ||
|
||||
"I couldn't generate a response.",
|
||||
)
|
||||
.setColor(supportbotai.Embed.Color);
|
||||
|
||||
return message.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const replyContent = response.content;
|
||||
|
||||
if (memoryEnabled) {
|
||||
AIDatabase.addMessage({
|
||||
guildId: message.guild.id,
|
||||
channelId: message.channel.id,
|
||||
userId: client.user.id,
|
||||
role: "assistant",
|
||||
content: replyContent,
|
||||
});
|
||||
}
|
||||
|
||||
if (replyContent.length > 4000) {
|
||||
const pasteLink = await createPaste(replyContent);
|
||||
|
||||
if (pasteLink) {
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(
|
||||
(
|
||||
supportbotai.Messages?.MessageTooLong ||
|
||||
"My response was too long, so I uploaded it here: {pastebin}"
|
||||
).replace("{pastebin}", pasteLink),
|
||||
)
|
||||
.setColor(supportbotai.Embed.Color);
|
||||
|
||||
return message.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
return message.reply({
|
||||
content: replyContent.slice(0, 1900),
|
||||
});
|
||||
}
|
||||
|
||||
const suggestTicket = shouldSuggestTicket(message, ticket);
|
||||
|
||||
const sentMessage = await sendAIResponse({
|
||||
client,
|
||||
message,
|
||||
replyContent,
|
||||
suggestTicket: false,
|
||||
});
|
||||
|
||||
if (
|
||||
shouldSuggestTicket(message, ticket) &&
|
||||
supportbotai.Features?.SuggestTickets === true
|
||||
) {
|
||||
const hintMessage = await message.channel.send(
|
||||
supportbotai.Messages?.SuggestTicketText ||
|
||||
"Need more help? React with 🎫 to open a ticket.",
|
||||
);
|
||||
|
||||
await hintMessage
|
||||
.react(supportbotai.Messages?.SuggestTicketReaction || "🎫")
|
||||
.catch(() => { });
|
||||
|
||||
setTimeout(
|
||||
() => {
|
||||
hintMessage.delete().catch(() => { });
|
||||
},
|
||||
5 * 60 * 1000,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
clearInterval(typingInterval);
|
||||
|
||||
console.error("AI Error:", error);
|
||||
|
||||
const embed = new Discord.EmbedBuilder()
|
||||
.setDescription(
|
||||
supportbotai.Messages?.AIError ||
|
||||
supportbotai.Messages?.ErrorResponse ||
|
||||
"There was an error contacting the AI provider.",
|
||||
)
|
||||
.setColor(supportbot.Embed.Colours.Error);
|
||||
|
||||
message.reply({ embeds: [embed] }).catch(() => { });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
const { EmbedBuilder } = require('discord.js');
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
module.exports = new Event("messageDelete", async (client, message) => {
|
||||
if (!message.guild) return;
|
||||
|
||||
const author = message.author || (message.partial ? await message.fetch().then(m => m.author).catch(() => null) : null);
|
||||
if (!author || author.bot) return;
|
||||
|
||||
const content = message.content || (message.attachments.size > 0 ? "Contains attachment(s)" : "*No content*");
|
||||
|
||||
const deleteLogChannel = message.guild.channels.cache.get(supportbot.MessageDelete.Channel) ||
|
||||
message.guild.channels.cache.find(c => c.name === supportbot.MessageDelete.Channel);
|
||||
|
||||
const deletedMessageEmbed = new EmbedBuilder()
|
||||
.setColor(supportbot.MessageDelete.Colour)
|
||||
.setTitle("Message Deleted")
|
||||
.setDescription(`> **Channel:** <#${message.channel.id}>\n> **Message ID:** ${message.id}\n> **Message author:** ${author.tag} (${author.id})\n> **Message Created:** <t:${Math.floor(message.createdTimestamp / 1000)}:F>`)
|
||||
.addFields({ name: "Deleted Content", value: content, inline: false })
|
||||
.setThumbnail(author.displayAvatarURL())
|
||||
.setTimestamp();
|
||||
|
||||
if (message.attachments.size > 0) {
|
||||
const attachment = message.attachments.first();
|
||||
deletedMessageEmbed.addFields({ name: "Attachment", value: `[${attachment.name}](${attachment.proxyURL})` });
|
||||
}
|
||||
|
||||
if (deleteLogChannel) {
|
||||
deleteLogChannel.send({ embeds: [deletedMessageEmbed] });
|
||||
}
|
||||
});
|
||||
@@ -1,40 +1,75 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Ready Event
|
||||
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
const panelconfig = yaml.load(fs.readFileSync('./Data/ticket-panel.yml', 'utf8'));
|
||||
const supportbot = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot.yml", "utf8"),
|
||||
);
|
||||
const supportbotai = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
|
||||
);
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
module.exports = new Event("messageReactionAdd", async (client) => {
|
||||
module.exports = new Event(
|
||||
"messageReactionAdd",
|
||||
async (client, reaction, user) => {
|
||||
try {
|
||||
if (user.bot) return;
|
||||
|
||||
let message = {
|
||||
guild: reaction.message.channel.guild,
|
||||
author: user,
|
||||
content: "N/A",
|
||||
channel: reaction.message.channel
|
||||
if (reaction.partial) {
|
||||
await reaction.fetch().catch(() => null);
|
||||
}
|
||||
|
||||
const message = reaction.message;
|
||||
if (!message || !message.guild) return;
|
||||
|
||||
const reactionEmoji = reaction.emoji?.name || reaction.emoji?.id || null;
|
||||
const expectedReaction =
|
||||
supportbotai.Messages?.SuggestTicketReaction || "🎫";
|
||||
|
||||
if (reactionEmoji !== expectedReaction) return;
|
||||
if (supportbotai.Features?.SuggestTickets !== true) return;
|
||||
if (message.author?.id !== client.user.id) return;
|
||||
|
||||
const expectedText =
|
||||
supportbotai.Messages?.SuggestTicketText ||
|
||||
"Need more help? React with 🎫 to open a ticket.";
|
||||
|
||||
if ((message.content || "").trim() !== expectedText.trim()) return;
|
||||
|
||||
await message.delete().catch(() => {});
|
||||
|
||||
const cmd = client.commands.get(cmdconfig.OpenTicket.Command);
|
||||
if (!cmd) {
|
||||
console.error("Open ticket command not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
const member = await message.guild.members
|
||||
.fetch(user.id)
|
||||
.catch(() => null);
|
||||
|
||||
if (!member) return;
|
||||
|
||||
const fakeInteraction = {
|
||||
user,
|
||||
member,
|
||||
guild: message.guild,
|
||||
channel: message.channel,
|
||||
client,
|
||||
replied: true,
|
||||
deferred: false,
|
||||
reason: `Opened from AI suggestion in #${message.channel.name}`,
|
||||
options: {
|
||||
getString: () => null,
|
||||
},
|
||||
reply: async () => null,
|
||||
};
|
||||
|
||||
await cmd.run(fakeInteraction);
|
||||
} catch (error) {
|
||||
console.error("Error handling AI ticket reaction:", error);
|
||||
}
|
||||
|
||||
if (panelconfig.TicketPanel) {
|
||||
if (reaction.message.id === panelconfig.TicketPanelID) {
|
||||
if (reaction.emoji.name == panelconfig.ButtonEmoji || reaction.emoji.id == panelconfig.ButtonEmoji) {
|
||||
await reaction.users.remove(user.id)
|
||||
|
||||
try {
|
||||
const cmd = client.commands.get(cmdconfig.OpenTicket);
|
||||
if(!cmd) return;
|
||||
|
||||
cmd.run(message, message.content);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,57 @@
|
||||
const { EmbedBuilder } = require('discord.js');
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
// Load the configuration files
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
module.exports = new Event("messageUpdate", async (client, oldMessage, newMessage) => {
|
||||
|
||||
// Check if the message is from a guild and not from a bot
|
||||
if (!newMessage.guild || newMessage.author.bot) return;
|
||||
|
||||
// Fetch old message if it's not cached (important for message content)
|
||||
if (!oldMessage.content && oldMessage.partial) {
|
||||
try {
|
||||
oldMessage = await oldMessage.fetch();
|
||||
} catch (err) {
|
||||
console.error('Error fetching old message:', err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback if content is missing
|
||||
const oldMessageContent = oldMessage.content || (oldMessage.attachments.size > 0 ? 'Contains attachment(s)' : '*No content*');
|
||||
const newMessageContent = newMessage.content || (newMessage.attachments.size > 0 ? 'Contains attachment(s)' : '*No content*');
|
||||
|
||||
// Get the update log channel either by ID or by name
|
||||
const updateLogChannel = newMessage.guild.channels.cache.get(supportbot.MessageUpdate.Channel) ||
|
||||
newMessage.guild.channels.cache.find(channel => channel.name === supportbot.MessageUpdate.Channel);
|
||||
|
||||
// Create the embed for the updated message
|
||||
const updatedMessageEmbed = new EmbedBuilder()
|
||||
.setColor(supportbot.MessageUpdate.Colour)
|
||||
.setTitle("Message Updated")
|
||||
.setDescription(`> **Channel:** <#${newMessage.channel.id}>\n> **Message ID:** [${newMessage.id}](https://discord.com/channels/${newMessage.guild.id}/${newMessage.channel.id}/${newMessage.id})\n> **Message author:** ${newMessage.author.tag} (${newMessage.author.id})\n> **Message Created:** <t:${Math.floor(oldMessage.createdTimestamp / 1000)}:F>`)
|
||||
.addFields(
|
||||
{ name: 'Old Message', value: oldMessageContent, inline: false },
|
||||
{ name: 'New Message', value: newMessageContent, inline: false }
|
||||
)
|
||||
.setThumbnail(newMessage.author.displayAvatarURL())
|
||||
.setTimestamp();
|
||||
|
||||
// If the new message contains an attachment, add it to the embed
|
||||
if (newMessage.attachments.size > 0) {
|
||||
const attachment = newMessage.attachments.first();
|
||||
updatedMessageEmbed.addFields({ name: 'Attachment', value: `[${attachment.name}](${attachment.proxyURL})` });
|
||||
}
|
||||
|
||||
// Send the embed to the update log channel if the channel is found
|
||||
if (updateLogChannel) {
|
||||
updateLogChannel.send({
|
||||
embeds: [updatedMessageEmbed]
|
||||
});
|
||||
}
|
||||
});
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
const fs = require("fs");
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
// Load configs
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
|
||||
const ACTIVITY_TYPES = {
|
||||
PLAYING: Discord.ActivityType.Playing,
|
||||
WATCHING: Discord.ActivityType.Watching,
|
||||
LISTENING: Discord.ActivityType.Listening,
|
||||
COMPETING: Discord.ActivityType.Competing
|
||||
};
|
||||
|
||||
const setActivity = (client, type, status) => {
|
||||
const activityType = ACTIVITY_TYPES[type?.toUpperCase()];
|
||||
if (!activityType) return;
|
||||
|
||||
client.user.setPresence({
|
||||
activities: [{ name: status || "Online", type: activityType }],
|
||||
status: "online"
|
||||
});
|
||||
};
|
||||
|
||||
// simple colors
|
||||
const c = {
|
||||
reset: "\x1b[0m",
|
||||
gray: "\x1b[90m",
|
||||
green: "\x1b[32m",
|
||||
yellow: "\x1b[33m",
|
||||
cyan: "\x1b[36m",
|
||||
bold: "\x1b[1m"
|
||||
};
|
||||
|
||||
function line() {
|
||||
console.log(`${c.gray}────────────────────────────────────────────────────────${c.reset}`);
|
||||
}
|
||||
|
||||
function section(title) {
|
||||
console.log(`\n${c.green}${title}${c.reset}`);
|
||||
console.log(`${c.gray}${"-".repeat(title.length)}${c.reset}`);
|
||||
}
|
||||
|
||||
function info(label, value) {
|
||||
console.log(`${c.gray}${label.padEnd(14)}${c.reset} ${value}`);
|
||||
}
|
||||
|
||||
function status(label, ok, details = "") {
|
||||
const icon = ok ? `${c.green}✓${c.reset}` : `${c.yellow}!${c.reset}`;
|
||||
console.log(` ${icon} ${label}${details ? ` (${details})` : ""}`);
|
||||
}
|
||||
|
||||
const logStartup = async (client) => {
|
||||
console.clear();
|
||||
|
||||
const botName = supportbot?.General?.Name || "SupportBot";
|
||||
const botVersion = supportbot?.SupportBot_Version || "Unknown";
|
||||
|
||||
const inviteUrl = `https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=8&scope=bot%20applications.commands`;
|
||||
|
||||
line();
|
||||
console.log(`${c.bold}${c.green}SupportBot${c.reset}`);
|
||||
console.log(`${c.gray}Emerald Services${c.reset}`);
|
||||
line();
|
||||
|
||||
section("System");
|
||||
info("Bot Name", botName);
|
||||
info("Version", botVersion);
|
||||
info("Node.js", process.version);
|
||||
info("Discord.js", `v${Discord.version}`);
|
||||
info("Logged in as", client.user.tag);
|
||||
info("Guilds", `${client.guilds.cache.size}`);
|
||||
|
||||
section("Links");
|
||||
info("Docs", "https://emerald-services.gitbook.io/");
|
||||
info("Discord", "https://dsc.gg/emerald-dev");
|
||||
info("Invite", inviteUrl);
|
||||
|
||||
console.log("");
|
||||
};
|
||||
|
||||
const checkConfigs = async (client) => {
|
||||
const guild = client.guilds.cache.first();
|
||||
if (!guild) return;
|
||||
|
||||
section("Config Check");
|
||||
|
||||
const roles = [
|
||||
supportbot?.Roles?.StaffMember?.Admin,
|
||||
supportbot?.Roles?.StaffMember?.Staff,
|
||||
supportbot?.Roles?.AutoRole?.Role
|
||||
].filter(Boolean);
|
||||
|
||||
const channels = [
|
||||
supportbot?.Ticket?.TicketHome
|
||||
].filter(Boolean);
|
||||
|
||||
const [roleResults, channelResults] = await Promise.all([
|
||||
Promise.all(roles.map((role) => client.getRole(role, guild))),
|
||||
Promise.all(channels.map((channel) => client.getChannel(channel, guild)))
|
||||
]);
|
||||
|
||||
const missingRoles = roles.filter((_, i) => !roleResults[i]);
|
||||
const missingChannels = channels.filter((_, i) => !channelResults[i]);
|
||||
|
||||
if (!missingRoles.length && !missingChannels.length) {
|
||||
status("All configurations validated successfully", true);
|
||||
} else {
|
||||
if (missingRoles.length) {
|
||||
status("Missing roles", false, missingRoles.join(", "));
|
||||
}
|
||||
|
||||
if (missingChannels.length) {
|
||||
status("Missing channels", false, missingChannels.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
console.log("");
|
||||
};
|
||||
|
||||
module.exports = new Event("clientReady", async (client) => {
|
||||
setActivity(client, supportbot?.Activity?.Type, supportbot?.Activity?.Status);
|
||||
await logStartup(client);
|
||||
await checkConfigs(client);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 Tanner Nielsen
|
||||
Copyright (c) 2026 Emerald Services
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -0,0 +1,96 @@
|
||||
<h1 align="center">
|
||||
<br>
|
||||
<a href="https://github.com/Emerald-Services/SupportBot"><img src="https://i.imgur.com/cuadAYv.png"></a>
|
||||
<br>
|
||||
SupportBot
|
||||
<br>
|
||||
</h1>
|
||||
|
||||
<div align="center">
|
||||
|
||||
<a href="https://opensource.org/licenses/MIT">
|
||||
<img src="https://img.shields.io/badge/license-MIT-green?style=for-the-badge" alt="shield.png">
|
||||
</a>
|
||||
|
||||
<a href="https://github.com/discordjs">
|
||||
<img src="https://img.shields.io/badge/DISCORD.JS%20-%20v14-blue?style=for-the-badge" alt="shield.png">
|
||||
</a>
|
||||
|
||||
<a href="https://github.com/nodejs/node">
|
||||
<img src="https://img.shields.io/badge/NODE.JS%20-%20v20.x-green?style=for-the-badge" alt="shield.png">
|
||||
</a>
|
||||
|
||||
<a href="https://github.com/Emerald-Services/SupportBot/releases">
|
||||
<img src="https://img.shields.io/github/downloads/Emerald-Services/SupportBot/total?style=for-the-badge" alt="shield.png">
|
||||
</a>
|
||||
|
||||
## Supported Versions
|
||||
|
||||
| SupportBot | Node.JS | Discord.JS | Supported |
|
||||
|------------|---------|------------|------------|
|
||||
| 8.x | 22.x | 14.x. | ✅ Yes
|
||||
| 7.7.3 | 16.x | 13.x. | ❌ No
|
||||
| 7.x | 16.x | 13.x. | ❌ No
|
||||
| 6.x | 14.x | 13.x. | ❌ No
|
||||
| 5.x | 12.x | 13.x. | ❌ No
|
||||
| 4.x | 11.x | 13.x. | ❌ No
|
||||
| Older | 10.x | 13.x. | ❌ No
|
||||
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://emeraldsrv.com/">Website</a>
|
||||
•
|
||||
<a href="https://github.com/Emerald-Services/SupportBot/wiki">Wiki</a>
|
||||
<br>
|
||||
<a href="#about">About</a>
|
||||
•
|
||||
<a href="#support">Support</a>
|
||||
•
|
||||
<a href="#license">License</a>
|
||||
•
|
||||
<a href="https://github.com/Emerald-Services/SupportBot/wiki/Third-Party-Developer">Third-Party</a>
|
||||
•
|
||||
<a href="#contributors">Contributors</a>
|
||||
</p>
|
||||
|
||||
## About
|
||||
|
||||
SupportBot is an Open-Source discord bot built with [discord.js](https://github.com/discordjs/discord.js). It's primarily focused to help servers organise and manage their support system in a unique way with full customisation to match your brand.
|
||||
|
||||
## Support
|
||||
|
||||
<a href="https://emeraldsrv.com/discord">
|
||||
<img alt="Discord" src="https://img.shields.io/discord/597779408295821323?logo=discord&logoColor=white&style=for-the-badge">
|
||||
</a>
|
||||
|
||||
|
||||
## License
|
||||
|
||||
Released under the [MIT](https://opensource.org/licenses/MIT) license.
|
||||
|
||||
|
||||
## Third-Party
|
||||
|
||||
- [Official addons repository](https://github.com/Emerald-Services/Addons/)
|
||||
- [Syphers Addons](https://github.com/SypherRed/SB_Addons_Unofficial)
|
||||
- [BuiltByBit]([https://builtbybit.com/supportbot](https://builtbybit.com/resources/supportbot-advanced-ticket-bot.8940/))
|
||||
- [Polymart](https://polymart.org/resource/supportbot-1-discord-ticket-bot.518)
|
||||
|
||||
|
||||
## Contributors
|
||||
|
||||
<a href="https://github.com/Emerald-Services/SupportBot/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=Emerald-Services/SupportBot">
|
||||
</a>
|
||||
|
||||
## Hosting
|
||||
|
||||
You can use our [Pterodactyl egg](https://github.com/Emerald-Services/Pterodactyl-Egg) to host it on your own panel. We currently don't offer hosting for you, altough we might add this in the future.
|
||||
If you don't know how to install pterodactyl, you could always host it on replit:
|
||||
|
||||
[]([https://repl.it/github/ItsNyoty/iki](https://repl.it/github/Emerald-Services/SupportBot
|
||||
)
|
||||
|
||||
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Use this section to tell people about which versions of your project are
|
||||
currently being supported with security updates.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 7.7.2 | :white_check_mark: |
|
||||
| 7.7.1 | :white_check_mark: |
|
||||
| < 4.0 | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Use this section to tell people how to report a vulnerability.
|
||||
|
||||
Tell them where to go, how often they can expect to get an update on a
|
||||
reported vulnerability, what to expect if the vulnerability is accepted or
|
||||
declined, etc.
|
||||
@@ -0,0 +1,438 @@
|
||||
const Database = require("better-sqlite3");
|
||||
const path = require("path");
|
||||
|
||||
const db = new Database(path.join(__dirname, "../Data/ai-memory.db"));
|
||||
|
||||
db.pragma("journal_mode = WAL");
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS ai_conversations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT,
|
||||
channel_id TEXT,
|
||||
user_id TEXT,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS ai_summaries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT,
|
||||
channel_id TEXT,
|
||||
summary TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS ai_facts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT,
|
||||
channel_id TEXT,
|
||||
user_id TEXT,
|
||||
fact_type TEXT NOT NULL,
|
||||
fact_key TEXT NOT NULL,
|
||||
fact_value TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS ai_knowledge (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_type TEXT NOT NULL,
|
||||
source_name TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS ai_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT,
|
||||
channel_id TEXT,
|
||||
user_id TEXT,
|
||||
model TEXT,
|
||||
mode TEXT,
|
||||
last_message_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
try {
|
||||
db.prepare(`ALTER TABLE ai_facts ADD COLUMN user_id TEXT`).run();
|
||||
} catch (e) {
|
||||
if (!String(e).includes("duplicate column name")) throw e;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
saveUserFact({ guildId, userId, factType, factKey, factValue }) {
|
||||
const existing = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT id FROM ai_facts
|
||||
WHERE guild_id IS ? AND user_id IS ? AND fact_type = ? AND fact_key = ?
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(guildId || null, userId || null, factType, factKey);
|
||||
|
||||
if (existing) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE ai_facts
|
||||
SET fact_value = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
).run(factValue, Date.now(), existing.id);
|
||||
return;
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO ai_facts (
|
||||
guild_id, channel_id, user_id, fact_type, fact_key, fact_value, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
).run(
|
||||
guildId || null,
|
||||
null,
|
||||
userId || null,
|
||||
factType,
|
||||
factKey,
|
||||
factValue,
|
||||
Date.now(),
|
||||
Date.now(),
|
||||
);
|
||||
},
|
||||
|
||||
getUserFacts(guildId, userId) {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_facts
|
||||
WHERE guild_id IS ? AND user_id IS ?
|
||||
ORDER BY updated_at DESC
|
||||
`,
|
||||
)
|
||||
.all(guildId || null, userId || null);
|
||||
},
|
||||
|
||||
getUserFactsByScope({ guildId = null, userId = null, scope = "guild" }) {
|
||||
if (!userId) return [];
|
||||
|
||||
if (scope === "global") {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_facts
|
||||
WHERE user_id IS ?
|
||||
ORDER BY updated_at DESC
|
||||
`,
|
||||
)
|
||||
.all(userId || null);
|
||||
}
|
||||
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_facts
|
||||
WHERE guild_id IS ? AND user_id IS ?
|
||||
ORDER BY updated_at DESC
|
||||
`,
|
||||
)
|
||||
.all(guildId || null, userId || null);
|
||||
},
|
||||
|
||||
addMessage({ guildId, channelId, userId, role, content }) {
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO ai_conversations (
|
||||
guild_id, channel_id, user_id, role, content, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
).run(
|
||||
guildId || null,
|
||||
channelId || null,
|
||||
userId || null,
|
||||
role,
|
||||
content,
|
||||
Date.now(),
|
||||
);
|
||||
},
|
||||
|
||||
getRecentMessages(channelId, limit = 15) {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_conversations
|
||||
WHERE channel_id = ?
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ?
|
||||
`,
|
||||
)
|
||||
.all(channelId, limit)
|
||||
.reverse();
|
||||
},
|
||||
|
||||
getRecentMessagesByScope({ guildId = null, channelId = null, limit = 15, scope = "guild" }) {
|
||||
if (scope === "channel") {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_conversations
|
||||
WHERE channel_id = ?
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ?
|
||||
`,
|
||||
)
|
||||
.all(channelId || null, limit)
|
||||
.reverse();
|
||||
}
|
||||
|
||||
if (scope === "global") {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_conversations
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ?
|
||||
`,
|
||||
)
|
||||
.all(limit)
|
||||
.reverse();
|
||||
}
|
||||
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_conversations
|
||||
WHERE guild_id IS ?
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ?
|
||||
`,
|
||||
)
|
||||
.all(guildId || null, limit)
|
||||
.reverse();
|
||||
},
|
||||
|
||||
saveSummary({ guildId, channelId, summary }) {
|
||||
const existing = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT id FROM ai_summaries
|
||||
WHERE guild_id IS ? AND channel_id IS ?
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(guildId || null, channelId || null);
|
||||
|
||||
if (existing) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE ai_summaries
|
||||
SET summary = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
).run(summary, Date.now(), existing.id);
|
||||
return;
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO ai_summaries (
|
||||
guild_id, channel_id, summary, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?)
|
||||
`,
|
||||
).run(guildId || null, channelId || null, summary, Date.now(), Date.now());
|
||||
},
|
||||
|
||||
getLatestSummary(channelId) {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_summaries
|
||||
WHERE channel_id = ?
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(channelId);
|
||||
},
|
||||
|
||||
getLatestSummaryByScope({ guildId = null, channelId = null, scope = "guild" }) {
|
||||
if (scope === "channel") {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_summaries
|
||||
WHERE channel_id = ?
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(channelId || null);
|
||||
}
|
||||
|
||||
if (scope === "global") {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_summaries
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get();
|
||||
}
|
||||
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_summaries
|
||||
WHERE guild_id IS ?
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(guildId || null);
|
||||
},
|
||||
|
||||
saveFact({ guildId, channelId, factType, factKey, factValue }) {
|
||||
const existing = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT id FROM ai_facts
|
||||
WHERE guild_id IS ? AND channel_id IS ? AND fact_type = ? AND fact_key = ?
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(guildId || null, channelId || null, factType, factKey);
|
||||
|
||||
if (existing) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE ai_facts
|
||||
SET fact_value = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
).run(factValue, Date.now(), existing.id);
|
||||
return;
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO ai_facts (
|
||||
guild_id, channel_id, fact_type, fact_key, fact_value, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
).run(
|
||||
guildId || null,
|
||||
channelId || null,
|
||||
factType,
|
||||
factKey,
|
||||
factValue,
|
||||
Date.now(),
|
||||
Date.now(),
|
||||
);
|
||||
},
|
||||
|
||||
getFacts(channelId) {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_facts
|
||||
WHERE channel_id = ?
|
||||
ORDER BY updated_at DESC
|
||||
`,
|
||||
)
|
||||
.all(channelId);
|
||||
},
|
||||
|
||||
getFactsByScope({ guildId = null, channelId = null, scope = "guild" }) {
|
||||
if (scope === "channel") {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_facts
|
||||
WHERE channel_id = ? AND user_id IS NULL
|
||||
ORDER BY updated_at DESC
|
||||
`,
|
||||
)
|
||||
.all(channelId || null);
|
||||
}
|
||||
|
||||
if (scope === "global") {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_facts
|
||||
WHERE user_id IS NULL
|
||||
ORDER BY updated_at DESC
|
||||
`,
|
||||
)
|
||||
.all();
|
||||
}
|
||||
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_facts
|
||||
WHERE guild_id IS ? AND user_id IS NULL
|
||||
ORDER BY updated_at DESC
|
||||
`,
|
||||
)
|
||||
.all(guildId || null);
|
||||
},
|
||||
|
||||
addKnowledge({ sourceType, sourceName, title, content }) {
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO ai_knowledge (
|
||||
source_type, source_name, title, content, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
).run(sourceType, sourceName, title, content, Date.now(), Date.now());
|
||||
},
|
||||
|
||||
getKnowledge(limit = 25) {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ai_knowledge
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ?
|
||||
`,
|
||||
)
|
||||
.all(limit);
|
||||
},
|
||||
|
||||
clearKnowledge() {
|
||||
db.prepare(`DELETE FROM ai_knowledge`).run();
|
||||
},
|
||||
|
||||
clearConversations(channelId) {
|
||||
if (!channelId) return;
|
||||
db.prepare(`DELETE FROM ai_conversations WHERE channel_id = ?`).run(channelId);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
|
||||
// SupportBot | Emerald Services
|
||||
// Addon Structure
|
||||
class Command {
|
||||
constructor(options) {
|
||||
this.name = options.name;
|
||||
this.description = options.description;
|
||||
this.permissions = options.permissions;
|
||||
this.options = options.options || [];
|
||||
this.run = options.run;
|
||||
this.defaultPermission = true;
|
||||
}
|
||||
|
||||
// Method to dynamically update options
|
||||
setOptions(options) {
|
||||
this.options = options;
|
||||
}
|
||||
}
|
||||
|
||||
class Event {
|
||||
constructor(event, run) {
|
||||
this.event = event;
|
||||
this.run = run;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Command, Event };
|
||||
@@ -1,24 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Addon Structure
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
|
||||
function RunFunction(message, args, client) {}
|
||||
|
||||
class Addon {
|
||||
constructor(options) {
|
||||
this.name = options.name;
|
||||
this.description = options.description;
|
||||
this.permission = options.permission;
|
||||
this.type = ["BOTH", "SLASH", "TEXT"].includes(options.type) ? options.type : "TEXT";
|
||||
this.slashCommandOptions = options.slashCommandOptions || [];
|
||||
this.run = options.run;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Addon;
|
||||
+184
-96
@@ -1,103 +1,191 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Client Structure
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const path = require("path");
|
||||
const Discord = require("discord.js");
|
||||
const Command = require("./Command.js");
|
||||
const Event = require("./Event.js");
|
||||
const intents = new Discord.Intents(32767);
|
||||
const { GatewayIntentBits, Partials } = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
const { Command, Event } = require("./Addon.js");
|
||||
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
|
||||
|
||||
class Client extends Discord.Client {
|
||||
constructor() {
|
||||
super({ intents });
|
||||
const c = {
|
||||
reset: "\x1b[0m",
|
||||
gray: "\x1b[90m",
|
||||
green: "\x1b[32m",
|
||||
yellow: "\x1b[33m",
|
||||
cyan: "\x1b[36m",
|
||||
red: "\x1b[31m",
|
||||
white: "\x1b[37m",
|
||||
bold: "\x1b[1m",
|
||||
};
|
||||
|
||||
this.commands = new Discord.Collection();
|
||||
|
||||
this.prefix = supportbot.Prefix;
|
||||
}
|
||||
|
||||
start(token) {
|
||||
const commandFiles = fs.readdirSync("./Commands")
|
||||
.filter(file => file.endsWith(".js"));
|
||||
|
||||
const commands = commandFiles.map(file => require(`../Commands/${file}`));
|
||||
|
||||
console.log(`\u001b[34;1m`, '▬▬▬▬▬▬▬ Commands ▬▬▬▬▬▬▬')
|
||||
|
||||
commands.forEach(cmd => {
|
||||
console.log(`\u001b[31;1m`, `${cmd.name}`, `\u001b[32;1m`, 'Loaded');
|
||||
this.commands.set(cmd.name, cmd);
|
||||
});
|
||||
|
||||
console.log(`\u001b[34;1m`, '▬▬▬▬▬▬▬ Commands ▬▬▬▬▬▬▬')
|
||||
|
||||
// Addons
|
||||
|
||||
const addonFiles = fs.readdirSync("./Addons")
|
||||
.filter(file => file.endsWith(".js"));
|
||||
|
||||
const addons = addonFiles.map(file => require(`../Addons/${file}`));
|
||||
|
||||
console.log(' ')
|
||||
console.log(`\u001b[34;1m`, '▬▬▬▬▬▬▬ Addons ▬▬▬▬▬▬▬')
|
||||
|
||||
addons.forEach(addon => {
|
||||
console.log(`\u001b[31;1m`, `${addon.name}`, `\u001b[32;1m`, 'Loaded');
|
||||
this.commands.set(addon.name, addon);
|
||||
});
|
||||
|
||||
console.log(`\u001b[34;1m`, '▬▬▬▬▬▬▬ Addons ▬▬▬▬▬▬▬')
|
||||
console.log(' ')
|
||||
|
||||
// Slash Commands
|
||||
|
||||
const slashCommands = commands
|
||||
.filter(cmd => ["BOTH", "SLASH"].includes(cmd.type))
|
||||
.map(cmd => ({
|
||||
name: cmd.name.toLowerCase(),
|
||||
description: cmd.description,
|
||||
permissions: [],
|
||||
options: cmd.slashCommandOptions,
|
||||
defaultPermission: true
|
||||
}));
|
||||
|
||||
this.removeAllListeners();
|
||||
|
||||
this.on("ready", async () => {
|
||||
const cmds = await this.application.commands.set(slashCommands);
|
||||
|
||||
console.log(' ')
|
||||
console.log(`\u001b[34;1m`, '▬▬▬▬▬▬▬ Slash Command ▬▬▬▬▬▬▬'),
|
||||
console.log(' ')
|
||||
|
||||
cmds.forEach(cmd =>
|
||||
console.log(`Slash Command ${cmd.name} registered`),
|
||||
)
|
||||
|
||||
})
|
||||
|
||||
console.log(' ')
|
||||
console.log(`\u001b[34;1m`, '▬▬▬▬▬▬▬ Events ▬▬▬▬▬▬▬')
|
||||
|
||||
fs.readdirSync("./Events")
|
||||
.filter(file => file.endsWith(".js"))
|
||||
.forEach(file => {
|
||||
|
||||
const event = require(`../Events/${file}`);
|
||||
console.log(`\u001b[31;1m`, `${event.event}`, `\u001b[32;1m`, 'Loaded');
|
||||
|
||||
this.on(event.event, event.run.bind(null, this));
|
||||
});
|
||||
|
||||
console.log(`\u001b[34;1m`, '▬▬▬▬▬▬▬ Events ▬▬▬▬▬▬▬')
|
||||
console.log(' ')
|
||||
|
||||
this.login(token);
|
||||
}
|
||||
function line() {
|
||||
console.log(`${c.gray}────────────────────────────────────────────────────────${c.reset}`);
|
||||
}
|
||||
|
||||
module.exports = Client;
|
||||
function section(title) {
|
||||
console.log(`\n${c.green}${title}${c.reset}`);
|
||||
console.log(`${c.gray}${"-".repeat(title.length)}${c.reset}`);
|
||||
}
|
||||
|
||||
function walk(dir, ext = ".js", fileList = []) {
|
||||
const files = fs.readdirSync(dir);
|
||||
for (const file of files) {
|
||||
const full = `${dir}/${file}`;
|
||||
const stat = fs.statSync(full);
|
||||
if (stat.isDirectory()) {
|
||||
walk(full, ext, fileList);
|
||||
} else if (file.endsWith(ext)) {
|
||||
fileList.push(full);
|
||||
}
|
||||
}
|
||||
return fileList;
|
||||
}
|
||||
|
||||
class Client extends Discord.Client {
|
||||
constructor() {
|
||||
super({
|
||||
intents: [
|
||||
GatewayIntentBits.Guilds,
|
||||
GatewayIntentBits.GuildMembers,
|
||||
GatewayIntentBits.GuildMessages,
|
||||
GatewayIntentBits.GuildMessageReactions,
|
||||
GatewayIntentBits.MessageContent,
|
||||
],
|
||||
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
|
||||
});
|
||||
|
||||
this.commands = new Discord.Collection();
|
||||
}
|
||||
|
||||
async getChannel(channel, guild) {
|
||||
if (!channel) return null;
|
||||
const channelStr = String(channel).toLowerCase();
|
||||
return guild.channels.cache.find(
|
||||
(c) =>
|
||||
(c.type === Discord.ChannelType.GuildText || c.type === Discord.ChannelType.GuildNews) &&
|
||||
(c.id === channel || (c.name && c.name.toLowerCase() === channelStr)),
|
||||
);
|
||||
}
|
||||
|
||||
async getRole(role, guild) {
|
||||
if (!role) return null;
|
||||
const roleStr = String(role).toLowerCase();
|
||||
return guild.roles.cache.find(
|
||||
(r) => r.id === role || (r.name && r.name.toLowerCase() === roleStr),
|
||||
);
|
||||
}
|
||||
|
||||
async getCategory(category, guild) {
|
||||
if (!category) return null;
|
||||
const catStr = String(category).toLowerCase();
|
||||
return guild.channels.cache.find(
|
||||
(c) =>
|
||||
c.type === Discord.ChannelType.GuildCategory &&
|
||||
(c.id === category || (c.name && c.name.toLowerCase() === catStr)),
|
||||
);
|
||||
}
|
||||
|
||||
async start(token) {
|
||||
const commandFiles = walk("./Commands");
|
||||
|
||||
const allCommands = commandFiles.map((file) => ({
|
||||
file,
|
||||
command: require(`../${file}`),
|
||||
}));
|
||||
|
||||
const enabledCommands = allCommands.filter(({ command }) => {
|
||||
const matchingConfig = Object.values(cmdconfig).find(
|
||||
(entry) =>
|
||||
entry &&
|
||||
typeof entry === "object" &&
|
||||
entry.Command &&
|
||||
String(entry.Command).toLowerCase() === String(command.name).toLowerCase(),
|
||||
);
|
||||
|
||||
if (!matchingConfig) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return matchingConfig.Enabled !== false;
|
||||
});
|
||||
|
||||
section("Commands");
|
||||
|
||||
enabledCommands.forEach(({ command, file }) => {
|
||||
console.log(
|
||||
`${c.green}✓${c.reset} ${c.white}${command.name}${c.reset} ${c.gray}(${path.basename(file)})${c.reset}`,
|
||||
);
|
||||
this.commands.set(command.name, command);
|
||||
});
|
||||
|
||||
if (supportbot.General.Addons.Enabled) {
|
||||
const addonFiles = fs.readdirSync("./Addons").filter((file) => file.endsWith(".js"));
|
||||
|
||||
section("Addons");
|
||||
|
||||
addonFiles.forEach((file) => {
|
||||
let addon = require(`../Addons/${file}`);
|
||||
|
||||
// Handle single or multiple addons per file
|
||||
const addonArray = Array.isArray(addon) ? addon : [addon];
|
||||
|
||||
addonArray.forEach((item, index) => {
|
||||
// If name is missing, use filename (handling index for arrays)
|
||||
if (!item.name) {
|
||||
item.name = index === 0 ? file.split(".")[0] : `${file.split(".")[0]}_${index}`;
|
||||
}
|
||||
|
||||
console.log(`${c.green}✓${c.reset} ${c.white}${item.name}${c.reset}`);
|
||||
|
||||
if (item instanceof Command) {
|
||||
this.commands.set(item.name, item);
|
||||
}
|
||||
|
||||
if (item.events && Array.isArray(item.events)) {
|
||||
item.events.forEach((event) => {
|
||||
if (event instanceof Event) {
|
||||
this.on(event.event, (...args) => event.run(this, ...args));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// If it's a direct Event instance
|
||||
if (item instanceof Event) {
|
||||
this.on(item.event, (...args) => item.run(this, ...args));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
this.once("clientReady", async () => {
|
||||
await this.guilds.cache.first()?.commands.set(this.commands);
|
||||
|
||||
console.log(
|
||||
`\n${c.green}✓${c.reset} ${c.white}Slash Commands Registered${c.reset} ${c.gray}for ${this.guilds.cache.first().name}${c.reset}`,
|
||||
);
|
||||
});
|
||||
|
||||
section("Events");
|
||||
|
||||
fs.readdirSync("./Events")
|
||||
.filter((file) => file.endsWith(".js"))
|
||||
.forEach((file) => {
|
||||
const event = require(`../Events/${file}`);
|
||||
console.log(
|
||||
`${c.green}✓${c.reset} ${c.white}${event.event}${c.reset} ${c.gray}(${file})${c.reset}`,
|
||||
);
|
||||
this.on(event.event, (...args) => event.run(this, ...args));
|
||||
});
|
||||
|
||||
console.log("");
|
||||
|
||||
if (process.argv[2] !== "test") {
|
||||
await this.login(token);
|
||||
} else {
|
||||
console.log(`${c.red}RUNNING IN TEST MODE, IF NOT INTENDED, PLEASE USE npm start${c.reset}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Client;
|
||||
+9
-19
@@ -1,24 +1,14 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Command Structure
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
|
||||
function RunFunction(message, args, client) {}
|
||||
|
||||
class Command {
|
||||
constructor(options) {
|
||||
this.name = options.name;
|
||||
this.description = options.description;
|
||||
this.permission = options.permission;
|
||||
this.type = ["BOTH", "SLASH", "TEXT"].includes(options.type) ? options.type : "TEXT";
|
||||
this.slashCommandOptions = options.slashCommandOptions || [];
|
||||
this.run = options.run;
|
||||
}
|
||||
constructor(options) {
|
||||
this.name = options.name;
|
||||
this.description = options.description;
|
||||
this.permissions = options.permissions || [];
|
||||
this.options = options.options || [];
|
||||
this.run = options.run;
|
||||
this.defaultPermission = true;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Command;
|
||||
module.exports = Command;
|
||||
@@ -0,0 +1,474 @@
|
||||
// SupportBot | Emerald Services
|
||||
const Database = require("better-sqlite3");
|
||||
const path = require("path");
|
||||
|
||||
const db = new Database(path.join(__dirname, "../Data/supportbot.db"));
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS suggestions (
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
author_id TEXT,
|
||||
text TEXT,
|
||||
status TEXT DEFAULT 'Created'
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS profiles (
|
||||
user_id TEXT PRIMARY KEY,
|
||||
bio TEXT,
|
||||
timezone TEXT,
|
||||
clockedIn INTEGER DEFAULT 0
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS tickets (
|
||||
ticket_id TEXT PRIMARY KEY,
|
||||
user_id TEXT,
|
||||
status TEXT DEFAULT 'open',
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
subject TEXT,
|
||||
description TEXT
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
// Safe column upgrades
|
||||
const safeAlter = (sql) => {
|
||||
try {
|
||||
db.prepare(sql).run();
|
||||
} catch (e) {
|
||||
if (!String(e).includes("duplicate column name")) throw e;
|
||||
}
|
||||
};
|
||||
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN voiceChannelId TEXT`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN department TEXT DEFAULT 'general'`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN priority TEXT DEFAULT 'medium'`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN aiModeEnabled INTEGER DEFAULT 0`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN aiChannelId TEXT`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN aiType TEXT`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN aiEnabledBy TEXT`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN aiEnabledAt INTEGER`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN questionAnswers TEXT`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN ticketName TEXT`);
|
||||
safeAlter(`ALTER TABLE tickets ADD COLUMN ticketNumber TEXT`);
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS ticket_panel (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
message_id TEXT,
|
||||
channel_id TEXT,
|
||||
created_at INTEGER
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS ticket_users (
|
||||
ticket_id TEXT,
|
||||
user_id TEXT,
|
||||
PRIMARY KEY(ticket_id, user_id)
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
id INTEGER PRIMARY KEY,
|
||||
data TEXT
|
||||
)
|
||||
`,
|
||||
).run();
|
||||
|
||||
function ensureProfile(userId) {
|
||||
const existing = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT user_id FROM profiles WHERE user_id = ?
|
||||
`,
|
||||
)
|
||||
.get(userId);
|
||||
|
||||
if (!existing) {
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO profiles (user_id, bio, timezone, clockedIn)
|
||||
VALUES (?, '', '', 0)
|
||||
`,
|
||||
).run(userId);
|
||||
}
|
||||
}
|
||||
|
||||
function normaliseTicketRow(row) {
|
||||
if (!row) return null;
|
||||
|
||||
let questionAnswers = [];
|
||||
|
||||
if (row.questionAnswers) {
|
||||
try {
|
||||
questionAnswers = JSON.parse(row.questionAnswers);
|
||||
} catch {
|
||||
questionAnswers = [];
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...row,
|
||||
aiModeEnabled: Boolean(row.aiModeEnabled),
|
||||
clockedIn:
|
||||
row.clockedIn !== undefined ? Boolean(row.clockedIn) : row.clockedIn,
|
||||
questionAnswers,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
addTicket(ticket) {
|
||||
const now = Date.now();
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO tickets (
|
||||
ticket_id,
|
||||
user_id,
|
||||
subject,
|
||||
description,
|
||||
created_at,
|
||||
updated_at,
|
||||
department,
|
||||
priority,
|
||||
aiModeEnabled,
|
||||
aiChannelId,
|
||||
aiType,
|
||||
aiEnabledBy,
|
||||
aiEnabledAt,
|
||||
questionAnswers,
|
||||
ticketName,
|
||||
ticketNumber
|
||||
)
|
||||
VALUES (
|
||||
@ticket_id,
|
||||
@user_id,
|
||||
@subject,
|
||||
@description,
|
||||
@created_at,
|
||||
@updated_at,
|
||||
@department,
|
||||
@priority,
|
||||
@aiModeEnabled,
|
||||
@aiChannelId,
|
||||
@aiType,
|
||||
@aiEnabledBy,
|
||||
@aiEnabledAt,
|
||||
@questionAnswers,
|
||||
@ticketName,
|
||||
@ticketNumber
|
||||
)
|
||||
ON CONFLICT(ticket_id) DO NOTHING
|
||||
`,
|
||||
).run({
|
||||
ticket_id: ticket.id,
|
||||
user_id: ticket.user,
|
||||
subject: ticket.reason || "",
|
||||
description: ticket.description || "",
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
department: ticket.department || "general",
|
||||
priority: ticket.priority || "medium",
|
||||
aiModeEnabled: ticket.aiModeEnabled ? 1 : 0,
|
||||
aiChannelId: ticket.aiChannelId || null,
|
||||
aiType: ticket.aiType || null,
|
||||
aiEnabledBy: ticket.aiEnabledBy || null,
|
||||
aiEnabledAt: ticket.aiEnabledAt || null,
|
||||
questionAnswers: JSON.stringify(ticket.questionAnswers || []),
|
||||
ticketName: ticket.name || null,
|
||||
ticketNumber: ticket.number || null,
|
||||
});
|
||||
},
|
||||
|
||||
updateTicketQuestionAnswers(ticketId, questionAnswers = []) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET questionAnswers=@questionAnswers, updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
ticketId,
|
||||
questionAnswers: JSON.stringify(questionAnswers),
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
},
|
||||
|
||||
updateTicketVoice(ticketId, voiceChannelId) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET voiceChannelId=@voiceChannelId, updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
ticketId,
|
||||
voiceChannelId,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
},
|
||||
|
||||
updateTicketStatus(ticketId, status) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET status=@status, updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
status,
|
||||
updatedAt: Date.now(),
|
||||
ticketId,
|
||||
});
|
||||
},
|
||||
|
||||
updateTicketDepartment(ticketId, department) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET department=@department, updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
ticketId,
|
||||
department,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
},
|
||||
|
||||
updateTicketPriority(ticketId, priority) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET priority=@priority, updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
ticketId,
|
||||
priority,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
},
|
||||
|
||||
setTicketAIState(ticketId, aiState = {}) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET
|
||||
aiModeEnabled=@aiModeEnabled,
|
||||
aiChannelId=@aiChannelId,
|
||||
aiType=@aiType,
|
||||
aiEnabledBy=@aiEnabledBy,
|
||||
aiEnabledAt=@aiEnabledAt,
|
||||
updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
ticketId,
|
||||
aiModeEnabled: aiState.enabled ? 1 : 0,
|
||||
aiChannelId: aiState.aiChannelId || null,
|
||||
aiType: aiState.aiType || null,
|
||||
aiEnabledBy: aiState.enabledBy || null,
|
||||
aiEnabledAt: aiState.enabledAt
|
||||
? new Date(aiState.enabledAt).getTime()
|
||||
: aiState.enabled
|
||||
? Date.now()
|
||||
: null,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
},
|
||||
|
||||
enableTicketAI(
|
||||
ticketId,
|
||||
aiChannelId = null,
|
||||
aiType = null,
|
||||
enabledBy = null,
|
||||
) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET
|
||||
aiModeEnabled=1,
|
||||
aiChannelId=@aiChannelId,
|
||||
aiType=@aiType,
|
||||
aiEnabledBy=@aiEnabledBy,
|
||||
aiEnabledAt=@aiEnabledAt,
|
||||
updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
ticketId,
|
||||
aiChannelId,
|
||||
aiType,
|
||||
aiEnabledBy,
|
||||
aiEnabledAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
},
|
||||
|
||||
disableTicketAI(ticketId) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE tickets
|
||||
SET
|
||||
aiModeEnabled=0,
|
||||
updated_at=@updatedAt
|
||||
WHERE ticket_id=@ticketId
|
||||
`,
|
||||
).run({
|
||||
ticketId,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
},
|
||||
|
||||
getTicket(ticketId) {
|
||||
const row = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM tickets WHERE ticket_id=@ticketId
|
||||
`,
|
||||
)
|
||||
.get({ ticketId });
|
||||
|
||||
return normaliseTicketRow(row);
|
||||
},
|
||||
|
||||
getTicketByAIChannel(aiChannelId) {
|
||||
const row = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM tickets WHERE aiChannelId=@aiChannelId LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get({ aiChannelId });
|
||||
|
||||
return normaliseTicketRow(row);
|
||||
},
|
||||
|
||||
getAllTickets() {
|
||||
return db.prepare(`SELECT * FROM tickets`).all().map(normaliseTicketRow);
|
||||
},
|
||||
|
||||
saveTicketPanel(messageId, channelId) {
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO ticket_panel (message_id, channel_id, created_at)
|
||||
VALUES (@messageId, @channelId, @createdAt)
|
||||
`,
|
||||
).run({ messageId, channelId, createdAt: Date.now() });
|
||||
},
|
||||
|
||||
getTicketPanel() {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM ticket_panel ORDER BY id DESC LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get();
|
||||
},
|
||||
|
||||
addUserToTicket(ticketId, userId) {
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO ticket_users (ticket_id, user_id)
|
||||
VALUES (?, ?)
|
||||
ON CONFLICT(ticket_id, user_id) DO NOTHING
|
||||
`,
|
||||
).run(ticketId, userId);
|
||||
},
|
||||
|
||||
removeUserFromTicket(ticketId, userId) {
|
||||
db.prepare(
|
||||
`
|
||||
DELETE FROM ticket_users WHERE ticket_id=? AND user_id=?
|
||||
`,
|
||||
).run(ticketId, userId);
|
||||
},
|
||||
|
||||
getTicketUsers(ticketId) {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT user_id FROM ticket_users WHERE ticket_id=?
|
||||
`,
|
||||
)
|
||||
.all(ticketId)
|
||||
.map((r) => r.user_id);
|
||||
},
|
||||
|
||||
getSettings() {
|
||||
const row = db.prepare(`SELECT data FROM settings WHERE id=1`).get();
|
||||
if (!row) return {};
|
||||
try {
|
||||
return JSON.parse(row.data);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
},
|
||||
|
||||
getProfile(userId) {
|
||||
ensureProfile(userId);
|
||||
|
||||
const row = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT * FROM profiles WHERE user_id = ?
|
||||
`,
|
||||
)
|
||||
.get(userId);
|
||||
|
||||
if (!row) {
|
||||
return {
|
||||
user_id: userId,
|
||||
bio: "",
|
||||
timezone: "",
|
||||
clockedIn: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...row,
|
||||
clockedIn: Boolean(row.clockedIn),
|
||||
};
|
||||
},
|
||||
|
||||
setClockedIn(userId, clockedIn) {
|
||||
ensureProfile(userId);
|
||||
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE profiles
|
||||
SET clockedIn = ?
|
||||
WHERE user_id = ?
|
||||
`,
|
||||
).run(clockedIn ? 1 : 0, userId);
|
||||
},
|
||||
|
||||
saveSettings(obj) {
|
||||
const data = JSON.stringify(obj);
|
||||
db.prepare(
|
||||
`
|
||||
INSERT INTO settings (id, data)
|
||||
VALUES (1, @data)
|
||||
ON CONFLICT(id) DO UPDATE SET data = excluded.data
|
||||
`,
|
||||
).run({ data });
|
||||
},
|
||||
};
|
||||
+5
-15
@@ -1,21 +1,11 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Event Structure
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
|
||||
function RunFunction(client, ...eventArgs) {}
|
||||
|
||||
class Event {
|
||||
|
||||
constructor(event, runFunction) {
|
||||
this.event = event;
|
||||
this.run = runFunction;
|
||||
}
|
||||
constructor(event, run) {
|
||||
this.event = event;
|
||||
this.run = run;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Event;
|
||||
module.exports = Event;
|
||||
+23
-69
@@ -1,76 +1,30 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Ticket ID Structure
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const Command = require("./Command.js");
|
||||
const Client = require("./Client.js");
|
||||
const Event = require("./Event.js");
|
||||
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const db = require("./Database")
|
||||
|
||||
class TicketNumberID {
|
||||
|
||||
static pad(guildId) {
|
||||
let n = this.get(guildId) + '';
|
||||
let z = '0';
|
||||
let width = 4;
|
||||
setTimeout(() => {
|
||||
this.set(guildId, this.get(guildId) + 1);
|
||||
}, 50);
|
||||
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
|
||||
static async pad() {
|
||||
let num = await this.get()
|
||||
let n = num + ""
|
||||
await this.set(num + 1)
|
||||
return n.length >= 4 ? n : new Array(4 - n.length + 1).join("0") + n
|
||||
}
|
||||
|
||||
static async get() {
|
||||
const row = db.getTicketPanel()
|
||||
if (!row) return await this.set(0)
|
||||
return row.id
|
||||
}
|
||||
|
||||
static async set(value) {
|
||||
db.saveTicketPanel(`panel-${value}`, "none")
|
||||
return value
|
||||
}
|
||||
|
||||
static async reset() {
|
||||
return await this.set(0)
|
||||
}
|
||||
}
|
||||
|
||||
static get(guildId) {
|
||||
|
||||
let ticketnumberID = JSON.parse(fs.readFileSync("./Data/TicketData.json", "utf8"));
|
||||
|
||||
if (!ticketnumberID[guildId]) {
|
||||
ticketnumberID[guildId] = {
|
||||
id: 0
|
||||
}
|
||||
|
||||
fs.writeFileSync("./Data/TicketData.json", JSON.stringify(ticketnumberID, null, 4), err => {
|
||||
if (err) console.log(err);
|
||||
});
|
||||
|
||||
return 0;
|
||||
|
||||
|
||||
} else {
|
||||
return ticketnumberID[guildId].id;
|
||||
}
|
||||
}
|
||||
|
||||
static set(guildId, value) {
|
||||
let ticketnumberID = JSON.parse(fs.readFileSync("./Data/TicketData.json", "utf8"));
|
||||
|
||||
ticketnumberID[guildId] = {
|
||||
id: value
|
||||
}
|
||||
|
||||
fs.writeFileSync("./Data/TicketData.json", JSON.stringify(ticketnumberID, null, 4), err => {
|
||||
if (err) console.log(err);
|
||||
});
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
static reset(guildId) {
|
||||
let ticketnumberID = JSON.parse(fs.readFileSync("./Data/TicketData.json", "utf8"));
|
||||
|
||||
ticketnumberID[guildId] = {
|
||||
id: 0
|
||||
}
|
||||
|
||||
fs.writeFileSync("./Data/TicketData.json", JSON.stringify(ticketnumberID, null, 4), err => {
|
||||
if (err) console.log(err);
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TicketNumberID;
|
||||
module.exports = TicketNumberID
|
||||
@@ -0,0 +1,636 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require("js-yaml");
|
||||
const db = require("./Database.js");
|
||||
|
||||
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
|
||||
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
|
||||
|
||||
function escapeHtml(str = "") {
|
||||
return String(str)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function parseMarkdown(content = "") {
|
||||
let safe = escapeHtml(content);
|
||||
|
||||
safe = safe.replace(/```([\s\S]*?)```/g, "<pre><code>$1</code></pre>");
|
||||
safe = safe.replace(/`(.*?)`/g, "<code>$1</code>");
|
||||
safe = safe.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>");
|
||||
safe = safe.replace(/\*(.*?)\*/g, "<em>$1</em>");
|
||||
safe = safe.replace(/_(.*?)_/g, "<em>$1</em>");
|
||||
safe = safe.replace(
|
||||
/\[(.*?)\]\((.*?)\)/g,
|
||||
'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>',
|
||||
);
|
||||
|
||||
return safe.replace(/\n/g, "<br>");
|
||||
}
|
||||
|
||||
function formatDate(iso) {
|
||||
try {
|
||||
return new Date(iso).toLocaleString("en-GB", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
});
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
function getFileTypeInfo(att) {
|
||||
const fileName = String(att.name || "attachment").toLowerCase();
|
||||
|
||||
if (/\.(png|jpg|jpeg|gif|webp|bmp|svg)$/i.test(fileName)) {
|
||||
return "image";
|
||||
}
|
||||
|
||||
if (/\.(mp4|webm|mov|m4v)$/i.test(fileName)) {
|
||||
return "video";
|
||||
}
|
||||
|
||||
if (/\.(mp3|wav|ogg|m4a|flac)$/i.test(fileName)) {
|
||||
return "audio";
|
||||
}
|
||||
|
||||
return "file";
|
||||
}
|
||||
|
||||
function renderAttachment(att) {
|
||||
const url = escapeHtml(att.url || "");
|
||||
const name = escapeHtml(att.name || "attachment");
|
||||
const type = getFileTypeInfo(att);
|
||||
|
||||
if (type === "image") {
|
||||
return `
|
||||
<div class="attachment">
|
||||
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
|
||||
<div class="attachment-preview attachment-image">
|
||||
<img src="${url}" alt="${name}" loading="lazy">
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
if (type === "video") {
|
||||
return `
|
||||
<div class="attachment">
|
||||
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
|
||||
<div class="attachment-preview">
|
||||
<video controls preload="metadata">
|
||||
<source src="${url}">
|
||||
</video>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
if (type === "audio") {
|
||||
return `
|
||||
<div class="attachment">
|
||||
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
|
||||
<div class="attachment-preview">
|
||||
<audio controls preload="metadata">
|
||||
<source src="${url}">
|
||||
</audio>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="attachment">
|
||||
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderEmbeds(embeds = []) {
|
||||
return embeds
|
||||
.map((embed) => {
|
||||
const fields = (embed.fields || [])
|
||||
.map(
|
||||
(field) => `
|
||||
<div class="embed-field">
|
||||
<div class="embed-field-name">${escapeHtml(field.name || "Field")}</div>
|
||||
<div class="embed-field-value">${parseMarkdown(field.value || "")}</div>
|
||||
</div>
|
||||
`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
return `
|
||||
<div class="discord-embed">
|
||||
${embed.title ? `<div class="discord-embed-title">${escapeHtml(embed.title)}</div>` : ""}
|
||||
${embed.description ? `<div class="discord-embed-description">${parseMarkdown(embed.description)}</div>` : ""}
|
||||
${fields}
|
||||
</div>
|
||||
`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
function createTranscriptHTML(ticket, reason) {
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Transcript - ${escapeHtml(ticket.name)}</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0b0f14;
|
||||
--panel: #111821;
|
||||
--panel-2: #182230;
|
||||
--panel-3: #1d2938;
|
||||
--border: #283548;
|
||||
--text: #e6edf3;
|
||||
--muted: #9fb0c3;
|
||||
--accent: #22c55e;
|
||||
--accent-soft: rgba(34, 197, 94, 0.12);
|
||||
--code: #0f1720;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
padding: 32px 20px;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.header {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.header-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.title-wrap h1 {
|
||||
margin: 0;
|
||||
font-size: 1.8rem;
|
||||
line-height: 1.2;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.title-wrap p {
|
||||
margin: 8px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.98rem;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: var(--accent-soft);
|
||||
color: #8df0ad;
|
||||
border: 1px solid rgba(34, 197, 94, 0.25);
|
||||
padding: 8px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.meta-grid {
|
||||
margin-top: 18px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.meta-card {
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.meta-label {
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
margin-bottom: 6px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.meta-value {
|
||||
font-size: 0.98rem;
|
||||
font-weight: 600;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.messages-wrap {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.messages-header {
|
||||
padding: 18px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--panel-2);
|
||||
font-weight: 800;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.message {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
padding: 18px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.message:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
min-width: 42px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
background: var(--panel-3);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.message-body {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.message-header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.username {
|
||||
font-weight: 800;
|
||||
color: var(--text);
|
||||
font-size: 0.98rem;
|
||||
}
|
||||
|
||||
.userid {
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.content {
|
||||
color: var(--text);
|
||||
font-size: 0.96rem;
|
||||
line-height: 1.6;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.content:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.discord-embed {
|
||||
margin-top: 12px;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--border);
|
||||
border-left: 4px solid var(--accent);
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
}
|
||||
|
||||
.discord-embed-title {
|
||||
font-weight: 800;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.discord-embed-description {
|
||||
color: var(--text);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.embed-field {
|
||||
margin-top: 10px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid rgba(255,255,255,0.06);
|
||||
}
|
||||
|
||||
.embed-field-name {
|
||||
font-weight: 700;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.embed-field-value {
|
||||
color: var(--text);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.attachment {
|
||||
margin-top: 12px;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.attachment-file {
|
||||
display: inline-block;
|
||||
color: #8fd9a8;
|
||||
text-decoration: none;
|
||||
font-weight: 700;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.attachment-file:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.attachment-preview {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.attachment-preview img,
|
||||
.attachment-preview video {
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border);
|
||||
display: block;
|
||||
background: #0a0f15;
|
||||
}
|
||||
|
||||
.attachment-preview audio {
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
code {
|
||||
background: var(--code);
|
||||
border: 1px solid var(--border);
|
||||
padding: 2px 6px;
|
||||
border-radius: 6px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: var(--code);
|
||||
border: 1px solid var(--border);
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
overflow-x: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
pre code {
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #8fd9ff;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 24px 20px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
body {
|
||||
padding: 18px 12px;
|
||||
}
|
||||
|
||||
.header,
|
||||
.messages-wrap {
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
width: 100%;
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<section class="header">
|
||||
<div class="header-top">
|
||||
<div class="title-wrap">
|
||||
<h1>Ticket Transcript</h1>
|
||||
<p>Exported conversation log for support ticket <strong>${escapeHtml(ticket.name)}</strong></p>
|
||||
</div>
|
||||
<div class="badge">Closed Transcript</div>
|
||||
</div>
|
||||
|
||||
<div class="meta-grid">
|
||||
<div class="meta-card">
|
||||
<div class="meta-label">Channel</div>
|
||||
<div class="meta-value">${escapeHtml(ticket.name)}</div>
|
||||
</div>
|
||||
<div class="meta-card">
|
||||
<div class="meta-label">Ticket ID</div>
|
||||
<div class="meta-value">${escapeHtml(ticket.id)}</div>
|
||||
</div>
|
||||
<div class="meta-card">
|
||||
<div class="meta-label">Message Count</div>
|
||||
<div class="meta-value">${ticket.messages.length}</div>
|
||||
</div>
|
||||
<div class="meta-card">
|
||||
<div class="meta-label">Close Reason</div>
|
||||
<div class="meta-value">${escapeHtml(reason || "No Reason Provided.")}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="messages-wrap">
|
||||
<div class="messages-header">Messages</div>
|
||||
${
|
||||
ticket.messages.length
|
||||
? ticket.messages
|
||||
.map(
|
||||
(msg) => `
|
||||
<article class="message">
|
||||
<img src="${escapeHtml(msg.avatar || "")}" alt="Avatar" class="avatar">
|
||||
<div class="message-body">
|
||||
<div class="message-header">
|
||||
<span class="username">${escapeHtml(msg.username || "Unknown User")}</span>
|
||||
<span class="userid">${escapeHtml(msg.userId || "Unknown ID")}</span>
|
||||
<span class="timestamp">${formatDate(msg.timestamp)}</span>
|
||||
</div>
|
||||
|
||||
<div class="content">${parseMarkdown(msg.content || "")}</div>
|
||||
|
||||
${renderEmbeds(msg.embeds || [])}
|
||||
${(msg.attachments || []).map(renderAttachment).join("")}
|
||||
</div>
|
||||
</article>
|
||||
`,
|
||||
)
|
||||
.join("")
|
||||
: `<div class="empty-state">No messages were found in this ticket.</div>`
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
async function createTranscript(interaction, ticket, reason) {
|
||||
const { getChannel } = interaction.client;
|
||||
|
||||
const transcriptChannel = await getChannel(
|
||||
supportbot.Ticket.Log.TicketDataLog,
|
||||
interaction.guild,
|
||||
);
|
||||
|
||||
if (!transcriptChannel) {
|
||||
throw new Error("Transcript log channel missing or inaccessible.");
|
||||
}
|
||||
|
||||
let allMessages = [];
|
||||
let lastId = null;
|
||||
|
||||
while (true) {
|
||||
const options = { limit: 100 };
|
||||
if (lastId) options.before = lastId;
|
||||
|
||||
const messages = await interaction.channel.messages.fetch(options);
|
||||
if (messages.size === 0) break;
|
||||
|
||||
allMessages = [...allMessages, ...messages.values()];
|
||||
lastId = messages.last().id;
|
||||
|
||||
if (messages.size < 100) break;
|
||||
}
|
||||
|
||||
allMessages.sort((a, b) => a.createdTimestamp - b.createdTimestamp);
|
||||
|
||||
const transcriptData = allMessages.map((msg) => ({
|
||||
content: msg.content || "",
|
||||
username: msg.author.username,
|
||||
userId: msg.author.id,
|
||||
avatar: msg.author.displayAvatarURL({ extension: "png", size: 128 }),
|
||||
timestamp: msg.createdAt.toISOString(),
|
||||
attachments: Array.from(msg.attachments.values()).map((att) => ({
|
||||
url: att.url,
|
||||
name: att.name || "attachment",
|
||||
contentType: att.contentType || null,
|
||||
size: att.size || 0,
|
||||
})),
|
||||
embeds: msg.embeds.map((embed) => ({
|
||||
title: embed.title || "",
|
||||
description: embed.description || "",
|
||||
fields: embed.fields || [],
|
||||
})),
|
||||
}));
|
||||
|
||||
if (typeof db.updateTicketStatus === "function") {
|
||||
db.updateTicketStatus(interaction.channel.id, "closed");
|
||||
}
|
||||
|
||||
const ticketUserId = ticket.user_id || ticket.user;
|
||||
const tUser =
|
||||
interaction.client.users.cache.get(ticketUserId) ||
|
||||
(ticketUserId
|
||||
? await interaction.client.users.fetch(ticketUserId).catch(() => null)
|
||||
: null);
|
||||
|
||||
const transcriptEmbed = new Discord.EmbedBuilder()
|
||||
.setTitle(msgconfig.TicketLog.Title)
|
||||
.setColor(msgconfig.TicketLog.Colour)
|
||||
.setFooter({
|
||||
text: supportbot.Embed.Footer,
|
||||
iconURL: interaction.user.displayAvatarURL(),
|
||||
})
|
||||
.setDescription(
|
||||
`> **Ticket:** ${interaction.channel.name} (\`${interaction.channel.id}\`)\n` +
|
||||
`> **User:** ${tUser?.tag || "Unknown User"} (\`${tUser?.id || ticketUserId || "Unknown"}\`)\n` +
|
||||
`> **Closed by:** <@${interaction.user.id}>\n` +
|
||||
`> **Message Count:** ${transcriptData.length}`,
|
||||
)
|
||||
.addFields({
|
||||
name: "Reason",
|
||||
value: `\`\`\`${reason || "No Reason Provided."}\`\`\``,
|
||||
inline: false,
|
||||
});
|
||||
|
||||
const transcriptDir = path.join(process.cwd(), "./Data/Transcripts");
|
||||
if (!fs.existsSync(transcriptDir)) {
|
||||
fs.mkdirSync(transcriptDir, { recursive: true });
|
||||
}
|
||||
|
||||
const htmlFileName = `${interaction.channel.id}-transcript.html`;
|
||||
const htmlPath = path.join(transcriptDir, htmlFileName);
|
||||
|
||||
const html = createTranscriptHTML(
|
||||
{
|
||||
id: interaction.channel.id,
|
||||
name: interaction.channel.name,
|
||||
messages: transcriptData,
|
||||
},
|
||||
reason,
|
||||
);
|
||||
|
||||
fs.writeFileSync(htmlPath, html, "utf8");
|
||||
|
||||
await transcriptChannel.send({
|
||||
embeds: [transcriptEmbed],
|
||||
files: [
|
||||
new Discord.AttachmentBuilder(htmlPath, {
|
||||
name: `SPOILER_${htmlFileName}`,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
return { htmlPath };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createTranscript,
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Ping Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.PingCommand,
|
||||
description: cmdconfig.PingCommandDesc,
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
const PingEmbed = new Discord.MessageEmbed()
|
||||
.setDescription(`:ping_pong: **Ping:** \`${client.ws.ping} ms\``)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
|
||||
message.channel.send({
|
||||
embeds: [PingEmbed]
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,245 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Ticket Command
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Command = require("../Structures/Command.js");
|
||||
const TicketNumberID = require('../Structures/TicketID.js');
|
||||
|
||||
async function asyncForEach(array, callback) {
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
await callback(array[index], index, array);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Command({
|
||||
name: cmdconfig.OpenTicket,
|
||||
description: cmdconfig.OpenTicketDesc,
|
||||
type: "BOTH",
|
||||
slashCommandOptions: [],
|
||||
permission: "SEND_MESSAGES",
|
||||
|
||||
async run(message, args, client) {
|
||||
|
||||
let reactionUser = message.guild.members.cache.get(message.author.id)
|
||||
|
||||
if (reactionUser.roles.cache.find(role => role.name === supportbot.TicketBlackListRole) || reactionUser.roles.cache.find(role => role.id === supportbot.TicketBlackListRole)) {
|
||||
return message.channel.send({content:`<@${message.author.id}> ${supportbot.TicketBlackListMessage}`}).then(msg => {
|
||||
setTimeout(() => msg.delete(), 3500)
|
||||
})
|
||||
}
|
||||
|
||||
// Ticket ID
|
||||
let ticketNumberID = TicketNumberID.pad(message.guild.id);
|
||||
|
||||
// Ticket Subject
|
||||
const TicketSubject = args || supportbot.NoTicketSubject;
|
||||
|
||||
const TicketExists = new Discord.MessageEmbed()
|
||||
.setTitle("Ticket Exists!")
|
||||
.setDescription(`${supportbot.TicketExists}`)
|
||||
.setColor(supportbot.WarningColour)
|
||||
|
||||
if (message.guild.channels.cache.find(ticketChannel => ticketChannel.name === `${supportbot.TicketChannel}-${ticketNumberID}`)) {
|
||||
return message.channel.send({ embeds: [TicketExists] });
|
||||
}
|
||||
const Staff = message.guild.roles.cache.find(SupportTeam => SupportTeam.name === supportbot.Staff) || message.guild.roles.cache.find(SupportTeam => SupportTeam.id === supportbot.Staff)
|
||||
const Admins = message.guild.roles.cache.find(AdminUser => AdminUser.name === supportbot.Admin) || message.guild.roles.cache.find(AdminUser => AdminUser.id === supportbot.Admin)
|
||||
const DeptRole1 = message.guild.roles.cache.find(DepartmentRole => DepartmentRole.name === `${supportbot.DepartmentRole_1}`) || message.guild.roles.cache.find(DepartmentRole => DepartmentRole.id === `${supportbot.DepartmentRole_1}`)
|
||||
const DeptRole2 = message.guild.roles.cache.find(DepartmentRole => DepartmentRole.name === `${supportbot.DepartmentRole_2}`) || message.guild.roles.cache.find(DepartmentRole => DepartmentRole.id === `${supportbot.DepartmentRole_2}`)
|
||||
const DeptRole3 = message.guild.roles.cache.find(DepartmentRole => DepartmentRole.name === `${supportbot.DepartmentRole_3}`) || message.guild.roles.cache.find(DepartmentRole => DepartmentRole.id === `${supportbot.DepartmentRole_3}`)
|
||||
const Author = message.author
|
||||
const Everyone = message.guild.id
|
||||
const ticketChannel = await message.guild.channels.create(`${supportbot.TicketChannel}-${ticketNumberID}`, {
|
||||
type: "GUILD_TEXT",
|
||||
})
|
||||
|
||||
if (message.channel.name === supportbot.ReactionChannel || message.channel.id === supportbot.ReactionChannel) {
|
||||
const CreatedTicket = new Discord.MessageEmbed()
|
||||
.setDescription(supportbot.TicketCreatedAlert.replace(/%ticketauthor%/g, message.author.id).replace(/%ticketid%/g, ticketChannel.id).replace(/%ticketusername%/g, message.author.username))
|
||||
.setColor(supportbot.EmbedColour)
|
||||
message.channel.send({embeds: [CreatedTicket]}).then(msg => {
|
||||
setTimeout(() => msg.delete(), 5000)
|
||||
})
|
||||
} else {
|
||||
const CreatedTicket = new Discord.MessageEmbed()
|
||||
.setDescription(supportbot.TicketCreatedAlert.replace(/%ticketauthor%/g, message.author.id).replace(/%ticketid%/g, ticketChannel.id).replace(/%ticketusername%/g, message.author.username))
|
||||
.setColor(supportbot.EmbedColour)
|
||||
message.channel.send({embeds: [CreatedTicket]}).then(msg => setTimeout(() => msg.delete(), 5000));
|
||||
}
|
||||
let AllowArr = [Staff, Staff, Admins, Author]
|
||||
await asyncForEach(AllowArr, (index) => {
|
||||
ticketChannel.permissionOverwrites.create(index, {VIEW_CHANNEL: true})
|
||||
})
|
||||
|
||||
let DenyArr = [Everyone]
|
||||
await asyncForEach(DenyArr, (index) => {
|
||||
ticketChannel.permissionOverwrites.create(index, {VIEW_CHANNEL: false})
|
||||
})
|
||||
|
||||
let TicketCategory = message.guild.channels.cache.find(category => category.name === supportbot.TicketCategory) || message.guild.channels.cache.find(category => category.id === supportbot.TicketCategory)
|
||||
if(TicketCategory) {
|
||||
ticketChannel.setParent(TicketCategory.id)
|
||||
}
|
||||
|
||||
if (supportbot.AllowTicketMentions) {
|
||||
ticketChannel.send({content:`${message.author}`})
|
||||
}
|
||||
|
||||
const TicketMessage = new Discord.MessageEmbed()
|
||||
.setTitle(supportbot.Ticket_Title.replace(/%ticketauthor%/g, message.author.id).replace(/%ticketid%/g, ticketChannel.id).replace(/%ticketusername%/g, message.author.username))
|
||||
.setDescription(supportbot.TicketMessage.replace(/%ticketauthor%/g, message.author.id).replace(/%ticketid%/g, ticketChannel.id).replace(/%ticketusername%/g, message.author.username))
|
||||
.setColor(supportbot.EmbedColour)
|
||||
|
||||
if (supportbot.TicketSubject === "embed") {
|
||||
|
||||
if (TicketSubject != 'No Reason Provided.') {
|
||||
TicketMessage.addFields({ name: 'Reason', value: TicketSubject })
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (supportbot.TicketSubject === "description") {
|
||||
|
||||
if (TicketSubject != 'No Reason Provided.') {
|
||||
ticketChannel.setTopic(`Reason: ${TicketSubject} - User ID: ${message.author.id} - Ticket: ${ticketChannel.name}`)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (supportbot.TicketDepartments) {
|
||||
TicketMessage.addFields({ name: 'Departments', value: ` **${supportbot.DepartmentTitle_1}**\n **${supportbot.DepartmentTitle_2}**\n **${supportbot.DepartmentTitle_3}**` })
|
||||
}
|
||||
const CloseButton = new Discord.MessageButton()
|
||||
.setCustomId('ticketclose')
|
||||
.setLabel('Close')
|
||||
.setStyle(supportbot.TicketCloseColour)
|
||||
.setEmoji(supportbot.TicketCloseEmoji)
|
||||
|
||||
const LockButton = new Discord.MessageButton()
|
||||
.setCustomId('ticketlock')
|
||||
.setLabel('Lock')
|
||||
.setStyle(supportbot.TicketLockColour)
|
||||
.setEmoji(supportbot.TicketLockEmoji)
|
||||
|
||||
const row2 = new Discord.MessageActionRow()
|
||||
.addComponents(CloseButton, LockButton)
|
||||
|
||||
if(supportbot.TicketDepartments) {
|
||||
|
||||
let DenyArr = [DeptRole1, DeptRole2, DeptRole3]
|
||||
await asyncForEach(DenyArr, (index) => {
|
||||
ticketChannel.permissionOverwrites.create(index, {VIEW_CHANNEL: false})
|
||||
})
|
||||
const Department1Button = new Discord.MessageButton()
|
||||
.setCustomId('Department1')
|
||||
.setLabel(`${supportbot.DepartmentTitle_1}`)
|
||||
.setStyle(supportbot.TicketDept1Colour)
|
||||
.setEmoji(supportbot.TicketDept1Emoji)
|
||||
|
||||
const Department2Button = new Discord.MessageButton()
|
||||
.setCustomId('Department2')
|
||||
.setLabel(`${supportbot.DepartmentTitle_2}`)
|
||||
.setStyle(supportbot.TicketDept2Colour)
|
||||
.setEmoji(supportbot.TicketDept2Emoji)
|
||||
|
||||
const Department3Button = new Discord.MessageButton()
|
||||
.setCustomId('Department3')
|
||||
.setLabel(`${supportbot.DepartmentTitle_3}`)
|
||||
.setStyle(supportbot.TicketDept3Colour)
|
||||
.setEmoji(supportbot.TicketDept3Emoji)
|
||||
|
||||
const row = new Discord.MessageActionRow()
|
||||
.addComponents(Department1Button, Department2Button, Department3Button)
|
||||
|
||||
const m = await ticketChannel.send({embeds: [TicketMessage], components: [row]})
|
||||
|
||||
const filter = i => {
|
||||
i.deferUpdate();
|
||||
return i.user.id === message.author.id;
|
||||
};
|
||||
const collector = m.createMessageComponentCollector({ filter, max: 1, componentType: 'BUTTON', time: 60000 });
|
||||
|
||||
collector.on('collect',async (i) => {
|
||||
|
||||
if(i.customId === 'Department1') {
|
||||
|
||||
ticketChannel.permissionOverwrites.edit(DeptRole1, {
|
||||
VIEW_CHANNEL: true,
|
||||
READ_MESSAGE_HISTORY: true,
|
||||
SEND_MESSAGES: true,
|
||||
})
|
||||
|
||||
if(!supportbot.AllowStaff) {
|
||||
ticketChannel.permissionOverwrites.edit(Staff, { VIEW_CHANNEL: false, READ_MESSAGE_HISTORY: false, SEND_MESSAGES: false })
|
||||
}
|
||||
|
||||
const Department1 = new Discord.MessageEmbed()
|
||||
.setDescription(`> Thank for reaching out to the **${supportbot.DepartmentTitle_1} Department**. Please provide us information regarding your query.`)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
ticketChannel.send({ embeds: [Department1] });
|
||||
|
||||
if (supportbot.AllowTicketMentions) {
|
||||
ticketChannel.send({content: `@here`})
|
||||
}
|
||||
}
|
||||
i.message.edit({embeds: [TicketMessage], components: [row2]})
|
||||
|
||||
if(i.customId === 'Department2') {
|
||||
|
||||
ticketChannel.permissionOverwrites.edit(DeptRole2, {
|
||||
VIEW_CHANNEL: true,
|
||||
READ_MESSAGE_HISTORY: true,
|
||||
SEND_MESSAGES: true,
|
||||
})
|
||||
|
||||
if(!supportbot.AllowStaff) {
|
||||
ticketChannel.permissionOverwrites.edit(Staff, { VIEW_CHANNEL: false, READ_MESSAGE_HISTORY: false, SEND_MESSAGES: false })
|
||||
}
|
||||
|
||||
|
||||
const Department2 = new Discord.MessageEmbed()
|
||||
.setDescription(`> Thank for reaching out to the **${supportbot.DepartmentTitle_2} Department**. Please provide us information regarding your query.`)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
ticketChannel.send({ embeds: [Department2] });
|
||||
|
||||
if (supportbot.AllowTicketMentions) {
|
||||
ticketChannel.send({content: `@here`})
|
||||
}
|
||||
|
||||
i.message.edit({embeds: [TicketMessage], components: [row2]})
|
||||
}
|
||||
if(i.customId === 'Department3') {
|
||||
|
||||
ticketChannel.permissionOverwrites.edit(DeptRole3, {
|
||||
VIEW_CHANNEL: true,
|
||||
READ_MESSAGE_HISTORY: true,
|
||||
SEND_MESSAGES: true,
|
||||
})
|
||||
|
||||
if(!supportbot.AllowStaff) {
|
||||
ticketChannel.permissionOverwrites.edit(Staff, { VIEW_CHANNEL: false, READ_MESSAGE_HISTORY: false, SEND_MESSAGES: false })
|
||||
}
|
||||
|
||||
const Department3 = new Discord.MessageEmbed()
|
||||
.setDescription(`> Thank for reaching out to the **${supportbot.DepartmentTitle_3} Department**. Please provide us information regarding your query.`)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
ticketChannel.send({ embeds: [Department3] });
|
||||
|
||||
if (supportbot.AllowTicketMentions) {
|
||||
ticketChannel.send({content: `@here`})
|
||||
}
|
||||
i.message.edit({embeds: [TicketMessage], components: [row2]})
|
||||
}
|
||||
})
|
||||
} else {
|
||||
ticketChannel.send({embeds: [TicketMessage], components: [row2]})
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
@@ -1,166 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Interaction Create Event
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const cmdconfig = yaml.load(fs.readFileSync('./Data/commands.yml', 'utf8'));
|
||||
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
module.exports = new Event("interactionCreate", (client, interaction) => {
|
||||
|
||||
if (interaction.isCommand()) return;
|
||||
|
||||
const command = client.commands.find(cmd => cmd.name.toLowerCase() == interaction.commandName);
|
||||
|
||||
if (interaction.user.bot || !interaction.isCommand() || !interaction.guild)
|
||||
return;
|
||||
|
||||
const args = [
|
||||
interaction.commandName,
|
||||
...client.commands
|
||||
.find(cmd => cmd.name.toLowerCase() == interaction.commandName)
|
||||
.slashCommandOptions.map(v => `${interaction.options.get(v.name).value}`)
|
||||
];
|
||||
|
||||
const NotValid = new Discord.MessageEmbed()
|
||||
.setDescription(`:x: \`Invalid Command\` `)
|
||||
.setColor(supportbot.ErrorColour)
|
||||
|
||||
if (!command) return interaction.reply({
|
||||
embeds: [NotValid]
|
||||
});
|
||||
|
||||
const permission = interaction.member.permissions.has(command.permission);
|
||||
|
||||
const ValidPerms = new Discord.MessageEmbed()
|
||||
.setDescription(":x: \`Invalid Permissions\` Do you have the correct permissions to execute this command?")
|
||||
.setColor(supportbot.ErrorColour)
|
||||
|
||||
if (!permission)
|
||||
return interaction.reply({
|
||||
embeds: [ValidPerms]
|
||||
});
|
||||
|
||||
command.run(interaction, args, client);
|
||||
|
||||
if(interaction.isButton()) {
|
||||
if(interaction.customId === 'openticket') {
|
||||
interaction.message.fetch()
|
||||
interaction.deferUpdate()
|
||||
let message = {
|
||||
guild: client.guilds.cache.get(interaction.message.guildId),
|
||||
author: client.users.cache.get(interaction.user.id),
|
||||
content: "N/A",
|
||||
channel: client.channels.cache.get(interaction.message.channelId)
|
||||
}
|
||||
try {
|
||||
const cmd = client.commands.get(cmdconfig.OpenTicket);
|
||||
if(!cmd) return;
|
||||
cmd.run(message, message.content)
|
||||
}
|
||||
catch (error){
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
if(interaction.customId === 'ticketclose') {
|
||||
if(interaction.channel.name.startsWith(`${supportbot.TicketChannel}-`)) {
|
||||
interaction.message.fetch()
|
||||
interaction.deferUpdate()
|
||||
const DeleteTicketEmbed = new Discord.MessageEmbed()
|
||||
.setDescription(supportbot.TicketDeleteMessage)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
interaction.channel.send({embeds: [DeleteTicketEmbed]})
|
||||
|
||||
let logChannel = interaction.guild.channels.cache.find(channel => channel.name === supportbot.TranscriptLog) || interaction.guild.channels.cache.find(channel => channel.id === supportbot.TranscriptLog)
|
||||
|
||||
let user = interaction.user
|
||||
let name = interaction.channel.name;
|
||||
let ticketChannel = interaction.channel
|
||||
let reason = "No Reason Provided."
|
||||
|
||||
interaction.channel.send({content: `**${supportbot.ClosingTicket}**`})
|
||||
.then(() => {
|
||||
const logEmbed = new Discord.MessageEmbed()
|
||||
.setTitle(supportbot.TranscriptTitle)
|
||||
.setColor(supportbot.EmbedColour)
|
||||
.setFooter(supportbot.EmbedFooter)
|
||||
.addField("Closed By", user.username)
|
||||
.addField("Reason", reason)
|
||||
|
||||
interaction.channel.messages.fetch({limit: 100}).then(msgs => {
|
||||
let html = ''
|
||||
|
||||
msgs = msgs.sort( ( a, b ) => a.createdTimestamp - b.createdTimestamp );
|
||||
html += `<strong>Server Name:</strong> ${interaction.guild.name}<br>`
|
||||
html += `<strong>Ticket:</strong> ${ticketChannel.name}<br>`
|
||||
html += `<strong>Message:</strong> ${msgs.size} Messages<br><br><br>`
|
||||
|
||||
|
||||
msgs.forEach(msg => {
|
||||
if(msg.content) {
|
||||
html += `<strong>User:</strong> ${msg.author.tag}<br>`;
|
||||
html += `<strong>Message:</strong> ${msg.content}<br>`;
|
||||
html += `-----<br><br>`;
|
||||
}
|
||||
})
|
||||
|
||||
const TranscriptSavedEmbed = new Discord.MessageEmbed()
|
||||
.setDescription(supportbot.TranscriptSavedMessage)
|
||||
.setColor(supportbot.SuccessColour)
|
||||
interaction.channel.send({embeds: [TranscriptSavedEmbed]})
|
||||
|
||||
let file = new Discord.MessageAttachment( Buffer.from( html ), `${name}.html` )
|
||||
logChannel.send({embeds: [logEmbed], files: [file]})
|
||||
|
||||
setTimeout(() => interaction.channel.delete(), supportbot.TicketDeleteTime)
|
||||
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
if(interaction.customId === 'ticketlock') {
|
||||
if(interaction.channel.name.startsWith(`${supportbot.TicketChannel}`)) {
|
||||
interaction.message.fetch()
|
||||
interaction.deferUpdate()
|
||||
let Admin = interaction.guild.roles.cache.find(AdminUser => AdminUser.name === supportbot.Admin) || interaction.guild.roles.cache.find(AdminUser => AdminUser.id === supportbot.Admin)
|
||||
let all = interaction.channel.permissionOverwrites.cache
|
||||
|
||||
let parent = interaction.guild.channels.cache.find(c => c.name === `${supportbot.LockTicketCategory}`) || interaction.guild.channels.cache.find(c => c.id === `${supportbot.LockTicketCategory}`)
|
||||
if(parent) {
|
||||
interaction.channel.setParent(parent.id)
|
||||
}
|
||||
|
||||
all.forEach(perm => {
|
||||
interaction.channel.permissionOverwrites.delete(perm.id)
|
||||
|
||||
})
|
||||
interaction.channel.permissionOverwrites.create(Admin.id, {VIEW_CHANNEL: true})
|
||||
|
||||
interaction.channel.permissionOverwrites.create(interaction.guild.id, {VIEW_CHANNEL: false})
|
||||
|
||||
|
||||
const ticketDeleteButton = new Discord.MessageButton()
|
||||
.setCustomId('ticketclose')
|
||||
.setLabel('Close')
|
||||
.setStyle(supportbot.TicketDeleteColour)
|
||||
.setEmoji(supportbot.TicketDeleteEmoji)
|
||||
|
||||
const row = new Discord.MessageActionRow()
|
||||
.addComponents(ticketDeleteButton)
|
||||
const ArchiveEmbed = new Discord.MessageEmbed()
|
||||
.setTitle("Archived")
|
||||
.setDescription(`Archived ${interaction.channel.name}`)
|
||||
.setColor(`${supportbot.SuccessColour}`)
|
||||
|
||||
interaction.channel.send({embeds: [ArchiveEmbed]})
|
||||
interaction.message.edit({components: [row]})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Message Create Event
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
module.exports = new Event("messageCreate", (client, message) => {
|
||||
if (message.author.bot) return;
|
||||
|
||||
if (!message.content.startsWith(client.prefix)) return;
|
||||
|
||||
const args = message.content.substring(client.prefix.length).split(/ +/);
|
||||
|
||||
const command = client.commands.find(cmd => cmd.name == args[0]);
|
||||
|
||||
const NotValid = new Discord.MessageEmbed()
|
||||
.setDescription(`:x: \`${args[0]}\` is an Invalid Command `)
|
||||
.setColor(supportbot.ErrorColour)
|
||||
|
||||
if (!command) return message.reply({
|
||||
embeds: [NotValid]
|
||||
});
|
||||
|
||||
const OnlySlashCmd = new Discord.MessageEmbed()
|
||||
.setDescription(`:warning: That command is only useable as a \`Slash Command\` `)
|
||||
.setColor(supportbot.WarnColour)
|
||||
|
||||
if (!["BOTH", "TEXT"].includes(command.type))
|
||||
return message.reply({
|
||||
embeds: [OnlySlashCmd]
|
||||
})
|
||||
|
||||
const permission = message.member.permissions.has(command.permission, true);
|
||||
|
||||
const ValidPerms = new Discord.MessageEmbed()
|
||||
.setDescription(":x: Do you have the \`${command.permission}\` permissions to execute this command?")
|
||||
.setColor(supportbot.ErrorColour)
|
||||
|
||||
if (!permission)
|
||||
return message.reply(
|
||||
`You do not have the permission \`${command.permission}\` to run this command!`
|
||||
);
|
||||
|
||||
command.run(message, args, client);
|
||||
});
|
||||
@@ -1,93 +0,0 @@
|
||||
// SupportBot | Emerald Services
|
||||
// Ready Event
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const panelconfig = yaml.load(fs.readFileSync('./Data/ticket-panel.yml', 'utf8'));
|
||||
|
||||
const Event = require("../Structures/Event.js");
|
||||
|
||||
module.exports = new Event("ready", client => {
|
||||
client.user.setActivity(supportbot.BotActivity, {
|
||||
type: supportbot.ActivityType,
|
||||
url: supportbot.StreamingURL
|
||||
});
|
||||
|
||||
console.log(`\u001b[32m`, `┏━━━┓╋╋╋╋╋╋╋╋╋╋╋╋╋┏┓┏━━┓╋╋╋┏┓`)
|
||||
console.log(`\u001b[32m`, `┃┏━┓┃╋╋╋╋╋╋╋╋╋╋╋╋┏┛┗┫┏┓┃╋╋┏┛┗┓`)
|
||||
console.log(`\u001b[32m`, `┃┗━━┳┓┏┳━━┳━━┳━━┳┻┓┏┫┗┛┗┳━┻┓┏┛`)
|
||||
console.log(`\u001b[32m`, `┗━━┓┃┃┃┃┏┓┃┏┓┃┏┓┃┏┫┃┃┏━┓┃┏┓┃┃`)
|
||||
console.log(`\u001b[32m`, `┃┗━┛┃┗┛┃┗┛┃┗┛┃┗┛┃┃┃┗┫┗━┛┃┗┛┃┗┓`)
|
||||
console.log(`\u001b[32m`, `┗━━━┻━━┫┏━┫┏━┻━━┻┛┗━┻━━━┻━━┻━┛`)
|
||||
console.log(`\u001b[32m`, `┗╋╋╋╋╋╋╋┃┃╋┃┃`)
|
||||
console.log(`\u001b[32m`, `╋╋╋╋╋╋╋┗┛╋┗┛`)
|
||||
console.log(` `)
|
||||
console.log(`\u001b[31m`, `――――――――――――――――――――――――――――――――――――――――――――`)
|
||||
console.log(` `)
|
||||
console.log(`\u001b[33m`, `${supportbot.Name} v${supportbot.SupportBot_Version}`, `\u001b[36m`, `Connected to Discord`)
|
||||
console.log(`\u001b[33m`, `Resources:`, `\u001b[36m`, `https://emeraldsrv.dev/resources`)
|
||||
console.log(`\u001b[33m`, `Documentation:`, `\u001b[36m`, `https://supportbot.emeraldsrv.dev`)
|
||||
console.log(`\u001b[33m`, `Discord:`, `\u001b[36m`, `https://emeraldsrv.dev/discord`)
|
||||
console.log(`\u001b[33m`, `Hosting:`, `\u001b[36m`, `https://emeraldsrv.dev/hosting`)
|
||||
console.log(` `)
|
||||
console.log(`\u001b[37m`, `SupportBot proudly created by Emerald Services`)
|
||||
console.log(` `)
|
||||
console.log(`\u001b[31m`, `――――――――――――――――――――――――――――――――――――――――――――`)
|
||||
|
||||
if (panelconfig.TicketPanel) {
|
||||
let chan1 = client.channels.cache.find(channel => channel.name === panelconfig.Channel)
|
||||
|
||||
if (!chan1) {
|
||||
console.log('\u001b[33m', "[WARN] Ticket reaction panel is not setup, You can do so via the configuration file!")
|
||||
return false;
|
||||
}
|
||||
|
||||
const panelid = yaml.load(fs.readFileSync('./Data/ticket-panel-id.yml', 'utf8'));
|
||||
|
||||
chan1.messages.fetch(panelid.TicketPanelID).catch(async r => {
|
||||
let embed = new Discord.MessageEmbed()
|
||||
.setTitle(`${panelconfig.PanelTitle}`)
|
||||
.setColor(supportbot.SuccessColour)
|
||||
.setFooter(supportbot.EmbedFooter);
|
||||
|
||||
if (panelconfig.TicketPanel_Description) {
|
||||
embed.setDescription(panelconfig.PanelMessage)
|
||||
}
|
||||
|
||||
if (panelconfig.TicketPanel_Thumbnail) {
|
||||
embed.setThumbnail(panelconfig.PanelThumbnail)
|
||||
}
|
||||
|
||||
if (panelconfig.TicketPanel_Image) {
|
||||
embed.setImage(panelconfig.PanelImage)
|
||||
}
|
||||
|
||||
let button = new Discord.MessageButton()
|
||||
.setLabel(panelconfig.ButtonLabel)
|
||||
.setCustomId('openticket')
|
||||
.setStyle(panelconfig.ButtonColour)
|
||||
|
||||
let row = new Discord.MessageActionRow()
|
||||
.addComponents(button)
|
||||
|
||||
|
||||
await chan1.send({
|
||||
embeds: [embed],
|
||||
components: [row]
|
||||
}).then(r => {
|
||||
let data = {
|
||||
"TicketPanelID": `${r.id}`
|
||||
}
|
||||
let yamlStr = yaml.dump(data);
|
||||
fs.writeFileSync('./Data/ticket-panel-id.yml', yamlStr, 'utf8');
|
||||
|
||||
}).catch(e => {
|
||||
console.log("Raw"+e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
});
|
||||
@@ -1,24 +1,79 @@
|
||||
// ___ _ ___ _
|
||||
// / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
// \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
// <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
// |_| |_|
|
||||
// ___ _ ___ _
|
||||
// / __> _ _ ___ ___ ___ _ _ _| |_ | . > ___ _| |_
|
||||
// \__ \| | || . \| . \/ . \| '_> | | | . \/ . \ | |
|
||||
// <___/`___|| _/| _/\___/|_| |_| |___/\___/ |_|
|
||||
// |_| |_|
|
||||
//
|
||||
// SupportBot created by Emerald Services
|
||||
// Installed with MIT License
|
||||
//
|
||||
// Discord Support: https://emeraldsrv.dev/discord
|
||||
// Community Resources: https://emeraldsrv.dev/resources
|
||||
// Community Resources: https://community.emeraldsrv.dev
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const Discord = require("discord.js");
|
||||
const yaml = require('js-yaml');
|
||||
const supportbot = yaml.load(fs.readFileSync('./Data/supportbot.yml', 'utf8'));
|
||||
const yaml = require("js-yaml");
|
||||
const supportbot = yaml.load(
|
||||
fs.readFileSync("./Configs/supportbot.yml", "utf8")
|
||||
);
|
||||
|
||||
const Client = require("./Structures/Client.js");
|
||||
const client = new Client({});
|
||||
const client = new Client({
|
||||
intents: ['Guilds', 'GuildMembers', 'GuildMessages', 'MessageContent']
|
||||
});
|
||||
|
||||
client.start(supportbot.Token);
|
||||
const APIServer = require("./API/server.js");
|
||||
|
||||
client.start(supportbot.General.Token);
|
||||
|
||||
client.once('clientReady', () => {
|
||||
const api = new APIServer(client);
|
||||
api.start();
|
||||
});
|
||||
|
||||
// SupportBot - New Logging System
|
||||
|
||||
const logTypes = ["Output", "Warn", "Error"];
|
||||
|
||||
if (!fs.existsSync("./Logs")) {
|
||||
fs.mkdirSync("./Logs");
|
||||
}
|
||||
logTypes.forEach((type) => {
|
||||
const dir = `./Logs/${type}`;
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir);
|
||||
}
|
||||
});
|
||||
|
||||
function logToFile(type, data) {
|
||||
const date = new Date().toISOString().split("T")[0];
|
||||
const file = path.join(`./Logs/${type}`, `${type}-${date}.log`);
|
||||
fs.appendFileSync(file, `[${new Date().toISOString()}] ${data}\n`);
|
||||
}
|
||||
|
||||
const origLog = console.log;
|
||||
console.log = (...args) => {
|
||||
origLog(...args);
|
||||
logToFile("Output", args.join(" "));
|
||||
};
|
||||
|
||||
const origWarn = console.warn;
|
||||
console.warn = (...args) => {
|
||||
origWarn(...args);
|
||||
logToFile("Warn", args.join(" "));
|
||||
};
|
||||
|
||||
const origError = console.error;
|
||||
console.error = (...args) => {
|
||||
origError(...args);
|
||||
logToFile("Error", args.join(" "));
|
||||
};
|
||||
|
||||
process.on("unhandledRejection", (reason) => {
|
||||
console.error("Unhandled Rejection:", reason);
|
||||
});
|
||||
|
||||
process.on("uncaughtException", (err) => {
|
||||
console.error("Uncaught Exception:", err);
|
||||
});
|
||||
BIN
Binary file not shown.
-1
@@ -1 +0,0 @@
|
||||
../js-yaml/bin/js-yaml.js
|
||||
-297
@@ -1,297 +0,0 @@
|
||||
{
|
||||
"name": "supportbot",
|
||||
"version": "7.2.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"node_modules/@discordjs/builders": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-0.5.0.tgz",
|
||||
"integrity": "sha512-HP5y4Rqw68o61Qv4qM5tVmDbWi4mdTFftqIOGRo33SNPpLJ1Ga3KEIR2ibKofkmsoQhEpLmopD1AZDs3cKpHuw==",
|
||||
"dependencies": {
|
||||
"@sindresorhus/is": "^4.0.1",
|
||||
"discord-api-types": "^0.22.0",
|
||||
"ow": "^0.27.0",
|
||||
"ts-mixer": "^6.0.0",
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0",
|
||||
"npm": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/collection": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-0.2.1.tgz",
|
||||
"integrity": "sha512-vhxqzzM8gkomw0TYRF3tgx7SwElzUlXT/Aa41O7mOcyN6wIJfj5JmDWaO5XGKsGSsNx7F3i5oIlrucCCWV1Nog==",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/form-data": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/form-data/-/form-data-3.0.1.tgz",
|
||||
"integrity": "sha512-ZfFsbgEXW71Rw/6EtBdrP5VxBJy4dthyC0tpQKGKmYFImlmmrykO14Za+BiIVduwjte0jXEBlhSKf0MWbFp9Eg==",
|
||||
"dependencies": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
"mime-types": "^2.1.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/@sapphire/async-queue": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.1.4.tgz",
|
||||
"integrity": "sha512-fFrlF/uWpGOX5djw5Mu2Hnnrunao75WGey0sP0J3jnhmrJ5TAPzHYOmytD5iN/+pMxS+f+u/gezqHa9tPhRHEA==",
|
||||
"engines": {
|
||||
"node": ">=14",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@sindresorhus/is": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.2.0.tgz",
|
||||
"integrity": "sha512-VkE3KLBmJwcCaVARtQpfuKcKv8gcBmUubrfHGF84dXuuW6jgsRYxPtzcIhPyK9WAPpRt2/xY6zkD9MnRaJzSyw==",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sindresorhus/is?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "16.10.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.10.2.tgz",
|
||||
"integrity": "sha512-zCclL4/rx+W5SQTzFs9wyvvyCwoK9QtBpratqz2IYJ3O8Umrn0m3nsTv0wQBk9sRGpvUe9CwPDrQFB10f1FIjQ=="
|
||||
},
|
||||
"node_modules/@types/ws": {
|
||||
"version": "7.4.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-7.4.7.tgz",
|
||||
"integrity": "sha512-JQbbmxZTZehdc2iszGKs5oC3NFnjeay7mtAWrdt7qNtAVK0g19muApzAy4bm9byz79xa2ZnO/BOBC2R8RC5Lww==",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
|
||||
},
|
||||
"node_modules/callsites": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
|
||||
"integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||
"dependencies": {
|
||||
"delayed-stream": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
"integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/discord-api-types": {
|
||||
"version": "0.22.0",
|
||||
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.22.0.tgz",
|
||||
"integrity": "sha512-l8yD/2zRbZItUQpy7ZxBJwaLX/Bs2TGaCthRppk8Sw24LOIWg12t9JEreezPoYD0SQcC2htNNo27kYEpYW/Srg==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/discord.js": {
|
||||
"version": "13.1.0",
|
||||
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.1.0.tgz",
|
||||
"integrity": "sha512-gxO4CXKdHpqA+WKG+f5RNnd3srTDj5uFJHgOathksDE90YNq/Qijkd2WlMgTTMS6AJoEnHxI7G9eDQHCuZ+xDA==",
|
||||
"dependencies": {
|
||||
"@discordjs/builders": "^0.5.0",
|
||||
"@discordjs/collection": "^0.2.1",
|
||||
"@discordjs/form-data": "^3.0.1",
|
||||
"@sapphire/async-queue": "^1.1.4",
|
||||
"@types/ws": "^7.4.7",
|
||||
"discord-api-types": "^0.22.0",
|
||||
"node-fetch": "^2.6.1",
|
||||
"ws": "^7.5.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.6.0",
|
||||
"npm": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dot-prop": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-6.0.1.tgz",
|
||||
"integrity": "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==",
|
||||
"dependencies": {
|
||||
"is-obj": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/is-obj": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz",
|
||||
"integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
|
||||
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"js-yaml": "bin/js-yaml.js"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.isequal": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
|
||||
"integrity": "sha1-QVxEePK8wwEgwizhDtMib30+GOA="
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.50.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.50.0.tgz",
|
||||
"integrity": "sha512-9tMZCDlYHqeERXEHO9f/hKfNXhre5dK2eE/krIvUjZbS2KPcqGDfNShIWS1uW9XOTKQKqK6qbeOci18rbfW77A==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.33",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.33.tgz",
|
||||
"integrity": "sha512-plLElXp7pRDd0bNZHw+nMd52vRYjLwQjygaNg7ddJ2uJtTlmnTCjWuPKxVu6//AdaRuME84SvLW91sIkBqGT0g==",
|
||||
"dependencies": {
|
||||
"mime-db": "1.50.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/node-fetch": {
|
||||
"version": "2.6.5",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.5.tgz",
|
||||
"integrity": "sha512-mmlIVHJEu5rnIxgEgez6b9GgWXbkZj5YZ7fx+2r94a2E+Uirsp6HsPTPlomfdHtpt/B0cdKviwkoaM6pyvUOpQ==",
|
||||
"dependencies": {
|
||||
"whatwg-url": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "4.x || >=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ow": {
|
||||
"version": "0.27.0",
|
||||
"resolved": "https://registry.npmjs.org/ow/-/ow-0.27.0.tgz",
|
||||
"integrity": "sha512-SGnrGUbhn4VaUGdU0EJLMwZWSupPmF46hnTRII7aCLCrqixTAC5eKo8kI4/XXf1eaaI8YEVT+3FeGNJI9himAQ==",
|
||||
"dependencies": {
|
||||
"@sindresorhus/is": "^4.0.1",
|
||||
"callsites": "^3.1.0",
|
||||
"dot-prop": "^6.0.1",
|
||||
"lodash.isequal": "^4.5.0",
|
||||
"type-fest": "^1.2.1",
|
||||
"vali-date": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/tr46": {
|
||||
"version": "0.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||
"integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o="
|
||||
},
|
||||
"node_modules/ts-mixer": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.0.tgz",
|
||||
"integrity": "sha512-nXIb1fvdY5CBSrDIblLn73NW0qRDk5yJ0Sk1qPBF560OdJfQp9jhl+0tzcY09OZ9U+6GpeoI9RjwoIKFIoB9MQ=="
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz",
|
||||
"integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="
|
||||
},
|
||||
"node_modules/type-fest": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-1.4.0.tgz",
|
||||
"integrity": "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/vali-date": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/vali-date/-/vali-date-1.0.0.tgz",
|
||||
"integrity": "sha1-G5BKWWCfsyjvB4E4Qgk09rhnCaY=",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/webidl-conversions": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
||||
"integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE="
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||
"integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=",
|
||||
"dependencies": {
|
||||
"tr46": "~0.0.3",
|
||||
"webidl-conversions": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "7.5.5",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.5.tgz",
|
||||
"integrity": "sha512-BAkMFcAzl8as1G/hArkxOxq3G7pjUqQ3gzYbLL0/5zNkph70e+lCoxBGnm6AW1+/aiNeV4fnKqZ8m4GZewmH2w==",
|
||||
"engines": {
|
||||
"node": ">=8.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": "^5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
-190
@@ -1,190 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright 2021 Vlad Frangu
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
<div align="center">
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
|
||||
</p>
|
||||
<br />
|
||||
<p>
|
||||
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
|
||||
<a href="https://github.com/discordjs/builders/actions"><img src="https://github.com/discordjs/builders/workflows/Tests/badge.svg" alt="Test status" /></a>
|
||||
<a href="https://github.com/discordjs/builders/actions"><img src="https://github.com/discordjs/builders/workflows/Lint/badge.svg" alt="Lint status" /></a>
|
||||
<a href="https://codecov.io/gh/discordjs/builders"><img src="https://codecov.io/gh/discordjs/builders/branch/main/graph/badge.svg" alt="Code coverage" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## Installation
|
||||
|
||||
Install with [npm](https://www.npmjs.com/) / [yarn](https://yarnpkg.com) / [pnpm](https://pnpm.js.org/):
|
||||
|
||||
```sh
|
||||
npm install @discordjs/builders
|
||||
yarn add @discordjs/builders
|
||||
pnpm add @discordjs/builders
|
||||
```
|
||||
|
||||
## Contribution
|
||||
|
||||
See [Contributing Guide](https://github.com/discordjs/builders/blob/main/.github/CONTRIBUTING.md).
|
||||
|
||||
## Examples
|
||||
|
||||
Here are some examples for the builders and utilities you can find in this package:
|
||||
|
||||
- [Slash Command Builders](./docs/examples/Slash%20Command%20Builders.md)
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
export * from './messages/formatters';
|
||||
export * as SlashCommandAssertions from './interactions/slashCommands/Assertions';
|
||||
export * from './interactions/slashCommands/SlashCommandBuilder';
|
||||
export * from './interactions/slashCommands/SlashCommandSubcommands';
|
||||
export * from './interactions/slashCommands/options/boolean';
|
||||
export * from './interactions/slashCommands/options/channel';
|
||||
export * from './interactions/slashCommands/options/integer';
|
||||
export * from './interactions/slashCommands/options/mentionable';
|
||||
export * from './interactions/slashCommands/options/role';
|
||||
export * from './interactions/slashCommands/options/string';
|
||||
export * from './interactions/slashCommands/options/user';
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AAEtC,OAAO,KAAK,sBAAsB,MAAM,yCAAyC,CAAC;AAClF,cAAc,kDAAkD,CAAC;AACjE,cAAc,sDAAsD,CAAC;AACrE,cAAc,8CAA8C,CAAC;AAC7D,cAAc,8CAA8C,CAAC;AAC7D,cAAc,8CAA8C,CAAC;AAC7D,cAAc,kDAAkD,CAAC;AACjE,cAAc,2CAA2C,CAAC;AAC1D,cAAc,6CAA6C,CAAC;AAC5D,cAAc,2CAA2C,CAAC"}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SlashCommandAssertions = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
tslib_1.__exportStar(require("./messages/formatters"), exports);
|
||||
exports.SlashCommandAssertions = tslib_1.__importStar(require("./interactions/slashCommands/Assertions"));
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/SlashCommandBuilder"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/SlashCommandSubcommands"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/options/boolean"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/options/channel"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/options/integer"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/options/mentionable"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/options/role"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/options/string"), exports);
|
||||
tslib_1.__exportStar(require("./interactions/slashCommands/options/user"), exports);
|
||||
//# sourceMappingURL=index.js.map
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;AAAA,gEAAsC;AAEtC,0GAAkF;AAClF,2FAAiE;AACjE,+FAAqE;AACrE,uFAA6D;AAC7D,uFAA6D;AAC7D,uFAA6D;AAC7D,2FAAiE;AACjE,oFAA0D;AAC1D,sFAA4D;AAC5D,oFAA0D","sourcesContent":["export * from './messages/formatters';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions';\nexport * from './interactions/slashCommands/SlashCommandBuilder';\nexport * from './interactions/slashCommands/SlashCommandSubcommands';\nexport * from './interactions/slashCommands/options/boolean';\nexport * from './interactions/slashCommands/options/channel';\nexport * from './interactions/slashCommands/options/integer';\nexport * from './interactions/slashCommands/options/mentionable';\nexport * from './interactions/slashCommands/options/role';\nexport * from './interactions/slashCommands/options/string';\nexport * from './interactions/slashCommands/options/user';\n"]}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
import mod from "./index.js";
|
||||
|
||||
export default mod;
|
||||
export const Faces = mod.Faces;
|
||||
export const SlashCommandAssertions = mod.SlashCommandAssertions;
|
||||
export const SlashCommandBooleanOption = mod.SlashCommandBooleanOption;
|
||||
export const SlashCommandBuilder = mod.SlashCommandBuilder;
|
||||
export const SlashCommandChannelOption = mod.SlashCommandChannelOption;
|
||||
export const SlashCommandIntegerOption = mod.SlashCommandIntegerOption;
|
||||
export const SlashCommandMentionableOption = mod.SlashCommandMentionableOption;
|
||||
export const SlashCommandRoleOption = mod.SlashCommandRoleOption;
|
||||
export const SlashCommandStringOption = mod.SlashCommandStringOption;
|
||||
export const SlashCommandSubcommandBuilder = mod.SlashCommandSubcommandBuilder;
|
||||
export const SlashCommandSubcommandGroupBuilder = mod.SlashCommandSubcommandGroupBuilder;
|
||||
export const SlashCommandUserOption = mod.SlashCommandUserOption;
|
||||
export const TimestampStyles = mod.TimestampStyles;
|
||||
export const blockQuote = mod.blockQuote;
|
||||
export const bold = mod.bold;
|
||||
export const channelMention = mod.channelMention;
|
||||
export const codeBlock = mod.codeBlock;
|
||||
export const formatEmoji = mod.formatEmoji;
|
||||
export const hideLinkEmbed = mod.hideLinkEmbed;
|
||||
export const hyperlink = mod.hyperlink;
|
||||
export const inlineCode = mod.inlineCode;
|
||||
export const italic = mod.italic;
|
||||
export const memberNicknameMention = mod.memberNicknameMention;
|
||||
export const quote = mod.quote;
|
||||
export const roleMention = mod.roleMention;
|
||||
export const spoiler = mod.spoiler;
|
||||
export const strikethrough = mod.strikethrough;
|
||||
export const time = mod.time;
|
||||
export const underscore = mod.underscore;
|
||||
export const userMention = mod.userMention;
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
import type { APIApplicationCommandOptionChoice } from 'discord-api-types/v9';
|
||||
import type { SlashCommandOptionBase } from './mixins/CommandOptionBase';
|
||||
import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder';
|
||||
import type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands';
|
||||
export declare function validateRequiredParameters(name: string, description: string, options: ToAPIApplicationCommandOptions[]): void;
|
||||
export declare function validateName(name: unknown): asserts name is string;
|
||||
export declare function validateDescription(description: unknown): asserts description is string;
|
||||
export declare function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[];
|
||||
export declare function validateMaxChoicesLength(choices: APIApplicationCommandOptionChoice[]): void;
|
||||
export declare function assertReturnOfBuilder<T extends SlashCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T;
|
||||
//# sourceMappingURL=Assertions.d.ts.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"Assertions.d.ts","sourceRoot":"/","sources":["interactions/slashCommands/Assertions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iCAAiC,EAAE,MAAM,sBAAsB,CAAC;AAE9E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,KAAK,EAAE,6BAA6B,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAEnH,wBAAgB,0BAA0B,CACzC,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,8BAA8B,EAAE,QAUzC;AAUD,wBAAgB,YAAY,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,IAAI,MAAM,CAElE;AAID,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,IAAI,MAAM,CAEvF;AAID,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,8BAA8B,EAAE,CAE9G;AAED,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,iCAAiC,EAAE,QAEpF;AAED,wBAAgB,qBAAqB,CACpC,CAAC,SAAS,sBAAsB,GAAG,6BAA6B,GAAG,kCAAkC,EACpG,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,UAAU,CAAC,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,CAuBrE"}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.assertReturnOfBuilder = exports.validateMaxChoicesLength = exports.validateMaxOptionsLength = exports.validateDescription = exports.validateName = exports.validateRequiredParameters = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
|
||||
const ow_1 = tslib_1.__importDefault(require("ow"));
|
||||
function validateRequiredParameters(name, description, options) {
|
||||
// Assert name matches all conditions
|
||||
validateName(name);
|
||||
// Assert description conditions
|
||||
validateDescription(description);
|
||||
// Assert options conditions
|
||||
validateMaxOptionsLength(options);
|
||||
}
|
||||
exports.validateRequiredParameters = validateRequiredParameters;
|
||||
const namePredicate = ow_1.default.string.lowercase
|
||||
.minLength(1)
|
||||
.maxLength(32)
|
||||
.addValidator({
|
||||
message: (value, label) => `Expected ${label} to match "^[\\p{L}\\p{N}_-]+$", got ${value} instead`,
|
||||
validator: (value) => /^[\p{L}\p{N}_-]+$/u.test(value),
|
||||
});
|
||||
function validateName(name) {
|
||||
ow_1.default(name, 'name', namePredicate);
|
||||
}
|
||||
exports.validateName = validateName;
|
||||
const descriptionPredicate = ow_1.default.string.minLength(1).maxLength(100);
|
||||
function validateDescription(description) {
|
||||
ow_1.default(description, 'description', descriptionPredicate);
|
||||
}
|
||||
exports.validateDescription = validateDescription;
|
||||
const maxArrayLengthPredicate = ow_1.default.array.maxLength(25);
|
||||
function validateMaxOptionsLength(options) {
|
||||
ow_1.default(options, 'options', maxArrayLengthPredicate);
|
||||
}
|
||||
exports.validateMaxOptionsLength = validateMaxOptionsLength;
|
||||
function validateMaxChoicesLength(choices) {
|
||||
ow_1.default(choices, 'choices', maxArrayLengthPredicate);
|
||||
}
|
||||
exports.validateMaxChoicesLength = validateMaxChoicesLength;
|
||||
function assertReturnOfBuilder(input, ExpectedInstanceOf) {
|
||||
const instanceName = ExpectedInstanceOf.name;
|
||||
if (is_1.default.nullOrUndefined(input)) {
|
||||
throw new TypeError(`Expected to receive a ${instanceName} builder, got ${input === null ? 'null' : 'undefined'} instead.`);
|
||||
}
|
||||
if (is_1.default.primitive(input)) {
|
||||
throw new TypeError(`Expected to receive a ${instanceName} builder, got a primitive (${typeof input}) instead.`);
|
||||
}
|
||||
if (!(input instanceof ExpectedInstanceOf)) {
|
||||
const casted = input;
|
||||
const constructorName = is_1.default.function_(input) ? input.name : casted.constructor.name;
|
||||
const stringTag = Reflect.get(casted, Symbol.toStringTag);
|
||||
const fullResultName = stringTag ? `${constructorName} [${stringTag}]` : constructorName;
|
||||
throw new TypeError(`Expected to receive a ${instanceName} builder, got ${fullResultName} instead.`);
|
||||
}
|
||||
}
|
||||
exports.assertReturnOfBuilder = assertReturnOfBuilder;
|
||||
//# sourceMappingURL=Assertions.js.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"Assertions.js","sourceRoot":"/","sources":["interactions/slashCommands/Assertions.ts"],"names":[],"mappings":";;;;AAAA,kEAAkC;AAElC,oDAAoB;AAKpB,SAAgB,0BAA0B,CACzC,IAAY,EACZ,WAAmB,EACnB,OAAyC;IAEzC,qCAAqC;IACrC,YAAY,CAAC,IAAI,CAAC,CAAC;IAEnB,gCAAgC;IAChC,mBAAmB,CAAC,WAAW,CAAC,CAAC;IAEjC,4BAA4B;IAC5B,wBAAwB,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAbD,gEAaC;AAED,MAAM,aAAa,GAAG,YAAE,CAAC,MAAM,CAAC,SAAS;KACvC,SAAS,CAAC,CAAC,CAAC;KACZ,SAAS,CAAC,EAAE,CAAC;KACb,YAAY,CAAC;IACb,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,YAAY,KAAM,wCAAwC,KAAK,UAAU;IACpG,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,KAAK,CAAC;CACtD,CAAC,CAAC;AAEJ,SAAgB,YAAY,CAAC,IAAa;IACzC,YAAE,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC;AACjC,CAAC;AAFD,oCAEC;AAED,MAAM,oBAAoB,GAAG,YAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAEnE,SAAgB,mBAAmB,CAAC,WAAoB;IACvD,YAAE,CAAC,WAAW,EAAE,aAAa,EAAE,oBAAoB,CAAC,CAAC;AACtD,CAAC;AAFD,kDAEC;AAED,MAAM,uBAAuB,GAAG,YAAE,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;AAEvD,SAAgB,wBAAwB,CAAC,OAAgB;IACxD,YAAE,CAAC,OAAO,EAAE,SAAS,EAAE,uBAAuB,CAAC,CAAC;AACjD,CAAC;AAFD,4DAEC;AAED,SAAgB,wBAAwB,CAAC,OAA4C;IACpF,YAAE,CAAC,OAAO,EAAE,SAAS,EAAE,uBAAuB,CAAC,CAAC;AACjD,CAAC;AAFD,4DAEC;AAED,SAAgB,qBAAqB,CAEnC,KAAc,EAAE,kBAA+B;IAChD,MAAM,YAAY,GAAG,kBAAkB,CAAC,IAAI,CAAC;IAE7C,IAAI,YAAE,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE;QAC9B,MAAM,IAAI,SAAS,CAClB,yBAAyB,YAAY,iBAAiB,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,WAAW,CACtG,CAAC;KACF;IAED,IAAI,YAAE,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE;QACxB,MAAM,IAAI,SAAS,CAAC,yBAAyB,YAAY,8BAA8B,OAAO,KAAK,YAAY,CAAC,CAAC;KACjH;IAED,IAAI,CAAC,CAAC,KAAK,YAAY,kBAAkB,CAAC,EAAE;QAC3C,MAAM,MAAM,GAAG,KAAqC,CAAC;QAErD,MAAM,eAAe,GAAG,YAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC;QACnF,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,WAAW,CAAuB,CAAC;QAEhF,MAAM,cAAc,GAAG,SAAS,CAAC,CAAC,CAAC,GAAG,eAAe,KAAK,SAAS,GAAG,CAAC,CAAC,CAAC,eAAe,CAAC;QAEzF,MAAM,IAAI,SAAS,CAAC,yBAAyB,YAAY,iBAAiB,cAAc,WAAW,CAAC,CAAC;KACrG;AACF,CAAC;AAzBD,sDAyBC","sourcesContent":["import is from '@sindresorhus/is';\nimport type { APIApplicationCommandOptionChoice } from 'discord-api-types/v9';\nimport ow from 'ow';\nimport type { SlashCommandOptionBase } from './mixins/CommandOptionBase';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands';\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst namePredicate = ow.string.lowercase\n\t.minLength(1)\n\t.maxLength(32)\n\t.addValidator({\n\t\tmessage: (value, label) => `Expected ${label!} to match \"^[\\\\p{L}\\\\p{N}_-]+$\", got ${value} instead`,\n\t\tvalidator: (value) => /^[\\p{L}\\p{N}_-]+$/u.test(value),\n\t});\n\nexport function validateName(name: unknown): asserts name is string {\n\tow(name, 'name', namePredicate);\n}\n\nconst descriptionPredicate = ow.string.minLength(1).maxLength(100);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tow(description, 'description', descriptionPredicate);\n}\n\nconst maxArrayLengthPredicate = ow.array.maxLength(25);\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tow(options, 'options', maxArrayLengthPredicate);\n}\n\nexport function validateMaxChoicesLength(choices: APIApplicationCommandOptionChoice[]) {\n\tow(choices, 'choices', maxArrayLengthPredicate);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends SlashCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\tconst instanceName = ExpectedInstanceOf.name;\n\n\tif (is.nullOrUndefined(input)) {\n\t\tthrow new TypeError(\n\t\t\t`Expected to receive a ${instanceName} builder, got ${input === null ? 'null' : 'undefined'} instead.`,\n\t\t);\n\t}\n\n\tif (is.primitive(input)) {\n\t\tthrow new TypeError(`Expected to receive a ${instanceName} builder, got a primitive (${typeof input}) instead.`);\n\t}\n\n\tif (!(input instanceof ExpectedInstanceOf)) {\n\t\tconst casted = input as Record<PropertyKey, unknown>;\n\n\t\tconst constructorName = is.function_(input) ? input.name : casted.constructor.name;\n\t\tconst stringTag = Reflect.get(casted, Symbol.toStringTag) as string | undefined;\n\n\t\tconst fullResultName = stringTag ? `${constructorName} [${stringTag}]` : constructorName;\n\n\t\tthrow new TypeError(`Expected to receive a ${instanceName} builder, got ${fullResultName} instead.`);\n\t}\n}\n"]}
|
||||
Generated
Vendored
-50
@@ -1,50 +0,0 @@
|
||||
import type { APIApplicationCommandOption } from 'discord-api-types/v9';
|
||||
import { SharedNameAndDescription } from './mixins/NameAndDescription';
|
||||
import { SharedSlashCommandOptions } from './mixins/CommandOptions';
|
||||
import { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands';
|
||||
export declare class SlashCommandBuilder {
|
||||
/**
|
||||
* The name of this slash command
|
||||
*/
|
||||
readonly name: string;
|
||||
/**
|
||||
* The description of this slash command
|
||||
*/
|
||||
readonly description: string;
|
||||
/**
|
||||
* The options of this slash command
|
||||
*/
|
||||
readonly options: ToAPIApplicationCommandOptions[];
|
||||
/**
|
||||
* Returns the final data that should be sent to Discord.
|
||||
*
|
||||
* **Note:** Calling this function will validate required properties based on their conditions.
|
||||
*/
|
||||
toJSON(): {
|
||||
name: string;
|
||||
description: string;
|
||||
options: APIApplicationCommandOption[];
|
||||
};
|
||||
/**
|
||||
* Adds a new subcommand group to this command
|
||||
* @param input A function that returns a subcommand group builder, or an already built builder
|
||||
*/
|
||||
addSubcommandGroup(input: SlashCommandSubcommandGroupBuilder | ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder)): SlashCommandSubcommandGroupsOnlyBuilder;
|
||||
/**
|
||||
* Adds a new subcommand to this command
|
||||
* @param input A function that returns a subcommand builder, or an already built builder
|
||||
*/
|
||||
addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): SlashCommandSubcommandsOnlyBuilder;
|
||||
}
|
||||
export interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {
|
||||
}
|
||||
export interface SlashCommandSubcommandsOnlyBuilder extends SharedNameAndDescription, Pick<SlashCommandBuilder, 'toJSON' | 'addSubcommand'> {
|
||||
}
|
||||
export interface SlashCommandSubcommandGroupsOnlyBuilder extends SharedNameAndDescription, Pick<SlashCommandBuilder, 'toJSON' | 'addSubcommandGroup'> {
|
||||
}
|
||||
export interface SlashCommandOptionsOnlyBuilder extends SharedNameAndDescription, SharedSlashCommandOptions, Pick<SlashCommandBuilder, 'toJSON'> {
|
||||
}
|
||||
export interface ToAPIApplicationCommandOptions {
|
||||
toJSON(): APIApplicationCommandOption;
|
||||
}
|
||||
//# sourceMappingURL=SlashCommandBuilder.d.ts.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"SlashCommandBuilder.d.ts","sourceRoot":"/","sources":["interactions/slashCommands/SlashCommandBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AAGxE,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,6BAA6B,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAE9G,qBACa,mBAAmB;IAC/B;;OAEG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAc;IAE1C;;OAEG;IACH,SAAgB,WAAW,EAAE,MAAM,CAAc;IAEjD;;OAEG;IACH,SAAgB,OAAO,EAAE,8BAA8B,EAAE,CAAM;IAE/D;;;;OAIG;IACI,MAAM;;;;;IASb;;;OAGG;IACI,kBAAkB,CACxB,KAAK,EACF,kCAAkC,GAClC,CAAC,CAAC,eAAe,EAAE,kCAAkC,KAAK,kCAAkC,CAAC,GAC9F,uCAAuC;IAqB1C;;;OAGG;IACI,aAAa,CACnB,KAAK,EACF,6BAA6B,GAC7B,CAAC,CAAC,eAAe,EAAE,6BAA6B,KAAK,6BAA6B,CAAC,GACpF,kCAAkC;CAqBrC;AAED,MAAM,WAAW,mBAAoB,SAAQ,wBAAwB,EAAE,yBAAyB;CAAG;AAEnG,MAAM,WAAW,kCAChB,SAAQ,wBAAwB,EAC/B,IAAI,CAAC,mBAAmB,EAAE,QAAQ,GAAG,eAAe,CAAC;CAAG;AAE1D,MAAM,WAAW,uCAChB,SAAQ,wBAAwB,EAC/B,IAAI,CAAC,mBAAmB,EAAE,QAAQ,GAAG,oBAAoB,CAAC;CAAG;AAE/D,MAAM,WAAW,8BAChB,SAAQ,wBAAwB,EAC/B,yBAAyB,EACzB,IAAI,CAAC,mBAAmB,EAAE,QAAQ,CAAC;CAAG;AAExC,MAAM,WAAW,8BAA8B;IAC9C,MAAM,IAAI,2BAA2B,CAAC;CACtC"}
|
||||
Generated
Vendored
-96
@@ -1,96 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SlashCommandBuilder = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const ts_mixer_1 = require("ts-mixer");
|
||||
const Assertions_1 = require("./Assertions");
|
||||
const NameAndDescription_1 = require("./mixins/NameAndDescription");
|
||||
const CommandOptions_1 = require("./mixins/CommandOptions");
|
||||
const SlashCommandSubcommands_1 = require("./SlashCommandSubcommands");
|
||||
let SlashCommandBuilder = class SlashCommandBuilder {
|
||||
constructor() {
|
||||
/**
|
||||
* The name of this slash command
|
||||
*/
|
||||
Object.defineProperty(this, "name", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: undefined
|
||||
});
|
||||
/**
|
||||
* The description of this slash command
|
||||
*/
|
||||
Object.defineProperty(this, "description", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: undefined
|
||||
});
|
||||
/**
|
||||
* The options of this slash command
|
||||
*/
|
||||
Object.defineProperty(this, "options", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: []
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns the final data that should be sent to Discord.
|
||||
*
|
||||
* **Note:** Calling this function will validate required properties based on their conditions.
|
||||
*/
|
||||
toJSON() {
|
||||
Assertions_1.validateRequiredParameters(this.name, this.description, this.options);
|
||||
return {
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
options: this.options.map((option) => option.toJSON()),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Adds a new subcommand group to this command
|
||||
* @param input A function that returns a subcommand group builder, or an already built builder
|
||||
*/
|
||||
addSubcommandGroup(input) {
|
||||
const { options } = this;
|
||||
// First, assert options conditions - we cannot have more than 25 options
|
||||
Assertions_1.validateMaxOptionsLength(options);
|
||||
// Make sure there is no subcommand at the root level - if there is, throw
|
||||
const hasSubcommands = options.some((item) => item instanceof SlashCommandSubcommands_1.SlashCommandSubcommandBuilder);
|
||||
if (hasSubcommands)
|
||||
throw new RangeError(`You cannot mix subcommands and subcommand groups at the root level.`);
|
||||
// Get the final result
|
||||
const result = typeof input === 'function' ? input(new SlashCommandSubcommands_1.SlashCommandSubcommandGroupBuilder()) : input;
|
||||
Assertions_1.assertReturnOfBuilder(result, SlashCommandSubcommands_1.SlashCommandSubcommandGroupBuilder);
|
||||
// Push it
|
||||
options.push(result);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a new subcommand to this command
|
||||
* @param input A function that returns a subcommand builder, or an already built builder
|
||||
*/
|
||||
addSubcommand(input) {
|
||||
const { options } = this;
|
||||
// First, assert options conditions - we cannot have more than 25 options
|
||||
Assertions_1.validateMaxOptionsLength(options);
|
||||
// Make sure there is no subcommand at the root level - if there is, throw
|
||||
const hasSubcommandGroups = options.some((item) => item instanceof SlashCommandSubcommands_1.SlashCommandSubcommandGroupBuilder);
|
||||
if (hasSubcommandGroups)
|
||||
throw new RangeError(`You cannot mix subcommands and subcommand groups at the root level.`);
|
||||
// Get the final result
|
||||
const result = typeof input === 'function' ? input(new SlashCommandSubcommands_1.SlashCommandSubcommandBuilder()) : input;
|
||||
Assertions_1.assertReturnOfBuilder(result, SlashCommandSubcommands_1.SlashCommandSubcommandBuilder);
|
||||
// Push it
|
||||
options.push(result);
|
||||
return this;
|
||||
}
|
||||
};
|
||||
SlashCommandBuilder = tslib_1.__decorate([
|
||||
ts_mixer_1.mix(CommandOptions_1.SharedSlashCommandOptions, NameAndDescription_1.SharedNameAndDescription)
|
||||
], SlashCommandBuilder);
|
||||
exports.SlashCommandBuilder = SlashCommandBuilder;
|
||||
//# sourceMappingURL=SlashCommandBuilder.js.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"SlashCommandBuilder.js","sourceRoot":"/","sources":["interactions/slashCommands/SlashCommandBuilder.ts"],"names":[],"mappings":";;;;AACA,uCAA+B;AAC/B,6CAA2G;AAC3G,oEAAuE;AACvE,4DAAoE;AACpE,uEAA8G;AAG9G,IAAa,mBAAmB,GAAhC,MAAa,mBAAmB;IAAhC;QACC;;WAEG;QACH;;;;mBAA+B,SAAU;WAAC;QAE1C;;WAEG;QACH;;;;mBAAsC,SAAU;WAAC;QAEjD;;WAEG;QACH;;;;mBAA4D,EAAE;WAAC;IA0EhE,CAAC;IAxEA;;;;OAIG;IACI,MAAM;QACZ,uCAA0B,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACtE,OAAO;YACN,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;SACtD,CAAC;IACH,CAAC;IAED;;;OAGG;IACI,kBAAkB,CACxB,KAEgG;QAEhG,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,yEAAyE;QACzE,qCAAwB,CAAC,OAAO,CAAC,CAAC;QAElC,0EAA0E;QAC1E,MAAM,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,YAAY,uDAA6B,CAAC,CAAC;QAC7F,IAAI,cAAc;YAAE,MAAM,IAAI,UAAU,CAAC,qEAAqE,CAAC,CAAC;QAEhH,uBAAuB;QACvB,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,4DAAkC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QAErG,kCAAqB,CAAC,MAAM,EAAE,4DAAkC,CAAC,CAAC;QAElE,UAAU;QACV,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAErB,OAAO,IAAI,CAAC;IACb,CAAC;IAED;;;OAGG;IACI,aAAa,CACnB,KAEsF;QAEtF,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,yEAAyE;QACzE,qCAAwB,CAAC,OAAO,CAAC,CAAC;QAElC,0EAA0E;QAC1E,MAAM,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,YAAY,4DAAkC,CAAC,CAAC;QACvG,IAAI,mBAAmB;YACtB,MAAM,IAAI,UAAU,CAAC,qEAAqE,CAAC,CAAC;QAE7F,uBAAuB;QACvB,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,uDAA6B,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QAEhG,kCAAqB,CAAC,MAAM,EAAE,uDAA6B,CAAC,CAAC;QAE7D,UAAU;QACV,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAErB,OAAO,IAAI,CAAC;IACb,CAAC;CACD,CAAA;AAxFY,mBAAmB;IAD/B,cAAG,CAAC,0CAAyB,EAAE,6CAAwB,CAAC;GAC5C,mBAAmB,CAwF/B;AAxFY,kDAAmB","sourcesContent":["import type { APIApplicationCommandOption } from 'discord-api-types/v9';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription';\nimport { SharedSlashCommandOptions } from './mixins/CommandOptions';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands';\n\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this slash command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this slash command\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options of this slash command\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * **Note:** Calling this function will validate required properties based on their conditions.\n\t */\n\tpublic toJSON() {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tdescription: this.description,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command\n\t * @param input A function that returns a subcommand group builder, or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandGroupsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Make sure there is no subcommand at the root level - if there is, throw\n\t\tconst hasSubcommands = options.some((item) => item instanceof SlashCommandSubcommandBuilder);\n\t\tif (hasSubcommands) throw new RangeError(`You cannot mix subcommands and subcommand groups at the root level.`);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command\n\t * @param input A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Make sure there is no subcommand at the root level - if there is, throw\n\t\tconst hasSubcommandGroups = options.some((item) => itLine truncated
|
||||
Generated
Vendored
-64
@@ -1,64 +0,0 @@
|
||||
import { ApplicationCommandOptionType } from 'discord-api-types/v9';
|
||||
import { SharedSlashCommandOptions } from './mixins/CommandOptions';
|
||||
import { SharedNameAndDescription } from './mixins/NameAndDescription';
|
||||
import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder';
|
||||
/**
|
||||
* Represents a folder for subcommands
|
||||
*
|
||||
* For more information, go to https://discord.com/developers/docs/interactions/slash-commands#subcommands-and-subcommand-groups
|
||||
*/
|
||||
export declare class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {
|
||||
/**
|
||||
* The name of this subcommand group
|
||||
*/
|
||||
readonly name: string;
|
||||
/**
|
||||
* The description of this subcommand group
|
||||
*/
|
||||
readonly description: string;
|
||||
/**
|
||||
* The subcommands part of this subcommand group
|
||||
*/
|
||||
readonly options: ToAPIApplicationCommandOptions[];
|
||||
/**
|
||||
* Adds a new subcommand to this group
|
||||
* @param input A function that returns a subcommand builder, or an already built builder
|
||||
*/
|
||||
addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): this;
|
||||
toJSON(): {
|
||||
type: ApplicationCommandOptionType;
|
||||
name: string;
|
||||
description: string;
|
||||
options: import("discord-api-types/v9").APIApplicationCommandOption[];
|
||||
};
|
||||
}
|
||||
export interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {
|
||||
}
|
||||
/**
|
||||
* Represents a subcommand
|
||||
*
|
||||
* For more information, go to https://discord.com/developers/docs/interactions/slash-commands#subcommands-and-subcommand-groups
|
||||
*/
|
||||
export declare class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {
|
||||
/**
|
||||
* The name of this subcommand
|
||||
*/
|
||||
readonly name: string;
|
||||
/**
|
||||
* The description of this subcommand
|
||||
*/
|
||||
readonly description: string;
|
||||
/**
|
||||
* The options of this subcommand
|
||||
*/
|
||||
readonly options: ToAPIApplicationCommandOptions[];
|
||||
toJSON(): {
|
||||
type: ApplicationCommandOptionType;
|
||||
name: string;
|
||||
description: string;
|
||||
options: import("discord-api-types/v9").APIApplicationCommandOption[];
|
||||
};
|
||||
}
|
||||
export interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions<false> {
|
||||
}
|
||||
//# sourceMappingURL=SlashCommandSubcommands.d.ts.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"SlashCommandSubcommands.d.ts","sourceRoot":"/","sources":["interactions/slashCommands/SlashCommandSubcommands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAGpE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AAE5E;;;;GAIG;AACH,qBACa,kCAAmC,YAAW,8BAA8B;IACxF;;OAEG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAc;IAE1C;;OAEG;IACH,SAAgB,WAAW,EAAE,MAAM,CAAc;IAEjD;;OAEG;IACH,SAAgB,OAAO,EAAE,8BAA8B,EAAE,CAAM;IAE/D;;;OAGG;IACI,aAAa,CACnB,KAAK,EACF,6BAA6B,GAC7B,CAAC,CAAC,eAAe,EAAE,6BAA6B,KAAK,6BAA6B,CAAC;IAkBhF,MAAM;;;;;;CASb;AAED,MAAM,WAAW,kCAAmC,SAAQ,wBAAwB;CAAG;AAEvF;;;;GAIG;AACH,qBACa,6BAA8B,YAAW,8BAA8B;IACnF;;OAEG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAc;IAE1C;;OAEG;IACH,SAAgB,WAAW,EAAE,MAAM,CAAc;IAEjD;;OAEG;IACH,SAAgB,OAAO,EAAE,8BAA8B,EAAE,CAAM;IAExD,MAAM;;;;;;CASb;AAED,MAAM,WAAW,6BAA8B,SAAQ,wBAAwB,EAAE,yBAAyB,CAAC,KAAK,CAAC;CAAG"}
|
||||
Generated
Vendored
-123
@@ -1,123 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SlashCommandSubcommandBuilder = exports.SlashCommandSubcommandGroupBuilder = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
require("discord-api-types/v9");
|
||||
const ts_mixer_1 = require("ts-mixer");
|
||||
const Assertions_1 = require("./Assertions");
|
||||
const CommandOptions_1 = require("./mixins/CommandOptions");
|
||||
const NameAndDescription_1 = require("./mixins/NameAndDescription");
|
||||
/**
|
||||
* Represents a folder for subcommands
|
||||
*
|
||||
* For more information, go to https://discord.com/developers/docs/interactions/slash-commands#subcommands-and-subcommand-groups
|
||||
*/
|
||||
let SlashCommandSubcommandGroupBuilder = class SlashCommandSubcommandGroupBuilder {
|
||||
constructor() {
|
||||
/**
|
||||
* The name of this subcommand group
|
||||
*/
|
||||
Object.defineProperty(this, "name", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: undefined
|
||||
});
|
||||
/**
|
||||
* The description of this subcommand group
|
||||
*/
|
||||
Object.defineProperty(this, "description", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: undefined
|
||||
});
|
||||
/**
|
||||
* The subcommands part of this subcommand group
|
||||
*/
|
||||
Object.defineProperty(this, "options", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: []
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Adds a new subcommand to this group
|
||||
* @param input A function that returns a subcommand builder, or an already built builder
|
||||
*/
|
||||
addSubcommand(input) {
|
||||
const { options } = this;
|
||||
// First, assert options conditions - we cannot have more than 25 options
|
||||
Assertions_1.validateMaxOptionsLength(options);
|
||||
// Get the final result
|
||||
const result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;
|
||||
Assertions_1.assertReturnOfBuilder(result, SlashCommandSubcommandBuilder);
|
||||
// Push it
|
||||
options.push(result);
|
||||
return this;
|
||||
}
|
||||
toJSON() {
|
||||
Assertions_1.validateRequiredParameters(this.name, this.description, this.options);
|
||||
return {
|
||||
type: 2 /* SubcommandGroup */,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
options: this.options.map((option) => option.toJSON()),
|
||||
};
|
||||
}
|
||||
};
|
||||
SlashCommandSubcommandGroupBuilder = tslib_1.__decorate([
|
||||
ts_mixer_1.mix(NameAndDescription_1.SharedNameAndDescription)
|
||||
], SlashCommandSubcommandGroupBuilder);
|
||||
exports.SlashCommandSubcommandGroupBuilder = SlashCommandSubcommandGroupBuilder;
|
||||
/**
|
||||
* Represents a subcommand
|
||||
*
|
||||
* For more information, go to https://discord.com/developers/docs/interactions/slash-commands#subcommands-and-subcommand-groups
|
||||
*/
|
||||
let SlashCommandSubcommandBuilder = class SlashCommandSubcommandBuilder {
|
||||
constructor() {
|
||||
/**
|
||||
* The name of this subcommand
|
||||
*/
|
||||
Object.defineProperty(this, "name", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: undefined
|
||||
});
|
||||
/**
|
||||
* The description of this subcommand
|
||||
*/
|
||||
Object.defineProperty(this, "description", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: undefined
|
||||
});
|
||||
/**
|
||||
* The options of this subcommand
|
||||
*/
|
||||
Object.defineProperty(this, "options", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: []
|
||||
});
|
||||
}
|
||||
toJSON() {
|
||||
Assertions_1.validateRequiredParameters(this.name, this.description, this.options);
|
||||
return {
|
||||
type: 1 /* Subcommand */,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
options: this.options.map((option) => option.toJSON()),
|
||||
};
|
||||
}
|
||||
};
|
||||
SlashCommandSubcommandBuilder = tslib_1.__decorate([
|
||||
ts_mixer_1.mix(NameAndDescription_1.SharedNameAndDescription, CommandOptions_1.SharedSlashCommandOptions)
|
||||
], SlashCommandSubcommandBuilder);
|
||||
exports.SlashCommandSubcommandBuilder = SlashCommandSubcommandBuilder;
|
||||
//# sourceMappingURL=SlashCommandSubcommands.js.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"SlashCommandSubcommands.js","sourceRoot":"/","sources":["interactions/slashCommands/SlashCommandSubcommands.ts"],"names":[],"mappings":";;;;AAAA,gCAAoE;AACpE,uCAA+B;AAC/B,6CAA2G;AAC3G,4DAAoE;AACpE,oEAAuE;AAGvE;;;;GAIG;AAEH,IAAa,kCAAkC,GAA/C,MAAa,kCAAkC;IAA/C;QACC;;WAEG;QACH;;;;mBAA+B,SAAU;WAAC;QAE1C;;WAEG;QACH;;;;mBAAsC,SAAU;WAAC;QAEjD;;WAEG;QACH;;;;mBAA4D,EAAE;WAAC;IAoChE,CAAC;IAlCA;;;OAGG;IACI,aAAa,CACnB,KAEsF;QAEtF,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,yEAAyE;QACzE,qCAAwB,CAAC,OAAO,CAAC,CAAC;QAElC,uBAAuB;QACvB,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,6BAA6B,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QAEhG,kCAAqB,CAAC,MAAM,EAAE,6BAA6B,CAAC,CAAC;QAE7D,UAAU;QACV,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAErB,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,MAAM;QACZ,uCAA0B,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACtE,OAAO;YACN,IAAI,yBAA8C;YAClD,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;SACtD,CAAC;IACH,CAAC;CACD,CAAA;AAlDY,kCAAkC;IAD9C,cAAG,CAAC,6CAAwB,CAAC;GACjB,kCAAkC,CAkD9C;AAlDY,gFAAkC;AAsD/C;;;;GAIG;AAEH,IAAa,6BAA6B,GAA1C,MAAa,6BAA6B;IAA1C;QACC;;WAEG;QACH;;;;mBAA+B,SAAU;WAAC;QAE1C;;WAEG;QACH;;;;mBAAsC,SAAU;WAAC;QAEjD;;WAEG;QACH;;;;mBAA4D,EAAE;WAAC;IAWhE,CAAC;IATO,MAAM;QACZ,uCAA0B,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACtE,OAAO;YACN,IAAI,oBAAyC;YAC7C,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;SACtD,CAAC;IACH,CAAC;CACD,CAAA;AAzBY,6BAA6B;IADzC,cAAG,CAAC,6CAAwB,EAAE,0CAAyB,CAAC;GAC5C,6BAA6B,CAyBzC;AAzBY,sEAA6B","sourcesContent":["import { ApplicationCommandOptionType } from 'discord-api-types/v9';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions';\nimport { SharedSlashCommandOptions } from './mixins/CommandOptions';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder';\n\n/**\n * Represents a folder for subcommands\n *\n * For more information, go to https://discord.com/developers/docs/interactions/slash-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands part of this subcommand group\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group\n\t * @param input A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON() {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tdescription: this.description,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * Represents a subcommand\n *\n * For more information, go to https://discord.com/developers/docs/interactions/slash-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options of this subcommand\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\tpublic toJSON() {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tdescription: this.description,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilLine truncated
|
||||
Generated
Vendored
-20
@@ -1,20 +0,0 @@
|
||||
import type { ApplicationCommandOptionType } from 'discord-api-types/v9';
|
||||
import type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';
|
||||
import { SharedNameAndDescription } from './NameAndDescription';
|
||||
export declare class SlashCommandOptionBase extends SharedNameAndDescription implements ToAPIApplicationCommandOptions {
|
||||
required: boolean;
|
||||
readonly type: ApplicationCommandOptionType;
|
||||
constructor(type: ApplicationCommandOptionType);
|
||||
/**
|
||||
* Marks the option as required
|
||||
* @param required If this option should be required
|
||||
*/
|
||||
setRequired(required: boolean): this;
|
||||
toJSON(): {
|
||||
type: ApplicationCommandOptionType;
|
||||
name: string;
|
||||
description: string;
|
||||
required: boolean;
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=CommandOptionBase.d.ts.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"CommandOptionBase.d.ts","sourceRoot":"/","sources":["interactions/slashCommands/mixins/CommandOptionBase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAGzE,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE,qBAAa,sBAAuB,SAAQ,wBAAyB,YAAW,8BAA8B;IACtG,QAAQ,UAAS;IACxB,SAAgB,IAAI,EAAE,4BAA4B,CAAC;gBAEhC,IAAI,EAAE,4BAA4B;IAKrD;;;OAGG;IACI,WAAW,CAAC,QAAQ,EAAE,OAAO;IAS7B,MAAM;;;;;;CAab"}
|
||||
Generated
Vendored
-48
@@ -1,48 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SlashCommandOptionBase = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const ow_1 = tslib_1.__importDefault(require("ow"));
|
||||
const Assertions_1 = require("../Assertions");
|
||||
const NameAndDescription_1 = require("./NameAndDescription");
|
||||
class SlashCommandOptionBase extends NameAndDescription_1.SharedNameAndDescription {
|
||||
constructor(type) {
|
||||
super();
|
||||
Object.defineProperty(this, "required", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: false
|
||||
});
|
||||
Object.defineProperty(this, "type", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: void 0
|
||||
});
|
||||
this.type = type;
|
||||
}
|
||||
/**
|
||||
* Marks the option as required
|
||||
* @param required If this option should be required
|
||||
*/
|
||||
setRequired(required) {
|
||||
// Assert that you actually passed a boolean
|
||||
ow_1.default(required, 'required', ow_1.default.boolean);
|
||||
this.required = required;
|
||||
return this;
|
||||
}
|
||||
toJSON() {
|
||||
Assertions_1.validateRequiredParameters(this.name, this.description, []);
|
||||
// Assert that you actually passed a boolean
|
||||
ow_1.default(this.required, 'required', ow_1.default.boolean);
|
||||
return {
|
||||
type: this.type,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
required: this.required,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.SlashCommandOptionBase = SlashCommandOptionBase;
|
||||
//# sourceMappingURL=CommandOptionBase.js.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"CommandOptionBase.js","sourceRoot":"/","sources":["interactions/slashCommands/mixins/CommandOptionBase.ts"],"names":[],"mappings":";;;;AACA,oDAAoB;AACpB,8CAA2D;AAE3D,6DAAgE;AAEhE,MAAa,sBAAuB,SAAQ,6CAAwB;IAInE,YAAmB,IAAkC;QACpD,KAAK,EAAE,CAAC;QAJT;;;;mBAAkB,KAAK;WAAC;QACxB;;;;;WAAmD;QAIlD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED;;;OAGG;IACI,WAAW,CAAC,QAAiB;QACnC,4CAA4C;QAC5C,YAAE,CAAC,QAAQ,EAAE,UAAU,EAAE,YAAE,CAAC,OAAO,CAAC,CAAC;QAErC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,OAAO,IAAI,CAAC;IACb,CAAC;IAEM,MAAM;QACZ,uCAA0B,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QAE5D,4CAA4C;QAC5C,YAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,UAAU,EAAE,YAAE,CAAC,OAAO,CAAC,CAAC;QAE1C,OAAO;YACN,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACvB,CAAC;IACH,CAAC;CACD;AAnCD,wDAmCC","sourcesContent":["import type { ApplicationCommandOptionType } from 'discord-api-types/v9';\nimport ow from 'ow';\nimport { validateRequiredParameters } from '../Assertions';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SharedNameAndDescription } from './NameAndDescription';\n\nexport class SlashCommandOptionBase extends SharedNameAndDescription implements ToAPIApplicationCommandOptions {\n\tpublic required = false;\n\tpublic readonly type: ApplicationCommandOptionType;\n\n\tpublic constructor(type: ApplicationCommandOptionType) {\n\t\tsuper();\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * Marks the option as required\n\t * @param required If this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tow(required, 'required', ow.boolean);\n\n\t\tthis.required = required;\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Assert that you actually passed a boolean\n\t\tow(this.required, 'required', ow.boolean);\n\n\t\treturn {\n\t\t\ttype: this.type,\n\t\t\tname: this.name,\n\t\t\tdescription: this.description,\n\t\t\trequired: this.required,\n\t\t};\n\t}\n}\n"]}
|
||||
Generated
Vendored
-25
@@ -1,25 +0,0 @@
|
||||
import { APIApplicationCommandOptionChoice, ApplicationCommandOptionType } from 'discord-api-types/v9';
|
||||
import type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';
|
||||
import { SlashCommandOptionBase } from './CommandOptionBase';
|
||||
export declare abstract class ApplicationCommandOptionWithChoicesBase<T extends string | number> extends SlashCommandOptionBase implements ToAPIApplicationCommandOptions {
|
||||
choices?: APIApplicationCommandOptionChoice[];
|
||||
/**
|
||||
* Adds a choice for this option
|
||||
* @param name The name of the choice
|
||||
* @param value The value of the choice
|
||||
*/
|
||||
addChoice(name: string, value: T): this;
|
||||
/**
|
||||
* Adds multiple choices for this option
|
||||
* @param choices The choices to add
|
||||
*/
|
||||
addChoices(choices: [name: string, value: T][]): this;
|
||||
toJSON(): {
|
||||
choices: APIApplicationCommandOptionChoice[] | undefined;
|
||||
type: ApplicationCommandOptionType;
|
||||
name: string;
|
||||
description: string;
|
||||
required: boolean;
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=CommandOptionWithChoices.d.ts.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"CommandOptionWithChoices.d.ts","sourceRoot":"/","sources":["interactions/slashCommands/mixins/CommandOptionWithChoices.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAGvG,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAU7D,8BAAsB,uCAAuC,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,CACtF,SAAQ,sBACR,YAAW,8BAA8B;IAElC,OAAO,CAAC,EAAE,iCAAiC,EAAE,CAAC;IAErD;;;;OAIG;IACI,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IAqBvC;;;OAGG;IACI,UAAU,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,EAAE;IAWrC,MAAM;;;;;;;CAMtB"}
|
||||
Generated
Vendored
-59
@@ -1,59 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ApplicationCommandOptionWithChoicesBase = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
require("discord-api-types/v9");
|
||||
const ow_1 = tslib_1.__importDefault(require("ow"));
|
||||
const Assertions_1 = require("../Assertions");
|
||||
const CommandOptionBase_1 = require("./CommandOptionBase");
|
||||
const stringPredicate = ow_1.default.string.minLength(1).maxLength(100);
|
||||
const integerPredicate = ow_1.default.number.finite;
|
||||
// TODO: See resolution for sindresorhus/ow#217 in relation to this cast
|
||||
const choicesPredicate = ow_1.default.array.ofType(ow_1.default.array.exactShape([stringPredicate, ow_1.default.any(ow_1.default.string, integerPredicate)]));
|
||||
class ApplicationCommandOptionWithChoicesBase extends CommandOptionBase_1.SlashCommandOptionBase {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
Object.defineProperty(this, "choices", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: void 0
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Adds a choice for this option
|
||||
* @param name The name of the choice
|
||||
* @param value The value of the choice
|
||||
*/
|
||||
addChoice(name, value) {
|
||||
this.choices ?? (this.choices = []);
|
||||
Assertions_1.validateMaxChoicesLength(this.choices);
|
||||
// Validate name
|
||||
ow_1.default(name, `${this.type === 3 /* String */ ? 'string' : 'integer'} choice name`, stringPredicate);
|
||||
// Validate the value
|
||||
if (this.type === 3 /* String */)
|
||||
ow_1.default(value, 'string choice value', stringPredicate);
|
||||
else
|
||||
ow_1.default(value, 'integer choice value', integerPredicate);
|
||||
this.choices.push({ name, value });
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds multiple choices for this option
|
||||
* @param choices The choices to add
|
||||
*/
|
||||
addChoices(choices) {
|
||||
ow_1.default(choices, `${this.type === 3 /* String */ ? 'string' : 'integer'} choices`, choicesPredicate);
|
||||
for (const [label, value] of choices)
|
||||
this.addChoice(label, value);
|
||||
return this;
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
...super.toJSON(),
|
||||
choices: this.choices,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.ApplicationCommandOptionWithChoicesBase = ApplicationCommandOptionWithChoicesBase;
|
||||
//# sourceMappingURL=CommandOptionWithChoices.js.map
|
||||
Generated
Vendored
-1
@@ -1 +0,0 @@
|
||||
{"version":3,"file":"CommandOptionWithChoices.js","sourceRoot":"/","sources":["interactions/slashCommands/mixins/CommandOptionWithChoices.ts"],"names":[],"mappings":";;;;AAAA,gCAAuG;AACvG,oDAAmC;AACnC,8CAAyD;AAEzD,2DAA6D;AAE7D,MAAM,eAAe,GAAG,YAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAC9D,MAAM,gBAAgB,GAAG,YAAE,CAAC,MAAM,CAAC,MAAM,CAAC;AAE1C,wEAAwE;AACxE,MAAM,gBAAgB,GAAG,YAAE,CAAC,KAAK,CAAC,MAAM,CACvC,YAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,eAAe,EAAE,YAAE,CAAC,GAAG,CAAC,YAAE,CAAC,MAAM,EAAE,gBAAgB,CAA0C,CAAC,CAAC,CACpH,CAAC;AAEF,MAAsB,uCACrB,SAAQ,0CAAsB;IAD/B;;QAIC;;;;;WAAqD;IAiDtD,CAAC;IA/CA;;;;OAIG;IACI,SAAS,CAAC,IAAY,EAAE,KAAQ;QACtC,IAAI,CAAC,OAAO,KAAZ,IAAI,CAAC,OAAO,GAAK,EAAE,EAAC;QAEpB,qCAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAEvC,gBAAgB;QAChB,YAAE,CACD,IAAI,EACJ,GAAG,IAAI,CAAC,IAAI,mBAAwC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,cAAc,EACzF,eAAe,CACf,CAAC;QAEF,qBAAqB;QACrB,IAAI,IAAI,CAAC,IAAI,mBAAwC;YAAE,YAAE,CAAC,KAAK,EAAE,qBAAqB,EAAE,eAAe,CAAC,CAAC;;YACpG,YAAE,CAAC,KAAK,EAAE,sBAAsB,EAAE,gBAAgB,CAAC,CAAC;QAEzD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAEnC,OAAO,IAAI,CAAC;IACb,CAAC;IAED;;;OAGG;IACI,UAAU,CAAC,OAAmC;QACpD,YAAE,CACD,OAAO,EACP,GAAG,IAAI,CAAC,IAAI,mBAAwC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,UAAU,EACrF,gBAAgB,CAChB,CAAC;QAEF,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,OAAO;YAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO,IAAI,CAAC;IACb,CAAC;IAEe,MAAM;QACrB,OAAO;YACN,GAAG,KAAK,CAAC,MAAM,EAAE;YACjB,OAAO,EAAE,IAAI,CAAC,OAAO;SACrB,CAAC;IACH,CAAC;CACD;AArDD,0FAqDC","sourcesContent":["import { APIApplicationCommandOptionChoice, ApplicationCommandOptionType } from 'discord-api-types/v9';\nimport ow, { Predicate } from 'ow';\nimport { validateMaxChoicesLength } from '../Assertions';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandOptionBase } from './CommandOptionBase';\n\nconst stringPredicate = ow.string.minLength(1).maxLength(100);\nconst integerPredicate = ow.number.finite;\n\n// TODO: See resolution for sindresorhus/ow#217 in relation to this cast\nconst choicesPredicate = ow.array.ofType<[string, string | number]>(\n\tow.array.exactShape([stringPredicate, ow.any(ow.string, integerPredicate) as unknown as Predicate<string | number>]),\n);\n\nexport abstract class ApplicationCommandOptionWithChoicesBase<T extends string | number>\n\textends SlashCommandOptionBase\n\timplements ToAPIApplicationCommandOptions\n{\n\tpublic choices?: APIApplicationCommandOptionChoice[];\n\n\t/**\n\t * Adds a choice for this option\n\t * @param name The name of the choice\n\t * @param value The value of the choice\n\t */\n\tpublic addChoice(name: string, value: T) {\n\t\tthis.choices ??= [];\n\n\t\tvalidateMaxChoicesLength(this.choices);\n\n\t\t// Validate name\n\t\tow(\n\t\t\tname,\n\t\t\t`${this.type === ApplicationCommandOptionType.String ? 'string' : 'integer'} choice name`,\n\t\t\tstringPredicate,\n\t\t);\n\n\t\t// Validate the value\n\t\tif (this.type === ApplicationCommandOptionType.String) ow(value, 'string choice value', stringPredicate);\n\t\telse ow(value, 'integer choice value', integerPredicate);\n\n\t\tthis.choices.push({ name, value });\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds multiple choices for this option\n\t * @param choices The choices to add\n\t */\n\tpublic addChoices(choices: [name: string, value: T][]) {\n\t\tow(\n\t\t\tchoices,\n\t\t\t`${this.type === ApplicationCommandOptionType.String ? 'string' : 'integer'} choices`,\n\t\t\tchoicesPredicate,\n\t\t);\n\n\t\tfor (const [label, value] of choices) this.addChoice(label, value);\n\t\treturn this;\n\t}\n\n\tpublic override toJSON() {\n\t\treturn {\n\t\t\t...super.toJSON(),\n\t\t\tchoices: this.choices,\n\t\t};\n\t}\n}\n"]}
|
||||
Loaded 100 of 1318 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user