Tobias Hopp 6102599e5d Update bot
Took 2 hours 17 minutes
2021-03-15 09:32:14 +01:00

359 lines
12 KiB
JavaScript

// Required Things
const Discord = require ( "discord.js" );
const config = require ( "./config.json" );
const AntiSpam = require ( "discord-anti-spam" );
const mySQL = require( "mysql2" );
// new Discord Client
const client = new Discord.Client ( {partials: [ 'MESSAGE', 'CHANNEL' ], disableMentions: "none"} );
const antiSpam = new AntiSpam ( {
warnThreshold: 4, // Amount of messages sent in a row that will cause a warning.
muteThreshold: 6, // Amount of messages sent in a row that will cause a mute
kickThreshold: 10, // Amount of messages sent in a row that will cause a kick.
banThreshold: 15, // Amount of messages sent in a row that will cause a ban.
maxInterval: 2300, // Amount of time (in milliseconds) in which messages are considered spam.
warnMessage: '{@user}, du hast eine Verwarnung für Spaming erhalten.', // Message that will be sent in chat upon warning a user.
kickMessage: '**{user_tag}** wurde wegen Spaming von unserem Server gekickt.', // Message that will be sent in chat upon kicking a user.
muteMessage: '**{user_tag}** wurde wegen Spaming temporär stumm geschaltet.',// Message that will be sent in chat upon muting a user.
banMessage: '**{user_tag}** wurde wegen Spaming von unserer Community ausgeschlossen.', // Message that will be sent in chat upon banning a user.
maxDuplicatesWarning: 5, // Amount of duplicate messages that trigger a warning.
maxDuplicatesKick: 10, // Amount of duplicate messages that trigger a warning.
maxDuplicatesBan: 15, // Amount of duplicate messages that trigger a warning.
exemptPermissions: [ 'ADMINISTRATOR' ], // Bypass users with any of these permissions.
ignoreBots: true, // Ignore bot messages.
verbose: true, // Extended Logs from module.
ignoredUsers: [], // Array of User IDs that get ignored.
muteRoleName: "Muted", // Name of the role that will be given to muted users!
removeMessages: true // If the bot should remove all the spam messages when taking action on a user!
// And many more options... See the documentation.
} );
const con = mySQL.createConnection ( {
host: config.mysqlHost,
user: config.mysqlUsername,
password: config.mysqlPassword,
port: config.mysqlPort,
database: config.mysqlDatabase
} );
let badWords = {}; // 0 => {1:2,}
let error = false;
con.connect(function(err) {
if (err) {
console.log ( "[ERROR] Cannot connect to database! Critical error" );
process.exit();
return;
}
console.log("[INFO] Connected to mySQL Server!");
});
client.on ( "ready", () =>
{
console.log ( "[INFO] Bot is now ready" );
client.user.setPresence ( {
activity:
{
name: "Reading your lovely messages",
type: 'PLAYING'
}
} ).then ( r =>
{
console.log ( "[INFO] Presence set" );
} );
if( loadAllUp() === false )
{
client.user.setPresence ( {
activity:
{
name: "Error 0",
type: 'PLAYING'
}
} ).then ( r =>
{
console.log ( "[INFO] Error 0 presence shown" );
error = true;
} );
}
} );
client.on ( "message", async ( message ) =>
{
if ( message.author.bot ) return;
// Beleidigungsfilter?
if ( !message.content.startsWith ( config.prefix ) )
{
// Check if the user has Admin permissions, so skip him
if ( message.member.hasPermission ( "ADMINISTRATOR" ) ) return;
// Filter goes here
if ( checkMessage ( message.guild.id, message.content ) )
{
await message.delete ();
let notifyChannelID = getNotifyChannel ( message.guild.id );
if ( notifyChannelID.length === 0 || notifyChannelID === 0 )
{
// NotifyChannel not send, so we gonna send the msg here
const notify = new Discord.MessageEmbed ()
.setColor ( "#b30202" )
.setTitle ( "Nachricht gelöscht" )
.setDescription ( `Es wurde eine Nachricht von ${ message.author.toString () } entfernt, da ein dort enthaltenes Wort auf der Blacklist steht.\n\nMir wurde noch nicht gesagt, wo ich Nachricht wie diese hinschreiben soll.\nDu kannst dies als Administrator mit ".w setNotify" in einem beliebigen Channel setzen.` )
message.channel.send( `**Nachricht gelöscht!**\nEs wurde eine Nachricht von ${ message.author.toString () } entfernt, da ein dort enthaltenes Wort auf der Blacklist steht.\n\nÜbrigens, mir wurde noch nicht gesagt, wo ich Nachricht wie diese hinschreiben soll.\nDu kannst dies als Administrator mit ".w setNotify" in einem beliebigen Channel setzen.` ).then ( () =>
{
} ).catch ( reason =>
{
console.log ( "[ERROR] Cannot send a message on guild " + message.guild.id + " in channel " + message.channel.id + " " + reason.message );
} );
} else
{
const notifyChannel = message.member.guild.channels.cache.find ( ch => ch.id === notifyChannelID );
const notify = new Discord.MessageEmbed ()
.setColor ( "#b30202" )
.setTitle ( "Nachricht gelöscht" )
.setDescription ( `Es wurde eine Nachricht von ${ message.author.toString () } entfernt, da ein dort enthaltenes Wort auf der Blacklist steht.` );
notifyChannel.send ( `Nachricht gelöscht!\nEs wurde eine Nachricht von ${ message.author.toString () } entfernt, da ein dort enthaltenes Wort auf der Blacklist steht.` ).then ( () =>
{
} ).catch ( () =>
{
console.log ( "[ERROR] Cannot send a message on guild " + message.guild.id + " in channel " + message.channel.id );
} );
}
}
return;
}
// Commands here
if ( !message.member.hasPermission ( "ADMINISTRATOR" ) )
{
await message.reply ( "mir wurde beigebracht, dass ich mit fremden Leuten nicht reden darf :c" );
return;
}
let notifyChannelID = getNotifyChannel ( message.guild.id );
const commandBody = message.content.slice ( config.prefix.length );
const args = commandBody.split ( ' ' ); // 1=> arg
const command = args.shift ().toLowerCase ();
if ( command === "ping" ) {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(`Der Ping von mir liegt bei ${timeTaken}ms.`).then(() => {
});
}
if ( command === "list" || command === "auflisten" || command === "liste" || command === "filter" )
{
// Listet alle Wörter des Servers mit indexen auf
let words = listWords( message.guild.id );
if( words === false )
{
await message.reply( `ich konnte deinen Filter nicht abrufen! - Bitte versuche es später erneut :c` );
return;
}
let output = "";
for ( let wordsKey in words )
{
output += `${wordsKey}\t | \t${words[wordsKey]}\n`;
}
await message.channel.send ( `Folgende Wörter & Sätze stehen auf der Schwarzen Liste:\nIndex\tWort\n` + output );
}
if ( command === "remove" || command === "delete" || command === "del" )
{
if ( args.length > 0)
{
const index = Number.parseInt ( args[0] );
if ( !isNaN ( index ) )
{
if( deleteWord( message.guild.id, args[0] ) === true )
{
await message.reply( `ich habe Index erfolgreich gelöscht! :D` );
}
else
{
await message.reply( `ich konnte den Index nicht entfernen. Hast du dich vielleicht vertippt?` );
}
} else
{
await message.reply ( `bitte gebe einen Index mit an. ${ config.prefix }delete <index>` )
}
} else
{
await message.reply ( `bitte gebe einen Index mit an. ${ config.prefix }delete <index>` )
}
}
if ( command === "add" || command === "hinzufügen" || command === "addword" )
{
if ( args.length > 0 )
{
if( addWord ( message.guild.id, args[0] ) )
{
await message.reply( `ich habe das Wort oder den Satz erfolgreich zu deinem Filter hinzugefügt! :D` );
}
else
{
await message.reply( `Oopsie! Ich konnte den Filter nicht verändern - Wende dich bitte an den Support!` );
}
} else
{
await message.reply ( `bitte gebe ein Wort/Satz mit an. ${ config.prefix }add <Wort/Satz>` );
}
}
} );
client.on ( "guildCreate", ( guild ) =>
{
console.log ( `[INFO] Joined a new guild named "${ guild.name }" with ID ${ guild.id }` );
createServerEntry ( guild.id, guild.name );
} );
function createServerEntry( a_ServerID, a_ServerName )
{
console.log ( `[INFO] Creating server entry...` );
let query = "INSERT INTO guilds ( guild_id, server_name ) VALUES ( ?, ? )";
con.query( query, [ a_ServerID, a_ServerName ], function( error, results, fields )
{
if( error )
{
console.log ( `[ERROR] An error occurred while creating a new guild in database: ${error.message} ` );
return false;
}
return true;
} );
}
function checkMessage( a_ServerID, a_Message )
{
/*let query = "SELECT word FROM words WHERE word LIKE ?";
con.query( query, ['%' + a_Message + '%'], function( error, results, fields ) {
if( error )
{
console.log ( `[ERROR] An error occurred while fetching th` )
}
} );*/
for (const badWordsKey in badWords[a_ServerID] ) {
if( a_Message.includes( badWords[a_ServerID][badWordsKey] ) )
{
return true;
}
}
return false;
}
async function refreshWords( a_ServerID )
{
let success = false;
console.log( "[INFO] Loading filter for guild " + a_ServerID )
// Add the word to the database
let query = "SELECT id, word FROM words WHERE guildID = ?";
let results = await con.query( query );
badWords[a_ServerID] = {};
for (let i = 0; i < results.length; i++ ) {
badWords[a_ServerID][results[i].id] = results[i].word;
}
return true;
}
async function loadAllUp()
{
console.log( "[INFO] Loading all up..." );
// LOADING ALL UP, can take a while
// Add the word to the database
let query = "SELECT id, guild_id FROM guilds";
let [results] = await con.promise().query( query );
for (let i = 0; i < results.length; i++) {
refreshWords( results[i].guild_id );
}
return true;
}
async function getNotifyChannel( a_ServerID )
{
let query = "SELECT id, notify_channel FROM guilds WHERE guilds.guild_id = ?";
let results = await con.query( query, [ a_ServerID ] );
if( results.length < 1 )
{
createServerEntry( a_ServerID );
return getNotifyChannel( a_ServerID );
}
return results.notify_channel;
}
// function broken i guess, the console.log is not getting out, so idk what happening
async function deleteWord( a_ServerID, a_Index )
{
// Delete the word out of the database
// Add the word to the database
let success = false;
let query = "DELETE FROM words WHERE id = ? AND guildID = ?";
let results = await con.query( query, [a_Index, a_ServerID] );
refreshWords( a_ServerID );
return true;
}
async function addWord( a_ServerID, a_Word )
{
let success = false;
// Add the word to the database
let query = "INSERT INTO words ( word, guildID ) VALUES ( ?, ? )";
let results = await con.query( query, [ a_Word, a_ServerID ] );
refreshWords( a_ServerID );
return true;
}
function listWords( a_ServerID )
{
return badWords[a_ServerID];
}
// Discord Login
client.login ( config.TOKEN ).then ( r =>
{
console.log ( "[INFO] Logged in as Woam" )
} );