Skip to content

Commit

Permalink
Update logging configuration, add Prettier configuration and modified…
Browse files Browse the repository at this point in the history
… eslints formating options
  • Loading branch information
chfuchte committed Dec 30, 2023
1 parent 07c8a78 commit 102bd5d
Show file tree
Hide file tree
Showing 68 changed files with 2,609 additions and 1,036 deletions.
21 changes: 13 additions & 8 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,23 @@ module.exports = {
es2021: true
},
extends: 'standard-with-typescript',
overrides: [{
files: ['./**/*.ts'],
rules: {
'@typescript-eslint/strict-boolean-expressions': 'off',
'@typescript-eslint/quotes': 'off'
overrides: [
{
files: ['./**/*.ts'],
rules: {
'@typescript-eslint/strict-boolean-expressions': 'off',
'@typescript-eslint/quotes': 'off',
'@typescript-eslint/space-before-function-paren': 'off',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/restrict-template-expressions': 'off',
'@typescript-eslint/indent': 'off'
}
}
}],
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json']
},
rules: {
}
rules: {}
}
2 changes: 1 addition & 1 deletion .github/workflows/build-non-master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: build-and-test-non-master
on:
push:
branches-ignore:
- 'master'
- 'master'

jobs:
docker:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/build-push-master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ jobs:
with:
context: .
push: true
tags: "${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:${{ env.BRANCH_NAME }},${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:${{ steps.meta.outputs.version }},${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:${{ env.COMMIT_SHA }},${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:latest"
tags: '${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:${{ env.BRANCH_NAME }},${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:${{ steps.meta.outputs.version }},${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:${{ env.COMMIT_SHA }},${{ env.REGISTRY }}/${{ env.IMAGE_REPOSITORY }}:latest'
# tags: ${{ steps.meta.outputs.tags }} #TAG from metadata-action
# labels: ${{ steps.meta.outputs.labels }} #TAG from metadata-action
# platforms: linux/amd64,linux/arm64
Expand Down
8 changes: 8 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 120,
"tabWidth": 2,
"useTabs": false
}
24 changes: 12 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
# Moderation Bot in TypeScript using discordjs v14
# Moderation Bot in TypeScript using discordjs v14

This project was programmed by some members of Florian Dalwigk's community discord which unfortunately doesn't exist anymore. You can find the new Discord Server [here](https://discord.gg/65pXxkSE5g). The bot uses discordjs v14 and is written entirely in TypeScript. We also use a github workflow to automatically deploy the bot on our own server.
This project was programmed by some members of Florian Dalwigk's community discord which unfortunately doesn't exist anymore. You can find the new Discord Server [here](https://discord.gg/65pXxkSE5g). The bot uses discordjs v14 and is written entirely in TypeScript. We also use a github workflow to automatically deploy the bot on our own server.

# Function overview

<div align="center">

| Command | Function |
| :---: | :----: |
| /kick | Kicks a user |
| /ban | Bans a user |
| /timeout | timeout a user |
| /warn | warns a user |
| /strike | strikes a user |
| /about | about me |
| /help | shows a multi page information widget |
| /bj help | shows the help information for the BlackJack sub commands |
| Command | Function |
| :------: | :-------------------------------------------------------: |
| /kick | Kicks a user |
| /ban | Bans a user |
| /timeout | timeout a user |
| /warn | warns a user |
| /strike | strikes a user |
| /about | about me |
| /help | shows a multi page information widget |
| /bj help | shows the help information for the BlackJack sub commands |

</div>

Expand Down
2 changes: 1 addition & 1 deletion logging.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"data": {
"path": "./logs"
},
},
"loggerImplementation": "FileConsoleLogger",
"minLevel": "LOG"
}
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"lint": "eslint --ignore-path .eslintignore --ext .js,.ts .",
"lint-fix": "eslint --ignore-path .eslintignore --ext .js,.ts . --fix",
"prepare": "husky install",
"test": "jest"
"test": "jest",
"format": "prettier --write ."
},
"devDependencies": {
"@jest/globals": "^29.3.1",
Expand All @@ -44,7 +45,8 @@
"husky": "^8.0.2",
"jest": "^29.3.1",
"nodemon": "^2.0.20",
"prettier": "^3.1.1",
"ts-jest": "^29.0.3",
"typescript": "^4.9.3"
}
}
}
80 changes: 54 additions & 26 deletions src/Bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,21 @@ import { AsyncDatabase } from './sqlite/sqlite'
import message from './listeners/message'
import path, { join } from 'path'
import { PersistentDataStorage } from './action/blackjack/persistentDataStorage'
import fs from "node:fs"
import { Button, Command, Menu, MessageContextMenu, Modal, UserContextMenu, isButton, isCommand, isMenu, isMessageContextMenu, isModal, isUserContextMenu } from './commandTypes'
import fs from 'node:fs'
import {
Button,
Command,
Menu,
MessageContextMenu,
Modal,
UserContextMenu,
isButton,
isCommand,
isMenu,
isMessageContextMenu,
isModal,
isUserContextMenu
} from './commandTypes'
import { handleBlackJackCommands } from './action/blackjack/handleCommands'
import { registerBlackJackCommands } from './action/blackjack/registerCommands'

