copy from ttt bot

This commit is contained in:
mightypanders 2022-01-03 15:07:49 +01:00
commit 7ac09678a1
16 changed files with 675 additions and 0 deletions

5
.eslintrc Normal file
View File

@ -0,0 +1,5 @@
{
"parser": "@typescript-eslint/parser",
"plugins":["@typescript-eslint"],
"extends":["plugin:@typescript-eslint/recommended"]
}

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
node_modules/
build/
yarn-error.log
.env

30
README.md Normal file
View File

@ -0,0 +1,30 @@
## Requirements
- yarn
- npm
## Environment Variables
- `BOT_TOKEN` -> acquire this from your Discord Application Page
- `GUILD_ID` -> the guild this bot should be active in. Still needs to be determined manually for the moment.
- `CLIENT_ID` -> not used right now
If you want to use this locally put these values into a file called `.env` in the project root.
```.env
BOT_TOKEN=<value here>
GUILD_ID=<value here>
CLIENT_ID=<value here>
```
## Usage
- Clone repo
- cd into dir
- `yarn install`
### Building
- `yarn run build`
### Start local instance
- `yarn run watch` for hot recompile on changes
- `yarn run monitor` for hot reload on recompile
### Start normal instance
- `yarn run start`

13
index.ts Normal file
View File

@ -0,0 +1,13 @@
import express, { Application } from "express"
import { config } from "./server/configuration"
import DiscordAdapter from "./server/discordAdapter"
import Routes from "./server/routes"
import Server from "./server/server"
const server = Server.init(config.port)
server.start(() => {
console.log(`Server running on port ${server.getPort()}`)
new Routes().setRoutes(server.getApp())
const discordAdapter = new DiscordAdapter()
})

19
jest.config.js Normal file
View File

@ -0,0 +1,19 @@
module.exports = {
'roots': [
'<rootDir>/tests',
'<rootDir>/server'
],
'transform': {
'^.+\\.tsx?$': 'ts-jest'
},
'testRegex': '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
'moduleFileExtensions': [
'ts',
'tsx',
'js',
'jsx',
'json',
'node'
],
};

47
package.json Normal file
View File

@ -0,0 +1,47 @@
{
"name": "discord-event-bot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc",
"clean": "rimraf build",
"watch": "yarn run clean && yarn run build -- -w",
"monitor": "nodemon build/index.js",
"start": "yarn run build && node build/index.js",
"lint":"eslint . --ext .ts",
"lint":"eslint . --ext .ts --fix",
"test": "jest",
"test-watch": "jest --watch",
"test-coverage": "jest --coverage"
},
"author": "",
"license": "ISC",
"dependencies": {
"@discordjs/rest": "^0.1.0-canary.0",
"axios": "^0.24.0",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"discord-api-types": "^0.24.0",
"discord.js": "^13.3.1",
"dotenv": "^10.0.0",
"eslint": "^8.2.0",
"express": "^4.17.1",
"jest": "^27.3.1",
"typescript": "^4.4.4",
"winston": "^3.3.3"
},
"devDependencies": {
"@tsconfig/recommended": "^1.0.1",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/jest": "^27.0.2",
"@typescript-eslint/eslint-plugin": "^5.3.0",
"@typescript-eslint/parser": "^5.3.0",
"jest-cli": "^27.3.1",
"nodemon": "^2.0.14",
"rimraf": "^3.0.2",
"ts-jest": "^27.0.7"
}
}

25
server/MuteHandler.ts Normal file
View File

@ -0,0 +1,25 @@
import RegistrationHandler from "./RegistrationHandler"
export default class MuteHandler {
public mute(player: string): boolean {
const register = RegistrationHandler.Instance
const binding = register.getNameRegisteredForSteamUser(player)
console.log(`Performing mute wizardry on ${player}, ${JSON.stringify(binding)}`)
return true
}
public unmute(player: string): boolean {
const register = RegistrationHandler.Instance
const binding = register.getNameRegisteredForSteamUser(player)
console.log(`Performing unmute wizardry on ${player}`)
return true
}
public unmuteAll(): boolean {
const register = RegistrationHandler.Instance
const binding = register.getAllMappings()
console.log(`Performing unmute wizardry on all players`)
return true
}
}

View File

