42 Commits

Author SHA1 Message Date
4dfe2d8db0 Merge pull request #16 from gractwo/stage
fix kiss command gif (tenor deleted it lmao)
2023-02-23 20:16:06 +01:00
1c7853371c fix kiss command gif (tenor deleted it lmao) 2023-02-23 20:07:42 +01:00
89d95cd583 Merge pull request #15 from gractwo/stage
add /kiss command
2023-02-20 18:51:16 +01:00
8930854ed6 add /kiss command 2023-02-20 18:48:50 +01:00
7653c2d821 Merge pull request #14 from gractwo/dependabot/npm_and_yarn/undici-5.19.1
Bump undici from 5.14.0 to 5.19.1
2023-02-17 08:19:25 +01:00
dependabot[bot]
adb93eee00 Bump undici from 5.14.0 to 5.19.1
Bumps [undici](https://github.com/nodejs/undici) from 5.14.0 to 5.19.1.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v5.14.0...v5.19.1)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-17 07:18:46 +00:00
b3d9718fac Merge pull request #13 from gractwo/plato
essa.jpeg
2022-12-30 12:25:25 +01:00
cbae250079 Merge branch 'master' into plato 2022-12-30 12:21:22 +01:00
f01401790f forgor about cors 💀 2022-12-30 12:19:07 +01:00
1f22aa4061 essa.jpeg 2022-12-30 12:15:49 +01:00
Stanisław Dzioba
74a761fdc0 Merge pull request #12 from gractwo/jakubmanczak-patch-1
Update deploy.yml
2022-12-27 14:32:44 +01:00
98ca0b963a Update deploy.yml 2022-12-27 00:18:59 +01:00
66c2398dc5 Merge pull request #11 from gractwo/deployfixing
fix deploys on PR addition
2022-12-21 14:12:55 +01:00
2398ca7ebf Merge pull request #9 from gractwo/heisenberg
use CORS w/ @types/cors to allow gractwo.pl access to api
2022-12-21 14:12:38 +01:00
47abbbc0a7 fix deploys on PR addition 2022-12-21 10:34:51 +01:00
3c4587fe2a use CORS w/ @types/cors to allow gractwo.pl access to api 2022-12-21 10:21:35 +01:00
Stanisław Dzioba
f1989d0f83 Merge pull request #8 from gractwo/heisenberg
member count api - discordjs cache bypass
2022-12-20 23:57:23 +01:00
81701e030d member count api - discordjs cache bypass 2022-12-20 23:49:46 +01:00
Stanisław Dzioba
6dd509eedc Merge pull request #7 from gractwo/millennium
workflow folder addition
2022-12-16 22:00:50 +01:00
Stanislaw
950fea0691 workflow folder addition 2022-12-16 21:58:19 +01:00
Stanisław Dzioba
48d9a04410 Merge pull request #6 from gractwo/millennium
Workflows
2022-12-16 21:55:26 +01:00
Stanisław Dzioba
9adf762b89 wrong node in dockerfile 2022-12-16 21:53:38 +01:00
Stanisław Dzioba
abddd180d6 wrong env 2022-12-16 21:51:12 +01:00
Stanisław Dzioba
0fe99e10cf change branch name 2022-12-16 21:49:48 +01:00
Stanisław Dzioba
27aa0d0cae Add port 2022-12-16 21:49:01 +01:00
Stanislaw
df646a0f80 CI/CD 2022-12-16 21:46:53 +01:00
8a783c5e0f Merge pull request #5 from gractwo/millennium
Millennium
2022-12-16 21:39:05 +01:00
77c1f0f664 rewrite init + member count api 2022-12-16 09:30:42 +01:00
9df1e896c6 millennium init 2022-12-15 21:49:07 +01:00
de3799757b bring back peak comedy from old ver 2022-07-16 15:12:01 +02:00
21f7e440ea Update README.md 2022-07-16 14:59:30 +02:00
5f415736fe Merge pull request #4 from Gractwo/dependabot/npm_and_yarn/node-fetch-2.6.7
Bump node-fetch from 2.6.5 to 2.6.7
2022-05-03 23:44:36 +02:00
dependabot[bot]
d5ab626261 Bump node-fetch from 2.6.5 to 2.6.7
Bumps [node-fetch](https://github.com/node-fetch/node-fetch) from 2.6.5 to 2.6.7.
- [Release notes](https://github.com/node-fetch/node-fetch/releases)
- [Commits](https://github.com/node-fetch/node-fetch/compare/v2.6.5...v2.6.7)

---
updated-dependencies:
- dependency-name: node-fetch
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-05-03 21:43:44 +00:00
5c6c152002 Merge pull request #3 from Gractwo/dependabot/npm_and_yarn/minimist-1.2.6
Bump minimist from 1.2.5 to 1.2.6
2022-05-03 23:42:43 +02:00
dependabot[bot]
3beeea10c9 Bump minimist from 1.2.5 to 1.2.6
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-05-03 21:41:46 +00:00
fbe4b20de5 minor spacing changes for witajembed 2022-05-01 20:27:02 +02:00
b9fdd910f7 fast update to witajembed for channels rearrange 2022-05-01 20:24:02 +02:00
dc40293dff funny messages trololo 2022-03-26 21:41:52 +01:00
22e9c0ebc0 add .prettierrc 2022-01-04 23:24:41 +01:00
7ce3db773d fuck up git blame for the 2nd time but the final one this time 2022-01-04 23:24:24 +01:00
BoberITman
978320d804 Hotfix 2022-01-04 16:17:51 +01:00
BoberITman
313758c174 Update cfg.json 2022-01-04 16:10:07 +01:00
30 changed files with 2083 additions and 2537 deletions

18
.github/workflows/deploy.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: Deploy
on:
push:
branches: ['master']
jobs:
build:
runs-on: self-hosted
steps:
- uses: actions/checkout@v3
- name: Build image
run: docker build -t ${{ github.repository }} .
- name: Deploy image
run: |
docker stop ${{ github.event.repository.name }} || true
docker rm ${{ github.event.repository.name }} || true
docker run -d -e "TOKEN=${{ secrets.TOKEN }}" -e "ENVIRONMENT=${{ secrets.ENVIRONMENT }}" --restart always -p 2020:2020 --name ${{ github.event.repository.name }} ${{ github.repository }}

2
.gitignore vendored
View File

@@ -1,3 +1,3 @@
/node_modules
/dist
.env
package-lock.json

7
.prettierrc Normal file
View File

@@ -0,0 +1,7 @@
{
"bracketSpacing": true,
"singleQuote": true,
"useTabs": true,
"tabWidth": 2,
"semi": true
}

5
Dockerfile Normal file
View File

@@ -0,0 +1,5 @@
FROM node:latest
WORKDIR /app
COPY ./ ./
RUN npm install
CMD ["npm", "run", "start"]

View File

@@ -1 +0,0 @@
worker: node src/index.js

View File

@@ -1,3 +1,11 @@
# gractwo-bot
gractwo-bot is a Discord bot written in JavaScript, using node.js and discord.js.
It has been created for and only serves the Gractwo Discord server. It is hosted using Heroku.
<img align="left" style="width:128px" src="https://github.com/gractwo/assets/blob/master/logo.svg" />
# gractwo/bot
The premier bot for Gractwo's discord operations.
### package scripts
- run `npm run start` to build and run the bot.
- run `npm run build` to only build the bot.
- run `npm run serve` to only run the bot.

12
environment.d.ts vendored Normal file
View File

@@ -0,0 +1,12 @@
declare global {
namespace NodeJS {
interface ProcessEnv {
TOKEN: string;
DEVTOKEN: string;
PORT: string;
ENVIRONMENT: 'prod' | 'dev';
}
}
}
export {};

3803
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,28 +1,34 @@
{
"name": "discord-bot",
"version": "1.0.0",
"description": "gractwo-bot is a Discord bot written in JavaScript, using node.js and discord.js.\r It has been created for and only serves the Gractwo Discord server. It is hosted using Heroku.",
"main": "src/index.js",
"name": "gractwo-bot",
"version": "0xDEADBEEF",
"description": "The premier bot for Gractwo's discord operations.",
"main": "dist/index.js",
"scripts": {
"start": "tsc && node .",
"build": "tsc",
"serve": "node .",
"register": "tsc && node ./dist/register.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Gractwo/discord-bot.git"
"url": "git+https://github.com/gractwo/bot.git"
},
"author": "github.com/jakubmanczak",
"author": "gractwo team",
"license": "UNLICENSED",
"bugs": {
"url": "https://github.com/Gractwo/discord-bot/issues"
},
"homepage": "https://github.com/Gractwo/discord-bot#readme",
"engines": {
"node": ">=16.10.0",
"npm": ">=7.24.0"
"url": "https://github.com/gractwo/bot/issues"
},
"homepage": "https://github.com/gractwo/bot#readme",
"dependencies": {
"discord.js": "^13.1.0",
"dotenv": "^10.0.0",
"nodemon": "^2.0.13"
"@types/cors": "^2.8.13",
"@types/express": "^4.17.15",
"@types/glob": "^8.0.0",
"cors": "^2.8.5",
"discord.js": "^14.7.1",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"glob": "^8.0.3",
"typescript": "^4.9.4"
}
}

View File

@@ -1,95 +1,9 @@
{
"prefix": ".",
"hexBlue": "61f2ea",
"hexRed": "fb636b",
"iconurl": "https://i.imgur.com/4AmRDyX.png",
"timeout": 4000,
"rolesList": [
"tf2",
"liga",
"csgo",
"minecraft",
"rainbow-six",
"apex",
"genshin",
"valorant"
],
"embedFields": {
"witaj": [
{
"name": "Zasady",
"value": "Zasady serwera są spisane na kanale `regulamin`. Pamiętajcie, by tam zajrzeć."
},
{
"name": "Gractwo WWW",
"value": "http://gractwo.pl",
"inline": true
},
{
"name": "Gractwo DISCORD",
"value": "http://gractwo.pl/discord",
"inline": true
},
{
"name": "DISCORD bezpośredni",
"value": "discord.gg/NBXq95C",
"inline": true
},
{
"name": "Gractwo TWITTER",
"value": "http://gractwo.pl/twitter",
"inline": true
},
{
"name": "Gractwo YOUTUBE",
"value": "http://gractwo.pl/youtube",
"inline": true
},
{
"name": "Gractwo GITHUB",
"value": "http://gractwo.pl/github",
"inline": true
}
],
"regulamin": [
{
"name": "§1 Szacunek",
"value": "Na naszym serwerze obowiązuje szacunek do innych osób podczas niesatyrycznej dyskusji."
},
{
"name": "§2 Spam / Trolling",
"value": "Jeżeli będziesz bezużytecznie spamować lub nieprzyjmenie się zachowywać zostaniesz zbanowany."
},
{
"name": "§3 Bagno",
"value": "Kanał #bagno jest najbardziej wyluzowanym kanałem na naszym serwerze. Nie oznacza to jednak, że nie jest monitorowany. Jeżeli czujesz, że rzecz którą chcesz tam umieścić jest nadzwyczajnie kontrowersyjna, zastanów się dwa razy przed wciśnięciem Enter."
},
{
"name": "§4 Poprawne Kanały",
"value": "Rozmowy na dany temat powinny toczyć się w kanałach do tego przeznaczonych."
},
{
"name": "§5 Memy i Gify",
"value": "Memy i Gify nie są zbyt przyjemne dla oka bez kontekstu. Najlepiej jest nie postować ich, jeżeli nie pasują do prowadzonej aktualnie dyskusji."
},
{
"name": "§6 Reklamy",
"value": "Zakaz reklam bez zezwolenia moderatora lub administratora. Pozwolenia na reklamę muszą być wydane przed jej zamieszczeniem."
},
{
"name": "§7 Przestrzeganie Regulaminu",
"value": "Przestrzeganie regulaminu jest obowiązkowe, a to że go ktoś nie przeczytał nic nie zmienia."
},
{
"name": "§8 Obcowanie z botem",
"value": "Próby intencjonalnego łamania bota nie są mile widziane, tak jak nadużywanie go w celach spamu kanałów."
},
{
"name": "§9 Warunki Użytkowania Discord (ToS)",
"value": "Nasz serwer, jak każdy inny, musi przestrzegać zasad zapisanych w warunkach użytkowania Discorda. Przypominamy o nich, bo choć nie są zbyt restrykcyjne, nie pozwalają na kilka określonych rzeczy."
}
],
"pomocDesc": "Komenda objaśniająca bota i jego zastosowanie, a także dostępne komendy.\n\nBot Gractwa funkcjonuje jako własne rozwiązanie na problemy z administrowaniem serwera Discord. Umożliwia między innymi samo-nadawanie rolek od gier, lub odsłuchiwanie muzyki.\n\nPoniżej znajduje się lista dostępnych komend:",
"rolkiDesc": "Poniżej widnieją przyciski służące do przyznawania bądź odejmowanie sobie ról powiązanych z grami. Służą one do oznaczania wszystkich zainteresowanych daną grą na określonym kanale."
"api": {
"fallbackPort": 2020,
"memberCountGuildId": "447075692664979466"
},
"dsc": {
"slashCmdTestGuildId": "860916258282012692"
}
}

View File

@@ -1,116 +0,0 @@
const {
MessageActionRow,
MessageButton,
ButtonInteraction,
Interaction,
Client,
} = require('discord.js');
module.exports = {
name: 'embed',
execute(cl, msg, args) {
// TODO: add a permissions check here to make sure nobody can spawn msgs
// not intended outside of specific scenarios
let embed = {
color: cl.cfg.hexBlue,
// timestamp: new Date(),
// footer: {
// text: `Komenda wywołana przez ${msg.author.tag}`,
// icon_url: cl.cfg.iconurl,
// },
};
let readyMsg;
switch (args[0]) {
case 'witaj':
embed.author = {
name: 'Witajcie w Gractwie!',
icon_url: 'https://i.imgur.com/4AmRDyX.png',
};
embed.description =
'Jesteśmy grupą ludzi których kręcą gry. Proste, nie?\nSerwer ten miał wcześniej tematykę Team Fortressową.';
embed.fields = cl.cfg.embedFields.witaj;
readyMsg = { embeds: [embed] };
break;
case 'regulamin':
embed.title = 'Regulamin';
embed.description =
'Regulamin naszego serwera składa się z tego, co następuje:';
embed.footer = {
text: `Ostatnio zaktualizowany`,
icon_url: cl.cfg.iconurl,
};
embed.timestamp = new Date();
embed.fields = cl.cfg.embedFields.regulamin;
readyMsg = { embeds: [embed] };
break;
case 'rolki':
embed.author = { name: 'Rolki' };
embed.description = cl.cfg.embedFields.rolkiDesc;
embed.footer = {
text: `#witaj`,
icon_url: cl.cfg.iconurl,
};
embed.timestamp = new Date();
// code responsible for making lists of buttons out of cl.cfg.rolesList
// & including them in the readyMsg
let i = 1,
l = 0;
let btnList = [];
while (
cl.cfg.rolesList.length / 5 +
(cl.cfg.rolesList.length % 5 != 0 ? 1 : 0) >=
i
) {
let btnRow = new MessageActionRow();
for (l; l <= 5 * i - 1 && cl.cfg.rolesList[l] != undefined; l++) {
btnRow.addComponents(
new MessageButton()
.setCustomId(cl.cfg.rolesList[l])
.setLabel(`rolka ${cl.cfg.rolesList[l]}`)
.setStyle('SECONDARY')
);
}
btnList.push(btnRow);
console.log(btnList);
i++;
}
readyMsg = { embeds: [embed], components: btnList };
break;
default:
embed.title = `zły parametr: ` + args[0];
embed.color = cl.cfg.hexRed;
readyMsg = { embeds: [embed] };
break;
}
msg.channel.send(readyMsg);
if (args[0] === 'rolki') {
cl.on('interactionCreate', (inter) => {
if (!inter.isButton()) return;
const role = inter.member.guild.roles.cache.find(
(role) => role.name == inter.customId
);
if (!role) return;
if (
!inter.member.roles.cache.find((role) => role.name == inter.customId)
) {
inter.member.roles.add(role);
inter
.reply('Gratulacje, dodalismy ci tą bezużyteczną rangę', {
timeout: cl.cfg.timeout,
})
.then(inter.deleteReply());
} else {
inter.member.roles.remove(role);
inter
.reply('Gratulacje, odebraliśmy ci tą bezużyteczną rangę', {
timeout: cl.cfg.timeout,
})
.then(inter.deleteReply());
}
});
}
},
};

View File

@@ -1,18 +0,0 @@
module.exports = {
name: 'ping',
execute(cl, msg) {
const embed = {
color: cl.cfg.hexBlue,
timestamp: new Date(),
footer: {
text: `Komenda wywołana przez ${msg.author.tag}`,
icon_url: cl.cfg.iconurl,
},
title: 'Pong!',
description: `Ping jednostronny wynosi ${
Date.now() - msg.createdTimestamp
}ms.`,
};
msg.channel.send({ embeds: [embed] });
},
};

View File

@@ -1,16 +0,0 @@
module.exports = {
name: 'pomoc',
execute(cl, msg) {
const embed = {
color: cl.cfg.hexBlue,
timestamp: new Date(),
footer: {
text: `Komenda wywołana przez ${msg.author.tag}`,
icon_url: cl.cfg.iconurl,
},
title: 'Pomoc!',
description: cl.cfg.embedFields.pomocDesc,
};
msg.channel.send({ embeds: [embed] });
},
};

View File

@@ -1,17 +0,0 @@
module.exports = {
name: 'regulamin',
execute(cl, msg) {
const embed = {
color: cl.cfg.hexBlue,
timestamp: new Date(),
footer: {
text: `Komenda wywołana przez ${msg.author.tag}`,
icon_url: cl.cfg.iconurl,
},
title: 'Regulamin',
description: 'Regulamin naszego serwera składa się z tego, co następuje:',
fields: cl.cfg.embedFields.regulamin,
};
msg.channel.send({ embeds: [embed] });
},
};

37
src/commands/kiss.ts Normal file
View File

@@ -0,0 +1,37 @@
import { ApplicationCommandOptionType } from 'discord.js';
import { EmbedBuilder } from 'discord.js';
import { Command } from '../structures/Command';
export default new Command({
name: 'kiss',
description: 'kiss somebody',
options: [
{
type: ApplicationCommandOptionType.User,
name: 'target',
description: 'the user to kiss',
required: true,
},
],
run: async ({ interaction, args }) => {
const kissEmbed = new EmbedBuilder()
.setColor('LuminousVividPink')
.setTitle(
`${interaction.user.username} kissed ${
args.getUser('target')?.username || 'a ghost'
} :)`
)
.setImage(
'https://media.discordapp.net/attachments/594222795999805643/1078363884190183485/ezgif-1-96508f9a03.gif'
);
interaction.followUp({ embeds: [kissEmbed] });
interaction.channel?.send(`${args.getUser('target')}`);
// interaction.channel?.send(`${args.getUser('target')}` || 'an invalid user');
// interaction.followUp(
// `${interaction.user.username} kissed ${args.getUser('target')} :)`
// );
// interaction.channel?.send(
// 'https://tenor.com/view/renko-usami-touhou-maribel-hearn-gif-22032279'
// );
},
});

9
src/commands/ping.ts Normal file
View File

@@ -0,0 +1,9 @@
import { Command } from '../structures/Command';
export default new Command({
name: 'ping',
description: 'pongs back!',
run: async ({ interaction }) => {
interaction.followUp('pong');
},
});

9
src/commands/pomoc.ts Normal file
View File

@@ -0,0 +1,9 @@
import { Command } from '../structures/Command';
export default new Command({
name: 'pomoc',
description: 'pokazuje pomocne informacje',
run: async ({ interaction }) => {
interaction.followUp('tu będzie komenda z pomocami!');
},
});

View File

@@ -0,0 +1,6 @@
import { Event } from '../structures/Event';
import { members } from '..';
export default new Event('guildMemberAdd', () => {
members.incrementCurrent();
});

View File

@@ -0,0 +1,6 @@
import { Event } from '../structures/Event';
import { members } from '..';
export default new Event('guildMemberRemove', () => {
members.decrementCurrent();
});

View File

@@ -0,0 +1,18 @@
import { CommandInteractionOptionResolver } from 'discord.js';
import { client } from '..';
import { Event } from '../structures/Event';
import { BotInteraction } from '../typings/Command';
export default new Event('interactionCreate', async (interaction) => {
if (interaction.isCommand()) {
await interaction.deferReply();
const command = client.commands.get(interaction.commandName);
if (!command)
return interaction.followUp("This command doesn't exist. Dork.");
command.run({
args: interaction.options as CommandInteractionOptionResolver,
client,
interaction: interaction as BotInteraction,
});
}
});

23
src/events/ready.ts Normal file
View File

@@ -0,0 +1,23 @@
import { client, config, members } from '..';
import { Event } from '../structures/Event';
export default new Event('ready', () => {
console.log(`BOT: Now logged in as ${client.user?.tag}.`);
// memberCount reporting - for the API
// ---------------------------------------
// NOTE: for this to work, bot needs to be
// member of Gractwo Main Discord Server
members.setCurrent(
client.guilds.resolve(config.api.memberCountGuildId)?.memberCount || null
);
let intervalSeconds = 5;
setInterval(() => {
if (members.previous != members.current) {
console.log(
`API/BOT: Gractwo memberCount is ${`now ${members.current}` || 'unset'}`
);
}
members.setPrevious(members.current);
}, intervalSeconds * 1000);
});

View File

@@ -1,57 +0,0 @@
const discordjs = require('discord.js');
const fs = require('fs');
require('dotenv').config();
const cl = new discordjs.Client({
intents: [
discordjs.Intents.FLAGS.GUILDS,
discordjs.Intents.FLAGS.GUILD_MESSAGES,
],
});
cl.cfg = require('./cfg.json');
cl.cmds = new discordjs.Collection();
const cmdsFls = fs
.readdirSync(`./src/cmds`)
.filter((file) => file.endsWith(`.js`));
for (const Fl of cmdsFls) {
const cmd = require(`./cmds/${Fl}`);
console.log(`command: ` + cmd.name);
cl.cmds.set(cmd.name, cmd);
}
cl.on('messageCreate', (msg) => {
if (!msg.content.startsWith(cl.cfg.prefix) || msg.author.bot) return;
const args = msg.content.slice(cl.cfg.prefix.length).trim().split(/ +/);
const cmdName = args.shift().toLowerCase();
if (!cl.cmds.has(cmdName)) return;
const cmd = cl.cmds.get(cmdName);
try {
cmd.execute(cl, msg, args);
} catch (error) {
console.error(
`msgCommand error: ${cmdName} with args ${args} by ${msg.author.tag}\n--\n${error}\n--`
);
msg.reply(
`An error occured while trying to execute ${cmdName} with args ${args}`
);
console.log(error);
return;
}
console.log(`msgCommand: ${cmdName + args} by ${msg.author.tag}`);
});
cl.once('ready', () => {
console.clear();
console.log(`bot ready; logged in as ${cl.user.tag}\n--`);
cl.user.setActivity('.pomoc', { type: 'LISTENING' });
});
cl.login(process.env.token); // here comes the boooy
// hello boy
// welcome
// there he is
// he is here

28
src/index.ts Normal file
View File

@@ -0,0 +1,28 @@
import { BotClient } from './structures/Client';
import { MemberCount } from './structures/MemberCount';
import express from 'express';
import cors from 'cors';
import config from './cfg.json';
require('dotenv').config();
const client = new BotClient();
client.boot();
const app = express();
app.use(cors());
const members = new MemberCount();
let port = process.env.PORT || config.api.fallbackPort;
app.get('/', (req, res) => {
res.sendStatus(200);
});
app.get('/members', (req, res) => {
res
.status(members.current ? 200 : 500)
.send(members.current ? members.current.toString() : 'Server Error');
});
app.listen(port, () => {
console.log(`API: Now listening on :${port}.`);
});
export { client, app, config, members };

84
src/structures/Client.ts Normal file
View File

@@ -0,0 +1,84 @@
import {
ApplicationCommandDataResolvable,
Client,
ClientEvents,
Collection,
GatewayIntentBits,
} from 'discord.js';
import { CommandType } from '../typings/Command';
import glob from 'glob';
import { promisify } from 'util';
import { RegisterCommandsOptions } from '../typings/Client';
import { Event } from './Event';
import config from '../cfg.json';
// makes file search lib a promise
const globPromise = promisify(glob);
class BotClient extends Client {
commands: Collection<string, CommandType> = new Collection();
constructor() {
super({
intents: 32767, // all intents!
});
}
boot() {
this.registerModules();
this.login(
// if prod, use main bot token
process.env.ENVIRONMENT == 'prod'
? process.env.TOKEN
: process.env.DEVTOKEN
);
}
async importFile(filePath: string) {
return (await import(filePath))?.default;
}
async registerCommands({ commands, guildId }: RegisterCommandsOptions) {
if (guildId) {
// register in guild
this.guilds.cache.get(guildId)?.commands.set(commands);
} else {
// register globally
this.application?.commands.set(commands);
}
}
async registerModules() {
const slashCommands: ApplicationCommandDataResolvable[] = [];
const commandFiles = await globPromise(
`${__dirname}/../commands/*{.ts,.,js}`
);
commandFiles.forEach(async (filePath) => {
const command: CommandType = await this.importFile(filePath);
if (!command.name) return;
this.commands.set(command.name, command);
slashCommands.push(command);
});
this.on('ready', () => {
this.registerCommands({
commands: slashCommands,
guildId: config.dsc.slashCmdTestGuildId,
});
// if prod, register global commands
if (process.env.ENVIRONMENT == 'prod') {
this.registerCommands({
commands: slashCommands,
});
}
});
const eventFiles = await globPromise(`${__dirname}/../events/*{.ts,.js}`);
eventFiles.forEach(async (filePath) => {
const event: Event<keyof ClientEvents> = await this.importFile(filePath);
this.on(event.event, event.run);
});
}
}
export { BotClient };

View File

@@ -0,0 +1,9 @@
import { CommandType } from '../typings/Command';
class Command {
constructor(commandOptions: CommandType) {
Object.assign(this, commandOptions);
}
}
export { Command };

10
src/structures/Event.ts Normal file
View File

@@ -0,0 +1,10 @@
import { ClientEvents } from 'discord.js';
class Event<Key extends keyof ClientEvents> {
constructor(
public event: Key,
public run: (...args: ClientEvents[Key]) => any
) {}
}
export { Event };

View File

@@ -0,0 +1,22 @@
class MemberCount {
current: number | null = null;
previous: number | null = null;
// "previous" is only used for reporting checks
// inside the ready.ts event
incrementCurrent() {
if (this.current) this.current++;
}
decrementCurrent() {
if (this.current) this.current--;
}
setCurrent(input: number | null) {
this.current = input;
}
setPrevious(input: number | null) {
this.previous = input;
}
}
export { MemberCount };

7
src/typings/Client.ts Normal file
View File

@@ -0,0 +1,7 @@
import { ApplicationCommandDataResolvable } from 'discord.js';
interface RegisterCommandsOptions {
guildId?: string;
commands: ApplicationCommandDataResolvable[];
}
export { RegisterCommandsOptions };

27
src/typings/Command.ts Normal file
View File

@@ -0,0 +1,27 @@
import {
ChatInputApplicationCommandData,
CommandInteraction,
CommandInteractionOptionResolver,
GuildMember,
PermissionResolvable,
} from 'discord.js';
import { BotClient } from '../structures/Client';
interface BotInteraction extends CommandInteraction {
member: GuildMember;
}
interface RunOptions {
client: BotClient;
interaction: BotInteraction;
args: CommandInteractionOptionResolver;
}
type RunFunction = (options: RunOptions) => any;
type CommandType = {
userPermissions?: PermissionResolvable[];
run: RunFunction;
} & ChatInputApplicationCommandData;
export { CommandType, BotInteraction };

103
tsconfig.json Normal file
View File

@@ -0,0 +1,103 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
"rootDir": "./src/" /* Specify the root folder within your source files. */,
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
"resolveJsonModule": true /* Enable importing .json files. */,
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist/" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}