Expand All @@ -21,7 +34,7 @@ const token = process.env.BOT_TOKEN

const dbFile = process.env.DB_PATH ?? './sqlite3.db'

async function init (): Promise<void> {
async function init(): Promise<void> {
try {
const db = await AsyncDatabase.open(dbFile)
logManager.logger('sqlite3').logSync('INFO', `DB opened ${path.resolve(dbFile)}`)
Expand Down Expand Up @@ -63,9 +76,18 @@ async function init (): Promise<void> {
identifier INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
giveaway_message_id TEXT NOT NULL,
dc_id TEXT NOT NULL,
hash TEXT NOT NULL UNIQUE ON CONFLICT REPLACE${'' /* Sollte mal ein Hash sein, ist aber keiner (nicht wundern) */}
hash TEXT NOT NULL UNIQUE ON CONFLICT REPLACE${
'' /* Sollte mal ein Hash sein, ist aber keiner (nicht wundern) */
}
)`)
if ((await db.getAsync("select count(*) as count from pragma_table_info('giveaways') where name = 'channel_id';", [])).count === 0) {
if (
(
await db.getAsync(
"select count(*) as count from pragma_table_info('giveaways') where name = 'channel_id';",
[]
)
).count === 0
) {
await db.runAsync(`ALTER TABLE giveaways add channel_id TEXT NULL`)
await db.runAsync(`ALTER TABLE giveaways add author_display_name TEXT NULL`)
await db.runAsync(`ALTER TABLE giveaways add author_avatar_url TEXT NULL`)
Expand All @@ -88,12 +110,12 @@ async function init (): Promise<void> {

const commands: Command[] = []
// command handling
const commandFiles = fs.readdirSync(join(__dirname, "commands")).filter(file => file.endsWith('.js'))
const commandFiles = fs.readdirSync(join(__dirname, 'commands')).filter((file) => file.endsWith('.js'))
for (const file of commandFiles) {
const command = (await import(`./commands/${file}`)).default
// check if command is a valid command
if (!command || !isCommand(command)) {
console.error("Command file is not valid " + file)
console.error('Command file is not valid ' + file)
continue
}
commands.push(command)
Expand All @@ -102,12 +124,12 @@ async function init (): Promise<void> {

const buttons: Button[] = []
// button handling
const buttonFiles = fs.readdirSync(join(__dirname, "buttons")).filter(file => file.endsWith('.js'))
const buttonFiles = fs.readdirSync(join(__dirname, 'buttons')).filter((file) => file.endsWith('.js'))
for (const file of buttonFiles) {
const button = (await import(`./buttons/${file}`)).default
// check if button is a valid button
if (!button || !isButton(button)) {
console.error("Button file is not valid " + file)
console.error('Button file is not valid ' + file)
continue
}
buttons.push(button)
Expand All @@ -116,12 +138,12 @@ async function init (): Promise<void> {

const menuInteractions: Menu[] = []
// menu handling
const menuFiles = fs.readdirSync(join(__dirname, "menuInteractions")).filter(file => file.endsWith('.js'))
const menuFiles = fs.readdirSync(join(__dirname, 'menuInteractions')).filter((file) => file.endsWith('.js'))
for (const file of menuFiles) {
const menu = (await import(`./menuInteractions/${file}`)).default
// check if menu is a valid menu
if (!menu || !isMenu(menu)) {
console.error("Menu file is not valid " + file)
console.error('Menu file is not valid ' + file)
continue
}
menuInteractions.push(menu)
Expand All @@ -130,12 +152,14 @@ async function init (): Promise<void> {

const messageContextMenuInteractions: MessageContextMenu[] = []
// message context menu handling
const messageContextMenuFiles = fs.readdirSync(join(__dirname, "messageContextMenuInteractions")).filter(file => file.endsWith('.js'))
const messageContextMenuFiles = fs
.readdirSync(join(__dirname, 'messageContextMenuInteractions'))
.filter((file) => file.endsWith('.js'))
for (const file of messageContextMenuFiles) {
const messageContextMenu = (await import(`./messageContextMenuInteractions/${file}`)).default
// check if message context menu is a valid message context menu
if (!messageContextMenu || !isMessageContextMenu(messageContextMenu)) {
console.error("Message context menu file is not valid " + file)
console.error('Message context menu file is not valid ' + file)
continue
}
messageContextMenuInteractions.push(messageContextMenu)
Expand All @@ -144,12 +168,12 @@ async function init (): Promise<void> {

const modalInteractions: Modal[] = []
// modal handling
const modalFiles = fs.readdirSync(join(__dirname, "modalInteractions")).filter(file => file.endsWith('.js'))
const modalFiles = fs.readdirSync(join(__dirname, 'modalInteractions')).filter((file) => file.endsWith('.js'))
for (const file of modalFiles) {
const modal = (await import(`./modalInteractions/${file}`)).default
// check if modal is a valid modal
if (!modal || !isModal(modal)) {
console.error("Modal file is not valid " + file)
console.error('Modal file is not valid ' + file)
continue
}
modalInteractions.push(modal)
Expand All @@ -158,27 +182,29 @@ async function init (): Promise<void> {

const userContextMenuInteractions: UserContextMenu[] = []
// user context menu handling
const userContextMenuFiles = fs.readdirSync(join(__dirname, "userContextMenuInteractions")).filter(file => file.endsWith('.js'))
const userContextMenuFiles = fs
.readdirSync(join(__dirname, 'userContextMenuInteractions'))
.filter((file) => file.endsWith('.js'))
for (const file of userContextMenuFiles) {
const userContextMenu = (await import(`./userContextMenuInteractions/${file}`)).default
// check if user context menu is a valid user context menu
if (!userContextMenu || !isUserContextMenu(userContextMenu)) {
console.error("User context menu file is not valid " + file)
console.error('User context menu file is not valid ' + file)
continue
}
userContextMenuInteractions.push(userContextMenu)
console.log(`User context menu ${userContextMenu.data.name} loaded`)
}

client.on("interactionCreate", async interaction => {
client.on('interactionCreate', async (interaction) => {
if (interaction.isCommand()) {
for await (const command of commands) {
if (command.data.name === interaction.commandName) {
await command.execute(interaction)
return
}
}
if (interaction.commandName === "bj") {
if (interaction.commandName === 'bj') {
await handleBlackJackCommands(interaction, logManager)
return
}
Expand Down Expand Up @@ -250,12 +276,12 @@ async function init (): Promise<void> {
})

if (token !== undefined) {
const tickers = fs.readdirSync(join(__dirname, "tick")).filter(file => file.endsWith('.js'))
const tickers = fs.readdirSync(join(__dirname, 'tick')).filter((file) => file.endsWith('.js'))
for (const file of tickers) {
const ticker = (await import(`./tick/${file}`)).default
// check if ticker is a valid ticker
if (!ticker || typeof ticker !== "function") {
console.error("Ticker file is not valid " + file)
if (!ticker || typeof ticker !== 'function') {
console.error('Ticker file is not valid ' + file)
continue
}
setInterval(() => ticker(client), 1000 * 60)
Expand All @@ -264,15 +290,17 @@ async function init (): Promise<void> {
}

registerCommands(client, logManager.logger('Command-Registrierung'), [
...commands.map(command => command.data),
...messageContextMenuInteractions.map(messageContextMenu => messageContextMenu.data),
...userContextMenuInteractions.map(userContextMenu => userContextMenu.data),
...commands.map((command) => command.data),
...messageContextMenuInteractions.map((messageContextMenu) => messageContextMenu.data),
...userContextMenuInteractions.map((userContextMenu) => userContextMenu.data),
registerBlackJackCommands()
])

await client.login(token)
} catch (err) {
logManager.logger().logSync('ERROR', `Failed to initialize system. Used db ${path.resolve(dbFile)}, error: ${JSON.stringify(err)}`)
logManager
.logger()
.logSync('ERROR', `Failed to initialize system. Used db ${path.resolve(dbFile)}, error: ${JSON.stringify(err)}`)
}
}

Expand Down
17 changes: 5 additions & 12 deletions src/action/blackjack/handleCommands.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { IGameData, PersistentDataStorage } from './persistentDataStorage'
import { getBet } from './remote-api'
import {
CommandInteraction,
CommandInteractionOptionResolver
} from 'discord.js'
import { CommandInteraction, CommandInteractionOptionResolver } from 'discord.js'
import { handleHighscore } from './slashCommands/Highscore'
import { handlePlay } from './slashCommands/Play'
import { handleScore } from './slashCommands/Score'
Expand All @@ -21,7 +18,9 @@ export const handleBlackJackCommands = async (interaction: CommandInteraction, l
const options = interaction.options as CommandInteractionOptionResolver
const subcommand = options.getSubcommand(true)

await logger.logger('BlackJack').log('DEBUG', `Received BJ subcommand = ${subcommand} from user ${interaction.user.tag}`)
await logger
.logger('BlackJack')
.log('DEBUG', `Received BJ subcommand = ${subcommand} from user ${interaction.user.tag}`)

if (subcommand === 'highscore') {
content = await handleHighscore()
Expand Down Expand Up @@ -59,13 +58,7 @@ export const handleBlackJackCommands = async (interaction: CommandInteraction, l
}

export const evalResult = async (storeElement: IGameData): Promise<string> => {
const {
dealersSecondCard,
dealersAdditionalCard,
result,
payout,
dealerTotal
} = await getBet(storeElement)
const { dealersSecondCard, dealersAdditionalCard, result, payout, dealerTotal } = await getBet(storeElement)
if (storeElement.secondBetId) {
storeElement.betId = storeElement.secondBetId
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Expand Down
Loading

0 comments on commit 102bd5d

Please sign in to comment.