25 Commits

Author SHA1 Message Date
Stanislaw
eabe9c9f95 prosma hotfix 2022-07-02 17:43:12 +02:00
Stanislaw
94650da46e prisma fix 2022-07-02 17:20:56 +02:00
Stanislaw
e22045b69a prod database implementation 2022-07-02 17:10:49 +02:00
Stanislaw
911ad50602 docker network 2022-07-01 23:03:11 +02:00
Stanislaw
918e498ac3 canvas fix 2022-07-01 22:51:06 +02:00
Stanislaw
8ec2b4dca2 test webhook 2022-06-21 14:44:16 +02:00
Stanislaw
d0ed5f7e00 canvas error on hold 2022-06-21 14:13:49 +02:00
Stanislaw
7e3e7ecbf8 python hotfix 3 2022-06-16 21:43:18 +02:00
Stanislaw
efaee7d035 node hotfix 2 2022-06-16 21:22:29 +02:00
Stanislaw
e1c499328a Python fix 2022-06-16 21:15:43 +02:00
Stanislaw
f7ba8187fe Node fix 2022-06-16 21:12:41 +02:00
Stanislaw
be4106b262 Prisma hotfix 2022-06-16 21:08:44 +02:00
Stanislaw
9364c1767a add dockerfile 2022-06-15 22:33:33 +02:00
Stanislaw
089e13b9ff add workflows 2022-06-15 22:28:18 +02:00
Stanislaw
ffc034dbdd dependencies update 2022-04-29 01:05:52 +02:00
Stanislaw
a2c8e1cfee class implementation with fixes and prisma schema changes 2022-04-29 00:43:24 +02:00
Stanislaw
f308503816 orm and profile first implementation 2022-04-20 15:20:22 +02:00
Stanislaw
4f11342db8 Badges download 2022-03-29 22:00:05 +02:00
Stanislaw
4af3c0adfa add leveling 2022-03-15 12:10:15 +01:00
Stanislaw
f2371974cd Postgres is alive 2022-03-11 21:16:45 +01:00
Stanislaw
5d5efa884d Redis appeared 2022-03-11 12:45:33 +01:00
Stanislaw
8a3f9bb03c Mee6discord przygotowania 2022-03-10 22:59:33 +01:00
Stanislaw
60bf216d71 new play changes 2021-12-27 21:36:50 +01:00
Stanislaw
cee3c07409 yt link download 2021-12-27 10:31:47 +01:00
Stanislaw
481a1f3f25 Voice connection shitfest edition
No działa tylko na papierze syf że szkoda gadać
2021-12-27 10:08:19 +01:00
42 changed files with 3448 additions and 2400 deletions

View File

@@ -2,7 +2,9 @@ name: Deploy
on:
push:
branches: ['master']
branches: ["canary"]
pull_request:
branches: ["main"]
jobs:
build:
@@ -15,4 +17,4 @@ jobs:
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 }}
docker run -d -e "DISCORD_TOKEN=${{ secrets.DISCORD_TOKEN }}" -e "REDIS_TOKEN=${{ secrets.REDIS_TOKEN }}" -e "DATABASE_URL=${{ secrets.DATABASE_URL }}" --restart always --network BOT --name ${{ github.event.repository.name }} ${{ github.repository }}

3
.gitignore vendored
View File

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

View File

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

View File

@@ -1,5 +1,10 @@
FROM node:latest
# syntax=docker/dockerfile:1
FROM node:16.10.0
WORKDIR /app
COPY ./ ./
RUN apt-get -y update
RUN apt-get install -y build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev
RUN npm install --build-from-source canvas
RUN npm install
CMD ["npm", "run", "start"]
CMD ["npx", "prisma", "db", "push"]
CMD ["node", "index.js"]

1
Procfile Normal file
View File

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

View File

@@ -1,11 +1,4 @@
<img align="left" style="width:128px" src="https://github.com/gractwo/assets/blob/master/logo.svg" />
# gractwo-bot
# 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.
<b>gractwo-bot</b> 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.

95
cfg.json Normal file
View File

