This commit is contained in:
st committed 2026-06-28 21:55:39 -05:00
commit 105dd2dc4d
16 files changed
+1393 -34498

No files matched your search

+8 -8
View File
@@ -1,8 +1,8 @@
# Discord Bot Token — get yours at https://discord.com/developers/applications # Discord Bot Token — get yours at https://discord.com/developers/applications
BOT_TOKEN=your_bot_token_here BOT_TOKEN=your_bot_token_here
# Command prefix (default: !) # Command prefix (default: !)
PREFIX=! PREFIX=!
# Guild ID for test server (optional — used for dev utilities) # Guild ID for test server (optional — used for dev utilities)
GUILD_ID=your_guild_id_here GUILD_ID=your_guild_id_here
+3 -1
View File
@@ -141,4 +141,6 @@ dist
# Vite logs files # Vite logs files
vite.config.js.timestamp-* vite.config.js.timestamp-*
vite.config.ts.timestamp-*
items.json
db.json
+121 -121
View File
@@ -1,121 +1,121 @@
# twitter (v3) # twitter (v3)
a discord.js v14 moderation (+ more) bot a discord.js v14 moderation (+ more) bot
--- ---
## features ## features
- prefix command system — commands triggered by a configurable prefix (default `!`) - prefix command system — commands triggered by a configurable prefix (default `!`)
- auto-loading — commands and events are loaded automatically from their folders - auto-loading — commands and events are loaded automatically from their folders
- aliases — each command can define one or more aliases - aliases — each command can define one or more aliases
- winston logging — coloured console output + rolling log files (`logs/combined.log`, `logs/error.log`) - winston logging — coloured console output + rolling log files (`logs/combined.log`, `logs/error.log`)
- global error handling — unhandled rejections and uncaught exceptions are caught and logged - global error handling — unhandled rejections and uncaught exceptions are caught and logged
--- ---
## project structure ## project structure
``` ```
src/ src/
├── index.js # entry point — creates the client, loads handlers ├── index.js # entry point — creates the client, loads handlers
├── commands/ ├── commands/
│ ├── help.js # !help — lists commands or shows command detail │ ├── help.js # !help — lists commands or shows command detail
│ └── ping.js # !ping — latency check │ └── ping.js # !ping — latency check
├── events/ ├── events/
│ ├── ready.js # fires once when the bot is online │ ├── ready.js # fires once when the bot is online
│ └── messageCreate.js # parses every message for prefix commands │ └── messageCreate.js # parses every message for prefix commands
├── handlers/ ├── handlers/
│ ├── commandHandler.js # reads src/commands/ and registers commands │ ├── commandHandler.js # reads src/commands/ and registers commands
│ └── eventHandler.js # reads src/events/ and registers discord events │ └── eventHandler.js # reads src/events/ and registers discord events
└── utils/ └── utils/
└── logger.js # winston logger instance └── logger.js # winston logger instance
logs/ # created automatically at runtime (git-ignored) logs/ # created automatically at runtime (git-ignored)
``` ```
--- ---
## setup ## setup
### 1. clone & install dependencies ### 1. clone & install dependencies
```bash ```bash
git clone https://github.com/yhqe/twitter_v3.git git clone https://github.com/yhqe/twitter_v3.git
cd twitter_v3 cd twitter_v3
npm install npm install
``` ```
### 2. configure environment variables ### 2. configure environment variables
```bash ```bash
cp .env.example .env cp .env.example .env
``` ```
open `.env` and fill in: open `.env` and fill in:
| variable | required | description | | variable | required | description |
|-------------|----------|------------------------------------------------------| |-------------|----------|------------------------------------------------------|
| `BOT_TOKEN` | yes | your bot token from the discord developer portal | | `BOT_TOKEN` | yes | your bot token from the discord developer portal |
| `PREFIX` | no | command prefix (default: `!`) | | `PREFIX` | no | command prefix (default: `!`) |
| `GUILD_ID` | no | test server id (handy for dev stuff) | | `GUILD_ID` | no | test server id (handy for dev stuff) |
### 3. enable the message content intent ### 3. enable the message content intent
go to your application in the [discord developer portal](https://discord.com/developers/applications), open **bot → privileged gateway intents**, and enable **message content intent**. you need this for prefix commands. go to your application in the [discord developer portal](https://discord.com/developers/applications), open **bot → privileged gateway intents**, and enable **message content intent**. you need this for prefix commands.
### 4. start the bot ### 4. start the bot
```bash ```bash
# production # production
npm start npm start
# development (auto-restarts on file changes, node.js 18+) # development (auto-restarts on file changes, node.js 18+)
npm run dev npm run dev
``` ```
--- ---
## adding commands ## adding commands
create a file in `src/commands/`. the handler will load it automatically on next start. create a file in `src/commands/`. the handler will load it automatically on next start.
```js ```js
'use strict'; 'use strict';
module.exports = { module.exports = {
name: 'example', // primary command name (also used as the key) name: 'example', // primary command name (also used as the key)
description: 'An example command.', description: 'An example command.',
aliases: ['ex'], // optional aliases aliases: ['ex'], // optional aliases
usage: 'example <text>', // shown in !help example usage: 'example <text>', // shown in !help example
async execute(client, message, args) { async execute(client, message, args) {
await message.reply(`You said: ${args.join(' ')}`); await message.reply(`You said: ${args.join(' ')}`);
}, },
}; };
``` ```
## adding events ## adding events
create a file in `src/events/`. set `once: true` if it should fire only once (e.g. `ready`). create a file in `src/events/`. set `once: true` if it should fire only once (e.g. `ready`).
```js ```js
'use strict'; 'use strict';
const { Events } = require('discord.js'); const { Events } = require('discord.js');
module.exports = { module.exports = {
name: Events.GuildMemberAdd, name: Events.GuildMemberAdd,
async execute(client, member) { async execute(client, member) {
console.log(`${member.user.tag} joined ${member.guild.name}`); console.log(`${member.user.tag} joined ${member.guild.name}`);
}, },
}; };
``` ```
--- ---
## logging ## logging
log files are written to the `logs/` directory (git-ignored). the log level defaults to `info` and can be overridden with the `LOG_LEVEL` environment variable (e.g. `LOG_LEVEL=debug npm start`). log files are written to the `logs/` directory (git-ignored). the log level defaults to `info` and can be overridden with the `LOG_LEVEL` environment variable (e.g. `LOG_LEVEL=debug npm start`).
-11
View File
@@ -1,11 +0,0 @@
{
"autoroles": {
"1133441692196950101": "1192595134026616894"
},
"autobans": {
"1133441692196950101": "1264634623950848158"
},
"prefixes": {
"1362160460253761536": "*"
}
}
-33156
View File
File diff suppressed because it is too large. Load diff
+609 -609
View File
File diff suppressed because it is too large. Load diff
+139 -139
View File
@@ -1,139 +1,139 @@
'use strict'; 'use strict';
const { time } = require("discord.js"); const { time } = require("discord.js");
const logger = require('../../utils/logger'); const logger = require('../../utils/logger');
async function getAvailableCapes(username) { async function getAvailableCapes(username) {
const capes =[]; const capes =[];
const mojangReq = await Promise.allSettled([ const mojangReq = await Promise.allSettled([
fetch(`https://api.ashcon.app/mojang/v2/user/${username}`), fetch(`https://api.ashcon.app/mojang/v2/user/${username}`),
]); ]);
if (mojangReq.status === 'fulfilled' && mojangReq.value.ok) { if (mojangReq.status === 'fulfilled' && mojangReq.value.ok) {
const mojangData = await mojangReq.value.json(); const mojangData = await mojangReq.value.json();
if (mojangData.textures && mojangData.textures.cape) { if (mojangData.textures && mojangData.textures.cape) {
capes.push({ capes.push({
source: 'Official (Equipped)', source: 'Official (Equipped)',
url: mojangData.textures.cape.url url: mojangData.textures.cape.url
}); });
} }
} }
return capes; return capes;
} }
module.exports = { module.exports = {
name: 'mc', name: 'mc',
description: `request different information about a minecraft user`, description: `request different information about a minecraft user`,
aliases: ['minecraft'], aliases: ['minecraft'],
usage: 'mc <username>', usage: 'mc <username>',
async execute(client, message, args) { async execute(client, message, args) {
var embed; var embed;
let sent = await message.reply({ let sent = await message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
title: '', title: '',
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: '<a:loading_icon:1366587619890302998> fetching...', description: '<a:loading_icon:1366587619890302998> fetching...',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
const username = args[0]; const username = args[0];
if (!username) { if (!username) {
embed = { embed = {
color: 0x8aa2b3, color: 0x8aa2b3,
title: '', title: '',
description: '<:no:1481811955592466492> please provide a valid minecraft username!', description: '<:no:1481811955592466492> please provide a valid minecraft username!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}; };
return await sent.edit({ content: null, embeds: [embed] }); return await sent.edit({ content: null, embeds: [embed] });
} }
const uuid_res = await fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`); const uuid_res = await fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`);
const uuid = await uuid_res.json().then(res => res.id).catch(err => { const uuid = await uuid_res.json().then(res => res.id).catch(err => {
embed = { embed = {
color: 0x8aa2b3, color: 0x8aa2b3,
title: '', title: '',
description: '<:no:1481811955592466492> cannot fetch uuid!', description: '<:no:1481811955592466492> cannot fetch uuid!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}; };
return null; return null;
}); });
const res = await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`); const res = await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`);
const data = await res.json().then(res => res).catch(err => { const data = await res.json().then(res => res).catch(err => {
embed = { embed = {
color: 0x8aa2b3, color: 0x8aa2b3,
title: '', title: '',
description: '<:no:1481811955592466492> cannot fetch data!', description: '<:no:1481811955592466492> cannot fetch data!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}; };
return null; return null;
}); });
getAvailableCapes(`${data.name}`).then(capes => { getAvailableCapes(`${data.name}`).then(capes => {
logger.debug(`found ${capes.length} cape(s):`); logger.debug(`found ${capes.length} cape(s):`);
logger.debug(capes); logger.debug(capes);
}); });
if (!data) return await sent.edit({ content: null, embeds: [embed] }); if (!data) return await sent.edit({ content: null, embeds: [embed] });
const skin = await fetch (`https://minotar.net/helm/${data.name}/420.png`).then(res => res.url).catch(err => null); const skin = await fetch (`https://minotar.net/helm/${data.name}/420.png`).then(res => res.url).catch(err => null);
const capes = data.properties[0].value; const capes = data.properties[0].value;
const decoded_capes = Buffer.from(capes, 'base64').toString('utf-8'); const decoded_capes = Buffer.from(capes, 'base64').toString('utf-8');
const cape_url = JSON.parse(decoded_capes).textures.CAPE ? JSON.parse(decoded_capes).textures.CAPE.url : null; const cape_url = JSON.parse(decoded_capes).textures.CAPE ? JSON.parse(decoded_capes).textures.CAPE.url : null;
logger.debug(`[mc] fetched data for "${username}": ${JSON.stringify(data)}`); logger.debug(`[mc] fetched data for "${username}": ${JSON.stringify(data)}`);
logger.debug(`[mc] fetched cape data for "${username}": ${JSON.stringify(cape_url)}`); logger.debug(`[mc] fetched cape data for "${username}": ${JSON.stringify(cape_url)}`);
embed = { embed = {
color: 0x8aa2b3, color: 0x8aa2b3,
title: '', title: '',
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: `**[${data.name}](https://namemc.com/profile/${data.name})**`, description: `**[${data.name}](https://namemc.com/profile/${data.name})**`,
fields: [ fields: [
{ name: 'uuid', value: `${data.id}`, inline: true }, { name: 'uuid', value: `${data.id}`, inline: true },
], ],
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
thumbnail: { thumbnail: {
url: skin, url: skin,
height: 1024, height: 1024,
width: 1024, width: 1024,
}, },
}; };
await sent.edit({ content: null, embeds: [embed] }); await sent.edit({ content: null, embeds: [embed] });
}, },
}; };
+1 -43
View File
@@ -48,7 +48,7 @@ module.exports = {
name: 'rbx', name: 'rbx',
description: `various commands related to roblox`, description: `various commands related to roblox`,
aliases: ['roblox'], aliases: ['roblox'],
usage: `rbx user <username>\n${env.PREFIX}rbx item <item id>\n${env.PREFIX}rbx group <group id>\n${env.PREFIX}rbx game <game id>\n${env.PREFIX}rbx avatar <username>`, usage: 'rbx user <username>\n.rbx item <item id>\n.rbx group <group id>\n.rbx game <game id>',
async execute(client, message) { async execute(client, message) {
var embed = {}; var embed = {};
@@ -206,48 +206,6 @@ module.exports = {
timestamp: new Date(), timestamp: new Date(),
} }
} }
} else if (subcommand === 'avatar') {
try {
const user = data.data[0];
const a_res = await fetch(`https://thumbnails.roproxy.com/v1/users/avatar?userIds=${user.id}&size=720x720&format=Png&isCircular=false`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
const a_data = await a_res.json();
logger.debug(`[rbx] fetched avatar for "${argument}": ${JSON.stringify(a_data)}`);
embed = {
color: 0x8aa2b3,
author: {
name: message.author.username,
icon_url: message.author.displayAvatarURL(),
},
description: `**${user.displayName}**'s avatar`,
footer: {
text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(),
},
image: {
url: `${a_data.data[0].imageUrl}`
},
timestamp: new Date(),
};
} catch (err) {
logger.error(`[rbx] failed to fetch avatar for user id "${argument}":`, err);
embed = {
color: 0x8aa2b3,
author: {
name: message.author.username,
icon_url: message.author.displayAvatarURL(),
},
description: `<:no:1481811955592466492> could not fetch avatar data for user "${argument}"!`,
footer: {
text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(),
},
timestamp: new Date(),
};
}
} else if (subcommand === 'item') { } else if (subcommand === 'item') {
try { try {
const res = await fetch(`https://economy.roproxy.com/v2/assets/${argument}/details`, { const res = await fetch(`https://economy.roproxy.com/v2/assets/${argument}/details`, {
+102
View File
@@ -4,6 +4,108 @@ const { time } = require("discord.js");
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
module.exports = {
name: 'autoban',
description: `automatically ban a user if they join the server`,
aliases: ['ab', 'banish'],
usage: 'ban <user> [reason] [duration]',
async execute(client, message, args) {
if (!message.member.permissions.has('BanMembers')) {
return message.reply({
content: null, embeds: [{
color: 0x8aa2b3,
author: {
name: message.author.username,
icon_url: message.author.displayAvatarURL(),
},
description: '<:no:1481811955592466492> you do not have permission to use this command!',
footer: {
text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(),
},
timestamp: new Date(),
}]
});
}
const user = message.mentions.users.first() || await client.users.fetch(args[0]).catch(() => null);
if (!user) {
return message.reply({
content: null, embeds: [{
color: 0x8aa2b3,
author: {
name: message.author.username,
icon_url: message.author.displayAvatarURL(),
},
description: '<:no:1481811955592466492> please specify a user to autoban!',
footer: {
text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(),
},
timestamp: new Date(),
}]
});
}
const reason = args.slice(1).join(' ') || 'autobanned (twitter)';
const dbPath = path.join(__dirname, '..', '..', '..', 'db.json');
let db = {};
if (fs.existsSync(dbPath)) {
db = JSON.parse(fs.readFileSync(dbPath, 'utf8'));
}
if (!db.autobans) {
db.autobans = {};
}
db.autobans[message.guild.id] = user.id;
try {
await fs.writeFileSync(dbPath, JSON.stringify(db, null, 2));
message.reply({
content: null, embeds: [{
color: 0x8aa2b3,
author: {
name: message.author.username,
icon_url: message.author.displayAvatarURL(),
},
description: `<:check:1481811973447356496> ${user.username} has been added to the autoban list!`,
footer: {
text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(),
},
timestamp: new Date(),
}]
});
} catch (error) {
console.error(error);
message.reply({
content: null, embeds: [{
color: 0x8aa2b3,
author: {
name: message.author.username,
icon_url: message.author.displayAvatarURL(),
},
description: '<:no:1481811955592466492> an error occurred while trying to add the user to the autoban list!',
footer: {
text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(),
},
timestamp: new Date(),
}]
});
}
},
};
'use strict';
const { time } = require("discord.js");
const fs = require('fs');
const path = require('path');
module.exports = { module.exports = {
name: 'autoban', name: 'autoban',
description: `automatically ban a user if they join the server`, description: `automatically ban a user if they join the server`,
+2 -2
View File
@@ -5,8 +5,8 @@ const { time } = require("discord.js");
module.exports = { module.exports = {
name: 'ban', name: 'ban',
description: `ban a user from the current server`, description: `ban a user from the current server`,
aliases: ['b'], aliases: ['banish'],
usage: 'ban <user> [reason]', usage: 'ban <user> [reason] [duration]',
async execute(client, message, args) { async execute(client, message, args) {
if (!message.member.permissions.has('BanMembers')) { if (!message.member.permissions.has('BanMembers')) {
+87 -87
View File
@@ -1,88 +1,88 @@
'use strict'; 'use strict';
const { time } = require("discord.js"); const { time } = require("discord.js");
module.exports = { module.exports = {
name: 'kick', name: 'kick',
description: `kick a user from the current server`, description: `kick a user from the current server`,
aliases: ['kick'], aliases: ['kick'],
usage: 'kick <user> [reason]', usage: 'kick <user> [reason]',
async execute(client, message, args) { async execute(client, message, args) {
if (!message.member.permissions.has('KickMembers')) { if (!message.member.permissions.has('KickMembers')) {
return message.reply({ return message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: '<:no:1481811955592466492> you do not have permission to use this command!', description: '<:no:1481811955592466492> you do not have permission to use this command!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
} }
const user = message.mentions.users.first() || client.users.cache.get(args[0]); const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) { if (!user) {
return message.reply({ return message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: '<:no:1481811955592466492> please specify a user to ban!', description: '<:no:1481811955592466492> please specify a user to ban!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
} }
const reason = args.slice(1).join(' ') || 'no reason provided (twitter)'; const reason = args.slice(1).join(' ') || 'no reason provided (twitter)';
const duration = args[2] ? parseInt(args[2]) : null; const duration = args[2] ? parseInt(args[2]) : null;
try { try {
await message.guild.members.kick(user, { reason }); await message.guild.members.kick(user, { reason });
message.reply({ message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: `<:check:1481811973447356496> ${user.username} has been kicked!`, description: `<:check:1481811973447356496> ${user.username} has been kicked!`,
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
message.reply({ message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: '<:no:1481811955592466492> an error occurred while trying to ban the user!', description: '<:no:1481811955592466492> an error occurred while trying to ban the user!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
} }
}, },
}; };
+83 -83
View File
@@ -1,84 +1,84 @@
'use strict'; 'use strict';
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const { time } = require("discord.js"); const { time } = require("discord.js");
module.exports = { module.exports = {
name: 'autorole', name: 'autorole',
description: `assign a role to new members when they join the server`, description: `assign a role to new members when they join the server`,
aliases: ['ar'], aliases: ['ar'],
usage: 'autorole <role>', usage: 'autorole <role>',
async execute(client, message, args) { async execute(client, message, args) {
if (!message.member.permissions.has('Administrator')) { if (!message.member.permissions.has('Administrator')) {
return message.reply({ return message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: '<:no:1481811955592466492> you do not have permission to use this command!', description: '<:no:1481811955592466492> you do not have permission to use this command!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
} }
const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0]); const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0]);
if (!role) { if (!role) {
return message.reply({ return message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: '<:no:1481811955592466492> please provide a valid role!', description: '<:no:1481811955592466492> please provide a valid role!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
} }
// add the role to a json file for the guild and save it to be used when new members join (if the role is already in the database, update it to the new role) // add the role to a json file for the guild and save it to be used when new members join (if the role is already in the database, update it to the new role)
const dbPath = path.join(__dirname, '..', '..', '..', 'db.json'); const dbPath = path.join(__dirname, '..', '..', '..', 'db.json');
let db = {}; let db = {};
if (fs.existsSync(dbPath)) { if (fs.existsSync(dbPath)) {
db = JSON.parse(fs.readFileSync(dbPath, 'utf8')); db = JSON.parse(fs.readFileSync(dbPath, 'utf8'));
} }
if (!db.autoroles) { if (!db.autoroles) {
db.autoroles = {}; db.autoroles = {};
} }
db.autoroles[message.guild.id] = role.id; db.autoroles[message.guild.id] = role.id;
fs.writeFileSync(dbPath, JSON.stringify(db, null, 2)); fs.writeFileSync(dbPath, JSON.stringify(db, null, 2));
message.reply({ message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: `<:check:1481811973447356496> "${role.name}" has been set as the autorole!`, description: `<:check:1481811973447356496> "${role.name}" has been set as the autorole!`,
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}] }]
}); });
} }
}; };
+61 -61
View File
@@ -1,61 +1,61 @@
'use strict'; 'use strict';
const { time } = require("discord.js"); const { time } = require("discord.js");
module.exports = { module.exports = {
name: 'purge', name: 'purge',
description: `delete a specified number of messages from the current channel`, description: `delete a specified number of messages from the current channel`,
aliases: ['clear', 'p'], aliases: ['clear', 'p'],
usage: 'purge <number>', usage: 'purge <number>',
async execute(client, message) { async execute(client, message) {
if (!message.member.permissions.has('ManageMessages')) { if (!message.member.permissions.has('ManageMessages')) {
return message.reply({ return message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
description: '<:no:1481811955592466492> you do not have permission to use this command!', description: '<:no:1481811955592466492> you do not have permission to use this command!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}], }],
}); });
} }
const args = message.content.split(' ').slice(1); const args = message.content.split(' ').slice(1);
const amount = parseInt(args[0]) + 1; const amount = parseInt(args[0]) + 1;
if (isNaN(amount) || amount < 1 || amount > 100) { if (isNaN(amount) || amount < 1 || amount > 100) {
return message.reply({ return message.reply({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
description: '<:no:1481811955592466492> please provide a number between 1 and 100!', description: '<:no:1481811955592466492> please provide a number between 1 and 100!',
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}], }],
}); });
} }
const deletedMessages = await message.channel.bulkDelete(amount, true); const deletedMessages = await message.channel.bulkDelete(amount, true);
const reply = await message.channel.send({ const reply = await message.channel.send({
content: null, embeds: [{ content: null, embeds: [{
color: 0x8aa2b3, color: 0x8aa2b3,
author: { author: {
name: message.author.username, name: message.author.username,
icon_url: message.author.displayAvatarURL(), icon_url: message.author.displayAvatarURL(),
}, },
description: `<:no:1481811955592466492> successfully deleted ${deletedMessages.size - 1} messages!`, description: `<:no:1481811955592466492> successfully deleted ${deletedMessages.size - 1} messages!`,
footer: { footer: {
text: `twitter @ ${message.guild.name}`, text: `twitter @ ${message.guild.name}`,
icon_url: client.user.displayAvatarURL(), icon_url: client.user.displayAvatarURL(),
}, },
timestamp: new Date(), timestamp: new Date(),
}], }],
}); });
setTimeout(() => reply.delete().catch(() => { }), 5000); setTimeout(() => reply.delete().catch(() => { }), 5000);
}, },
}; };
+53 -53
View File
@@ -1,53 +1,53 @@
'use strict'; 'use strict';
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const { Events } = require('discord.js'); const { Events } = require('discord.js');
const guildMemberAddEvent = require('../events/guildMemberAdd'); const guildMemberAddEvent = require('../events/guildMemberAdd');
const logger = require('../utils/logger'); const logger = require('../utils/logger');
/** /**
* Loads all event files from src/events and registers them on the client. * Loads all event files from src/events and registers them on the client.
* Each event file must export: { name, once?, execute } * Each event file must export: { name, once?, execute }
* *
* @param {import('discord.js').Client} client * @param {import('discord.js').Client} client
*/ */
function loadEvents(client) { function loadEvents(client) {
const eventsPath = path.join(__dirname, '..', 'events'); const eventsPath = path.join(__dirname, '..', 'events');
const eventFiles = fs const eventFiles = fs
.readdirSync(eventsPath) .readdirSync(eventsPath)
.filter((file) => file.endsWith('.js')); .filter((file) => file.endsWith('.js'));
let loaded = 0; let loaded = 0;
for (const file of eventFiles) { for (const file of eventFiles) {
try { try {
const event = require(path.join(eventsPath, file)); const event = require(path.join(eventsPath, file));
if (!event.name || typeof event.execute !== 'function') { if (!event.name || typeof event.execute !== 'function') {
logger.warn( logger.warn(
`[eventhandler] skipping ${file}: missing "name" or "execute"`, `[eventhandler] skipping ${file}: missing "name" or "execute"`,
); );
continue; continue;
} }
if (event.once) { if (event.once) {
client.once(event.name, (...args) => event.execute(client, ...args)); client.once(event.name, (...args) => event.execute(client, ...args));
} else { } else {
client.on(event.name, (...args) => event.execute(client, ...args)); client.on(event.name, (...args) => event.execute(client, ...args));
} }
logger.debug(`[eventhandler] registered event: ${event.name}`); logger.debug(`[eventhandler] registered event: ${event.name}`);
loaded++; loaded++;
} catch (err) { } catch (err) {
logger.error(`[eventhandler] failed to load ${file}:`, err); logger.error(`[eventhandler] failed to load ${file}:`, err);
} }
} }
client.on(Events.GuildMemberAdd, guildMemberAddEvent.bind(null, client)); client.on(Events.GuildMemberAdd, guildMemberAddEvent.bind(null, client));
loaded++; loaded++;
logger.info(`[eventhandler] ${loaded} event(s) registered`); logger.info(`[eventhandler] ${loaded} event(s) registered`);
} }
module.exports = { loadEvents }; module.exports = { loadEvents };
+50 -50
View File
@@ -1,50 +1,50 @@
'use strict'; 'use strict';
require('dotenv').config(); require('dotenv').config();
const { Client, Collection, GatewayIntentBits } = require('discord.js'); const { Client, Collection, GatewayIntentBits } = require('discord.js');
const logger = require('./utils/logger'); const logger = require('./utils/logger');
const { loadCommands } = require('./handlers/commandHandler'); const { loadCommands } = require('./handlers/commandHandler');
const { loadEvents } = require('./handlers/eventHandler'); const { loadEvents } = require('./handlers/eventHandler');
// Validate required environment variables // Validate required environment variables
if (!process.env.BOT_TOKEN) { if (!process.env.BOT_TOKEN) {
logger.error( logger.error(
'BOT_TOKEN is not set. Copy .env.example to .env and fill in your token.', 'BOT_TOKEN is not set. Copy .env.example to .env and fill in your token.',
); );
process.exit(1); process.exit(1);
} }
// Create the Discord client with the intents needed for prefix commands // Create the Discord client with the intents needed for prefix commands
const client = new Client({ const client = new Client({
intents: [ intents: [
GatewayIntentBits.Guilds, GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent, // Required to read message content for prefix commands GatewayIntentBits.MessageContent, // Required to read message content for prefix commands
GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessages,
], ],
}); });
// Attach a Collection to store commands // Attach a Collection to store commands
client.commands = new Collection(); client.commands = new Collection();
// Load commands and events // Load commands and events
loadCommands(client); loadCommands(client);
loadEvents(client); loadEvents(client);
// Global error handling // Global error handling
process.on('unhandledRejection', (err) => { process.on('unhandledRejection', (err) => {
logger.error('[process] unhandled rejection:', err); logger.error('[process] unhandled rejection:', err);
}); });
process.on('uncaughtException', (err) => { process.on('uncaughtException', (err) => {
logger.error('[process] uncaught exception:', err); logger.error('[process] uncaught exception:', err);
process.exit(1); process.exit(1);
}); });
// Connect to Discord // Connect to Discord
client.login(process.env.BOT_TOKEN).catch((err) => { client.login(process.env.BOT_TOKEN).catch((err) => {
logger.error('[login] failed to log in:', err); logger.error('[login] failed to log in:', err);
process.exit(1); process.exit(1);
}); });
+74 -74
View File
@@ -1,74 +1,74 @@
'use strict'; 'use strict';
const { createLogger, format, transports } = require('winston'); const { createLogger, format, transports } = require('winston');
const { consoleFormat } = require("winston-console-format"); const { consoleFormat } = require("winston-console-format");
const { printf } = format; const { printf } = format;
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
const logs_dir = path.join(__dirname, '..', '..', 'logs'); const logs_dir = path.join(__dirname, '..', '..', 'logs');
if (!fs.existsSync(logs_dir)) { if (!fs.existsSync(logs_dir)) {
fs.mkdirSync(logs_dir, { recursive: true }); fs.mkdirSync(logs_dir, { recursive: true });
} }
const logger = createLogger({ const logger = createLogger({
level: "silly", level: "silly",
format: format.combine( format: format.combine(
format.timestamp(), format.timestamp(),
format.ms(), format.ms(),
format.errors({ stack: true }), format.errors({ stack: true }),
format.splat(), format.splat(),
format.json({ space: 2 }) format.json({ space: 2 })
), ),
transports: [ transports: [
new transports.Console({ new transports.Console({
format: format.combine( format: format.combine(
format.colorize({ all: true }), format.colorize({ all: true }),
format.padLevels(), format.padLevels(),
consoleFormat({ consoleFormat({
showMeta: true, showMeta: true,
metaStrip: ["timestamp", "service"], metaStrip: ["timestamp", "service"],
inspectOptions: { inspectOptions: {
depth: Infinity, depth: Infinity,
colors: true, colors: true,
maxArrayLength: Infinity, maxArrayLength: Infinity,
breakLength: 120, breakLength: 120,
compact: Infinity, compact: Infinity,
}, },
}) })
), ),
}), }),
new transports.File({ new transports.File({
filename: path.join(logs_dir, 'combined.log'), filename: path.join(logs_dir, 'combined.log'),
format: format.combine( format: format.combine(
format.timestamp(), format.timestamp(),
format.ms(), format.ms(),
format.errors({ stack: true }), format.errors({ stack: true }),
format.splat(), format.splat(),
format.json({ space: 2 }) format.json({ space: 2 })
), ),
}), }),
new transports.File({ new transports.File({
filename: path.join(logs_dir, 'error.log'), filename: path.join(logs_dir, 'error.log'),
level: 'error', level: 'error',
format: format.combine( format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }), format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
format.errors({ stack: true }), format.errors({ stack: true }),
printf(({ level, message, timestamp, stack, ...meta }) => { printf(({ level, message, timestamp, stack, ...meta }) => {
let log = `${timestamp} [${level.toUpperCase()}]: ${message}`; let log = `${timestamp} [${level.toUpperCase()}]: ${message}`;
if (stack) { if (stack) {
log += `\ntrace: ${stack}`; log += `\ntrace: ${stack}`;
} }
if (Object.keys(meta).length > 0) { if (Object.keys(meta).length > 0) {
log += `\nmetadata: ${JSON.stringify(meta, null, 2)}`; log += `\nmetadata: ${JSON.stringify(meta, null, 2)}`;
} }
return log; return log;
}) })
), ),
}), }),
], ],
}); });
module.exports = logger; module.exports = logger;