@ -0,0 +1,55 @@
import { GuildMember } from "discord.js"
import { Maybe, userNameBinding } from "./interfaces"
export default class RegistrationHandler {
private userRegister: userNameBinding[] = []
private static _instance: RegistrationHandler
public constructor() {
console.log('Setup RegistrationHandler')
}
public static get Instance() {
return this._instance || (this._instance = new this())
}
public register(discordUser: GuildMember, steamname: string): boolean {
try {
const binding: userNameBinding = {
Steam: steamname,
DiscordUser: discordUser
}
console.log(`Trying to register ${JSON.stringify(binding)}`)
let alreadyPresentBinding = this.userRegister.find(x => x.DiscordUser.user.username == binding.DiscordUser.user.username)
if (alreadyPresentBinding) {
console.log(`Binding already present: ${JSON.stringify(alreadyPresentBinding)}, overwriting.`)
alreadyPresentBinding = binding
}
else {
this.userRegister.push(binding)
console.log(`Binding successfully added.`)
}
} catch (error) {
console.error(error)
return false
}
return true
}
public getAllMappings(): userNameBinding[] {
return this.userRegister
}
public removeUser(discordUser: GuildMember): void {
this.userRegister = this.userRegister.filter(x => x.DiscordUser.user.id !== discordUser.user.id)
}
public getNameRegisteredForDiscordUser(discordUser: GuildMember): Maybe<userNameBinding> {
return this.userRegister.find(x => x.DiscordUser.user.id == discordUser.user.id)
}
public getNameRegisteredForSteamUser(steamUser: string): Maybe<userNameBinding> {
return this.userRegister.find(x => x.Steam == steamUser)
}
public listRegisteredMembers(): string {
const output = this.userRegister.map(x => `${x.DiscordUser.user.username} : ${x.Steam}\n`)
return output.join()
}
private printHelpText(): string { return "" }
private buildHelpText(): string { return "" }
}

27
server/configuration.ts Normal file
View File

@ -0,0 +1,27 @@
import dotenv from "dotenv"
dotenv.config()
export const config = {
server: {
bodyParser: {
urlEncodedOptions: {
inflate: true,
limit: '5mb',
type: 'application/x-www-form-urlencoded',
extended: true,
parameterLimit: 1000
},
jsonOptions: {
inflate: true,
limit: '5mb',
type: 'application/json',
strict: true
}
}
},
debug: true,
port: 1234,
token: process.env.BOT_TOKEN ?? "",
guild_id: process.env.GUILD_ID ?? "",
client_id: process.env.CLIENT_ID ?? ""
}

52
server/constants.ts Normal file
View File

@ -0,0 +1,52 @@
import { localized_string } from "./interfaces"
export const reactions = {
troll_grin: "U+1F92A",
angry_face: "U+1F621",
ok: "U+1F44C"
}
export const commands = {
LIST_COMMAND: "list",
REGISTER_COMMAND: "register",
REMOVE_COMMAND: "remove",
SHOW_FOR_STEAM_COMMAND: "forsteam",
SHOW_COMMAND: "show"
}
export const msg_strings: localized_string = {
greeting: {
german: "Ich wurde neugestartet. Bitte registriert euch erneut, falls ihr automatisch gemutet werden wollt :)",
english: "I have been restarted. Please register again if you want to be muted automatically :)"
},
fmt_registered_user: {
german: "Habe den Steamname {steam_name} mit dem Discordnamen {discord_name} verknüpft.",
english: "Registered the steam name {steam_name} for the discord name {discord_name}."
},
fmt_registered_for_steam: {
german: "Aktuell registriert für User {steam_name}: {discord_name}",
english: "Currently registered for user {steam_name}: {discord_name}"
},
fmt_registered_for_discord: {
german: "Aktuell registriert für User {discord_name}: {steam_name}",
english: "Currently registered for user {discord_name}: {steam_name}"
},
user_was_not_registered: {
german: "Du warst gar nicht registriert.",
english: "You weren't even registered.",
},
user_has_been_removed: {
german: "Du wurdest aus der Liste entfernt.",
english: "You were removed from the list.",
},
currently_registered: {
german: "Aktuell registriert: \n {playerlist}",
english: "Currently registered: \n {playerlist}"
},
troll_rejection: {
german: "Nöööö, du nicht...",
english: "Naaaah, not you..."
},
troll_rejection_second_part: {
german: "Spaß, hab dich registriert: :P",
english: "Just kidding, you are registered: :P"
}
}

149
server/discordAdapter.ts Normal file
View File