@@ -0,0 +1,95 @@
{
"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."
}
}

12
environment.d.ts vendored
View File

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

95
index.js Normal file
View File

@@ -0,0 +1,95 @@
const discordjs = require("discord.js");
const fs = require("fs");
const redis = require("./src/functions/redis");
const { Postgres } = require("./src/functions/postgres");
const { createClient } = require("redis");
const colors = require("colors");
colors.setTheme({
prompt: "grey",
info: "green",
warn: "yellow",
debug: "blue",
error: "red",
});
require("dotenv").config();
const cl = new discordjs.Client({
intents: [
discordjs.Intents.FLAGS.GUILDS,
discordjs.Intents.FLAGS.GUILD_MESSAGES,
discordjs.Intents.FLAGS.GUILD_VOICE_STATES,
],
});
//redis connect
const redisConnection = createClient({
url: process.env.REDIS_TOKEN,
});
redisConnection
.connect()
.then(() => console.log("✔️ redis connected".info))
.catch((err) => console.error(err.stack.red));
//postgres connection
const client = new Postgres();
cl.cfg = require("./cfg.json");
cl.cmds = new discordjs.Collection();
//cmds handler
const cmdsFls = fs
.readdirSync(`./src/cmds`)
.filter((file) => file.endsWith(`.js`));
for (const Fl of cmdsFls) {
const cmd = require(`./src/cmds/${Fl}`);
console.log(`command: ` + cmd.name);
cl.cmds.set(cmd.name, cmd);
}
//command execution
cl.on("messageCreate", async (msg) => {
if (msg.author.bot) return;
//exp
if (!msg.content.startsWith(cl.cfg.prefix)) {
client.messageCount(msg.author.id, msg.channel.id);
if (await redis.expCheck(msg.author.id, redisConnection)) {
client.addExp(msg.author.id, 10, 25);
}
} else {
//client.messageCount(msg.author.id);
}
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, client);
} 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}`);
});
//client
cl.once("ready", () => {
console.log(`bot ready; logged in as ${cl.user.tag}\n--`.info);
cl.user.setActivity(".pomoc", { type: "LISTENING" });
});
cl.login(process.env.TOKEN); // here comes the boooy
// hello boy
// welcome
// there he is
// he is here

4116
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +1,33 @@
{
"name": "gractwo-bot",
"version": "0xDEADBEEF",
"description": "The premier bot for Gractwo's discord operations.",
"main": "dist/index.js",
"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",
"scripts": {
"start": "tsc && node .",
"build": "tsc",
"serve": "node .",
"register": "tsc && node ./dist/register.js",
"test": "echo \"Error: no test specified\" && exit 1"
"start": "nodemon"
},
"repository": {
"type": "git",
"url": "git+https://github.com/gractwo/bot.git"
"url": "git+https://github.com/Gractwo/discord-bot.git"
},
"author": "gractwo team",
"author": "github.com/jakubmanczak",
"license": "UNLICENSED",
"bugs": {
"url": "https://github.com/gractwo/bot/issues"
"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"
},
"homepage": "https://github.com/gractwo/bot#readme",
"dependencies": {
"@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"
"@prisma/client": "^3.12.0",
"colors": "^1.4.0",
"daemon": "^1.1.0",
"discord.js": "^13.6.0",
"dotenv": "^10.0.0",
"nodemon": "^2.0.16",
"prisma": "^3.13.0",
"redis": "^4.0.4"
}
}

48
prisma/schema.prisma Normal file
View File

@@ -0,0 +1,48 @@
generator client {
provider = "prisma-client-js"
binaryTargets = ["linux-musl"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model badges {
badge_id Int @id
badge_name String
badge_description String
badge_visibility Boolean @default(true)
badge_type Int @default(0)
givenbadges givenbadges[]
}
model givenbadges {
user_id String
badge_id Int
date_of_confer DateTime @id @db.Date
badges badges @relation(fields: [badge_id], references: [badge_id], onDelete: NoAction, onUpdate: NoAction, map: "badge_id")
users users @relation(fields: [user_id], references: [user_id], onDelete: NoAction, onUpdate: NoAction, map: "user_id")
@@index([badge_id], map: "fki_badge_id")
@@index([user_id], map: "fki_user_id")
}
model users {
user_id String @id(map: "user_pkey")
exp Int @default(0)
voice_time Int @default(0)
lvl Int @default(0)
givenbadges givenbadges[]
sendmessages sendmessages[]
}
model sendmessages {
id Int @id @default(autoincrement())
user_id String
date DateTime @db.Date
channel String
msg_count Int
users users @relation(fields: [user_id], references: [user_id], onDelete: NoAction, onUpdate: NoAction, map: "user_id")
}

View File

@@ -1,9 +0,0 @@
{
"api": {
"fallbackPort": 2020,
"memberCountGuildId": "447075692664979466"
},
"dsc": {
"slashCmdTestGuildId": "860916258282012692"
}
}

0
src/cmds/batch.js Normal file
View File

37
src/cmds/dodajodznake.js Normal file
View File

@@ -0,0 +1,37 @@
module.exports = {
name: "dodajodznake",
async execute(cl, msg, args) {
const { get } = require("https");
const { createWriteStream, access } = require("fs");
if (msg.member.permissions.has(0x20)) {
if (msg.attachments.at(0) != null) {
console.log("attachmentadded");
msg.attachments.each((x) => {
if (x.contentType.startsWith("application/json")) {
access(`src/badges/json/${x.name}`, (e) => {
if (!e) {
const file = createWriteStream(`src/badges/json/${x.name}`);
get(x.url, (res) => {
res.pipe(file);
});
} else {
msg.channel.send("Taka odznaka już istnieje");
}
});
} else if (x.contentType.startsWith("image/")) {
exists(`src/badges/img/${x.name}`, (e) => {
if (!e) {
const file = createWriteStream(`src/badges/img/${x.name}`);
get(x.url, (res) => {
res.pipe(file);
});
} else {
msg.channel.send("Taka odznaka już istnieje");
}
});
}
});
}
}
},
};

111
src/cmds/embed.js Normal file
View File

@@ -0,0 +1,111 @@
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,
};
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());
}
});
}
},
};

6
src/cmds/odznaki.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
name: "odznaki",
execute(cl, msg) {
},
};

18
src/cmds/ping.js Normal file
View File

@@ -0,0 +1,18 @@
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] });
},
};

16
src/cmds/pomoc.js Normal file
View File

@@ -0,0 +1,16 @@
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] });
},
};

56
src/cmds/profile.js Normal file
View File

@@ -0,0 +1,56 @@
module.exports = {
name: "profile",
async execute(cl, msg, args, connect) {
const { roundRect, expThreshold } = require("../functions/tools");
const canvas = require("canvas");
await connect
.profile(msg.author.id)
.then((user) => {
canvas.registerFont("./src/fonts/Lexend-Bold.ttf", {
family: "LexendBold",
});
canvas.registerFont("./src/fonts/Lexend-Thin.ttf", {
family: "LexendThin",
});
const canva = canvas.createCanvas(1024, 256);
let context = canva.getContext("2d");
context.fillStyle = "#484848";
roundRect(context, 0, 0, 1024, 256, 25);
context.fill();
context.font = '48px "LexendBold"';
context.fillStyle = "#FFFFFF";
context.fillText(msg.author.tag, 244, 24 + 48);
context.fillText("Lvl " + user.lvl, 850, 24 + 48);
context.font = '25px "LexendThin"';
context.fillText(user.msg_count + " messages sent", 244, 72 + 25);
context.font = '24px "LexendThin"';
context.fillText(expThreshold(user.lvl + 1) + " exp", 810, 164 + 24);
context.fillText(user.exp + " exp", 250, 164 + 24);
context.fillStyle = "#242424";
roundRect(context, 244, 200, 700, 30, 50);
context.fill();
context.fillStyle = "#61F2EA";
roundRect(
context,
244,
200,
700 *
((user.exp - expThreshold(user.lvl)) / expThreshold(user.lvl + 1)),
30,
50
);
context.fill();
roundRect(context, 34, 34, 188, 188, 100);
canvas
.loadImage(msg.author.avatarURL({ format: "png" }))
.then((image) => {
context.clip();
context.drawImage(image, 34, 34, 188, 188);
msg.reply({
files: [canva.toBuffer()],
});
});
})
.catch((err) => console.error(err.stack));
},
};

4
src/cmds/ranking.js Normal file
View File

@@ -0,0 +1,4 @@
module.exports = {
name: "ranking",
execute(cl, msg) {},
};

17
src/cmds/regulamin.js Normal file
View File

@@ -0,0 +1,17 @@
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] });
},
};

View File

@@ -1,37 +0,0 @@
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'
// );
},
});

View File

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

View File

@@ -1,9 +0,0 @@
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

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

View File

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

View File

@@ -1,18 +0,0 @@
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,
});
}
});

View File

@@ -1,23 +0,0 @@
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);
});

BIN
src/fonts/Lexend-Bold.ttf Normal file

Binary file not shown.

BIN
src/fonts/Lexend-Thin.ttf Normal file

Binary file not shown.

94
src/functions/postgres.js Normal file
View File

@@ -0,0 +1,94 @@
const { lvl, randomExp } = require("./tools");
const { PrismaClient } = require("@prisma/client");
class Postgres {
constructor() {
this.client = new PrismaClient();
}
async messageCount(userID) {
return await this.client.users.update({
where: {
user_id: userID,
},
data: {
msg_count: {
increment: 1,
},
},
});
}
async profile(userID) {
return await this.client.users.findUnique({
where: {
user_id: userID,
},
});
}
async msg_state(userID) {
return await this.client.users.findUnique({
where: {
user_id: userID,
},
});
}
async addExp(userID, min, max) {
await this.#ifUserExist(userID).then(async () => {
const rExp = randomExp(min, max);
return await this.client.users.update({
where: {
user_id: userID,
},
data: {
exp: {
increment: rExp,
},
lvl: lvl(
(
await this.client.users.findUnique({
where: {
user_id: userID,
},
select: {
exp: true,
},
})
).exp
),
},
});
});
}
async #ifUserExist(userID) {
if ((await this.profile(userID)) == null) {
console.log("Account");
await this.client.users.create({
data: {
user_id: userID,
lvl: 0,
exp: 0,
},
});
}
}
async #ifMsgsExist(userID, channelID) {
if ((await this.profile(userID)) == null) {
console.log("Account");
await this.client.users.create({
data: {
user_id: userID,
lvl: 0,
exp: 0,
},
});
}
}
//addBadge: async function (args) {},
//giveBadge: async function (args) {},
}
module.exports.Postgres = Postgres;

19
src/functions/redis.js Normal file
View File

@@ -0,0 +1,19 @@
module.exports = {
expCheck: async function (userID, connect) {
date = new Date();
const user = await connect.get(userID);
if (user == null) {
await connect.set(userID, date.getTime());
return true;
} else {
date = await connect.get(userID);
const currentDate = new Date();
if (currentDate.getTime() - date > 60000) {
await connect.set(userID, currentDate.getTime());
return true;
} else {
return false;
}
}
},
};

23
src/functions/tools.js Normal file
View File

@@ -0,0 +1,23 @@
module.exports = {
lvl: function (exp) {
return Math.floor(Math.sqrt(exp) / 5);
},
expThreshold: function (lvl) {
return Math.floor(lvl * lvl * 25);
},
randomExp: function (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
},
roundRect: function (ctx, x, y, width, height, radius) {
if (width < 2 * radius) radius = width / 2;
if (height < 2 * radius) radius = height / 2;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
return ctx;
},
};

View File

@@ -1,28 +0,0 @@
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 };

View File

@@ -1,84 +0,0 @@
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

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

View File

@@ -1,10 +0,0 @@
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

@@ -1,22 +0,0 @@
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 };

View File

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

View File

@@ -1,27 +0,0 @@
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 };

View File

@@ -1,103 +0,0 @@
{
"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. */
}
}