@ -0,0 +1,149 @@
import { REST } from '@discordjs/rest'
import { SlashCommandBuilder } from '@discordjs/builders'
import { commands } from './constants'
import { Routes } from 'discord-api-types/v9'
import { config } from './configuration'
import { Client, CommandInteraction, GuildMember, Intents, Interaction } from 'discord.js'
import RegistrationHandler from './RegistrationHandler'
import { discordCommand } from './interfaces'
export default class DiscordAdapter {
private rest: REST
private client: Client
private registration: RegistrationHandler
public constructor() {
this.rest = new REST({ version: '9' }).setToken(config.token)
this.client = new Client({ intents: [Intents.FLAGS.GUILDS] })
this.registration = RegistrationHandler.Instance
this.setupCallbacks(this.client)
this.client.login(config.token)
this.registerCommands(this.commandList)
}
public async registerCommands(pCommands: discordCommand[]) {
try {
console.log('Refreshing slash commands')
await this.rest.put(Routes.applicationGuildCommands(config.client_id, config.guild_id), { body: pCommands })
console.log('Successfully refreshed slash commands')
} catch (error) {
console.log(`Error refreshing slash commands: ${error}`)
}
}
private setupCallbacks(c: Client) {
c.on('ready', () => {
console.log(`Logged in as ${c.user?.tag}`)
})
c.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return
const interactionCommand = this.commandList.find(x => x.name == interaction.commandName)
if (interactionCommand)
interactionCommand.performCommand(interaction, this.registration)
})
}
public async echoes(interaction: CommandInteraction, registration: RegistrationHandler): Promise<void> {
const value = interaction.options.getString('input')
const member: GuildMember = <GuildMember>interaction.member
try {
console.log(`Member ${member.user.username} mute state: ${member.voice.mute}`)
member.voice.setMute(!member.voice.mute, "test")
} catch (error) {
console.error(error)
}
await interaction.reply(`This should be an echo: ${value}`)
}
public async listUsers(interaction: CommandInteraction, registration: RegistrationHandler): Promise<void> {
const result = registration.listRegisteredMembers()
await interaction.reply(result)
}
public async removeUser(interaction: CommandInteraction, registration: RegistrationHandler): Promise<void> {
const discordUser: GuildMember = <GuildMember>interaction.member
registration.removeUser(discordUser)
await interaction.reply(`User has been removed`)
return
}
public async registerUser(interaction: CommandInteraction, registration: RegistrationHandler): Promise<void> {
const discordUser: GuildMember = <GuildMember>interaction.member
const steamNameToRegister = interaction.options.getString('steamname')
console.dir(discordUser)
if (!steamNameToRegister) {
await interaction.reply(`No steam name supplied, can't register`)
}
else {
registration.register(discordUser, steamNameToRegister)
await interaction.reply(`This should register user ${discordUser.user.username} with id ${discordUser.user.id} to use steamname: ${steamNameToRegister}`)
}
return
}
public async showForSteam(interaction: CommandInteraction, registration: RegistrationHandler): Promise<void> {
const steamName = interaction.options.getString('steamname')
if (!steamName) {
await interaction.reply(`No steam name supplied, can't search`)
} else {
const result = registration.getNameRegisteredForSteamUser(steamName)
await interaction.reply(JSON.stringify(result, null, 2))
}
return
}
public async show(interaction: CommandInteraction, registration: RegistrationHandler): Promise<void> {
const discordUser: GuildMember = <GuildMember>interaction.member
const result = registration.getNameRegisteredForDiscordUser(discordUser)
await interaction.reply(JSON.stringify(result, null, 2))
return
}
public commandList: discordCommand[] = [
{
name: "echo",
description: "Echoes a string",
performCommand: this.echoes,
options: [
{
name: 'input',
description: 'The input that should be echoed',
required: true,
type: 3
}
]
},
{
name: commands.LIST_COMMAND,
description: "Lists all registerd users",
performCommand: this.listUsers
},
{
name: commands.REMOVE_COMMAND,
description: "Remove the mapping for this discord user",
performCommand: this.removeUser
},
{
name: commands.REGISTER_COMMAND,
description: "Register the senders discord name for a supplied steam name",
options: [
{
name: 'steamname',
description: 'The steamname that should be registered',
required: true,
type: 3
}
],
performCommand: this.registerUser
},
{
name: commands.SHOW_FOR_STEAM_COMMAND,
description: "Show the discord that's registered for a steam name",
performCommand: this.showForSteam,
options: [
{
name: 'steamname',
description: 'The steamname that should be searched',
required: true,
type: 3
}
],
},
{
name: commands.SHOW_COMMAND,
description: "Show the Steamname that's registered for this discord name",
performCommand: this.show
}
]
}

24
server/interfaces.ts Normal file
View File

@ -0,0 +1,24 @@
import { CommandInteraction, GuildMember } from "discord.js"
import RegistrationHandler from "./RegistrationHandler"
export type Maybe<T> = T | undefined
export interface Player {
name: string
}
export type supported_languages = "german" | "english"
export interface localized_string {
[k: string]: {
german: string,
english: string
}
}
export interface userNameBinding {
Steam: string,
DiscordUser: GuildMember
}
export interface discordCommand {
name: string,
description: string
options?: any[]
performCommand(interaction: CommandInteraction, registration: RegistrationHandler): Promise<void>
}

36
server/routes.ts Normal file
View File

@ -0,0 +1,36 @@
import express from "express";
import MuteHandler from "./MuteHandler";
export default class Routes {
public constructor(
private muteHandler = new MuteHandler()
) { }
public setRoutes(app: express.Application): void {
app.route('').get(this.landingPage.bind(this))
app.route('/').get(this.landingPage.bind(this))
app.route('/mute').post(this.mutePlayer.bind(this))
app.route('/unmute/all').post(this.unmuteAll.bind(this))
app.route('/unmute/:id').post(this.unmutePlayer.bind(this))
}
private async mutePlayer(req: express.Request, res: express.Response): Promise<void> {
const playerName = req.body.name
console.log(`Muting player ${playerName}`)
this.muteHandler.mute(playerName)
res.status(200).json()
}
private async unmuteAll(_: express.Request, res: express.Response): Promise<void> {
console.log(`Unmuting all players`)
this.muteHandler.unmuteAll()
res.status(200).json()
}
private async unmutePlayer(req: express.Request, res: express.Response): Promise<void> {
const playerName = req.body.name
console.log(`Unmuting player ${playerName}`)
this.muteHandler.unmute(playerName)
res.status(200).json()
}
private async landingPage(_: express.Request, res: express.Response): Promise<void> {
res.send('Hello World')
}
}

36
server/server.ts Normal file
View File

@ -0,0 +1,36 @@
import bodyParser from "body-parser"
import cors from "cors"
import express from "express"
import { config } from "./configuration"
export default class Server {
private app: express.Application
private port: number
public constructor(port: number) {
this.port = port
this.app = express()
}
public static init(port: number): Server {
return new Server(port)
}
public start(callback: (...args: any[]) => void): void {
this.setBodyParser()
this.setCors()
this.getApp().listen(this.port, callback)
}
public getApp(): express.Application {
return this.app
}
public getPort(): number {
return this.port
}
private setBodyParser(): void {
this.getApp().use(bodyParser.urlencoded(config.server.bodyParser.urlEncodedOptions))
this.getApp().use(bodyParser.json(config.server.bodyParser.jsonOptions))
}
private setCors(): void {
this.getApp().use(cors())
}
}

View File

@ -0,0 +1,91 @@
import { GuildMember } from "discord.js"
import RegistrationHandler from "../server/RegistrationHandler"
const guildMember: GuildMember = <GuildMember><unknown>{
guild: {
id: 'guild_id',
name: 'Bot Playground',
icon: null,
features: [],
commands: { permissions: [], guild: [] },
members: { guild: [] },
channels: { guild: [] },
bans: { guild: [] },
roles: { guild: [] },
presences: {},
voiceStates: { guild: [] },
stageInstances: { guild: [] },
invites: { guild: [] },
deleted: false,
available: true,
shardId: 0,
splash: null,
banner: null,
description: null,
verificationLevel: 'NONE',
vanityURLCode: null,
nsfwLevel: 'DEFAULT',
discoverySplash: null,
memberCount: 2,
large: false,
applicationId: null,
afkTimeout: 300,
afkChannelId: null,
systemChannelId: 'channel_id',
premiumTier: 'NONE',
premiumSubscriptionCount: 0,
explicitContentFilter: 'DISABLED',
mfaLevel: 'NONE',
joinedTimestamp: 1636540056755,
defaultMessageNotifications: 'ALL_MESSAGES',
systemChannelFlags: { bitfield: 0 },
maximumMembers: 250000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLUses: null,
rulesChannelId: null,
publicUpdatesChannelId: null,
preferredLocale: 'en-US',
ownerId: 'ownerID',
emojis: { guild: [] },
stickers: { guild: [] }
},
joinedTimestamp: 1636539420924,
premiumSinceTimestamp: null,
deleted: false,
nickname: null,
pending: false,
_roles: [],
user: {
id: 'user_id',
bot: false,
system: false,
flags: { bitfield: 256 },
username: 'username',
discriminator: '0965',
avatar: 'avatar_string',
banner: undefined,
accentColor: undefined
},
avatar: null
}
const registeredUser = {
"Steam": "abc",
"DiscordUser": guildMember
}
test(`Instances`, () => {
const register = RegistrationHandler.Instance
expect(register).toBeDefined()
})
test(`Registration works`, () => {
const register = RegistrationHandler.Instance
register.register(<GuildMember>guildMember, "abc")
const result = register.getAllMappings()
console.log(JSON.stringify(result))
expect(result).toBeDefined()
expect(result).toEqual([registeredUser])
})

62
tsconfig.json Normal file
View File

@ -0,0 +1,62 @@
{
"extends":"@tsconfig/recommended/tsconfig.json",
"compilerOptions": {
/* Basic Options */
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"resolveJsonModule": true,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./build" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
"inlineSourceMap": true /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}