Skip to content

Commit

Permalink
using http requests instead of the database
Browse files Browse the repository at this point in the history
  • Loading branch information
marceltransier committed Apr 2, 2018
1 parent b3b8771 commit e094644
Show file tree
Hide file tree
Showing 10 changed files with 288 additions and 236 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
discord_bot/node_modules/
discord_bot/package-lock.json
config.json
discord_bot/config.json
31 changes: 16 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,50 +7,51 @@
[![price](https://img.shields.io/badge/price-free-brightgreen.svg)](LICENSE)
[![gmod-addon](https://img.shields.io/badge/gmod-addon-_.svg?colorB=1194EF)](https://wiki.garrysmod.com)
[![discord-bot](https://img.shields.io/badge/discord-bot-_.svg?colorB=8C9EFF)](https://discord.js.org)
![i-like-badges](https://img.shields.io/badge/world's_coolest_color-green-_.svg?colorB=00FF00)
[![i-like-badges](https://img.shields.io/badge/world's_coolest_color-green-_.svg?colorB=00FF00)](https://github.com/marceltransier)
[![license](https://img.shields.io/github/license/marceltransier/ttt_discord_bot.svg)](LICENSE)


This is a powerful [discord bot](https://discord.js.org) that mutes dead players in [TTT](http://ttt.badking.net) (Garry's Mod - Trouble in Terrorist Town)

## Getting Started
If you don't know how to install MySQL or Nodejs on your server, follow my [step-by-step guide on steam](http://steamcommunity.com/sharedfiles/filedetails/?id=1343501656)
If you need step-by-step tutorial, follow my [guide on steam]()

### Prerequisites
- You have to have allready installed a Garry's Mod Server with the TTT Gamemode
- You must have MySQL and [Nodejs](https://nodejs.org) installed
- You need [Mysqloo](https://github.com/FredyH/MySQLOO) installed on you Garry's Mod Server (follow the [install instructions](https://github.com/FredyH/MySQLOO/blob/master/README.md#install-instructions))
- You must have [Nodejs](https://nodejs.org) installed

### Installation
1. Clone this repository into your addons folder and install the requirements
1. Clone this repository (to e.g. your home folder) and install the requirements
```bash
cd ~
git clone https://github.com/marceltransier/ttt_discord_bot.git
npm install --prefix ./ttt_discord_bot/discord_bot/
cd ttt_discord_bot
npm install --prefix ./discord_bot/
```
2. Rename the `config.json.example` in `config.json`

3. Create Discord Bot, invite him to your server and paste the token in the config

- if you don't know how to, follow [this guide](https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token)
- insert the bot token at `discord -> token` in the config.json
4. Insert the Guild *(Server)* id and the channel id in the config
- if you don't know how to get these id's, follow [this guide](https://support.discordapp.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID-)
- insert the guild id at `discord -> guild` and the cannel id of the voice channel in wich the bot should mute dead players at `discord -> channel` in the config.json
5. Setting up MySQL
- Create a MySQL database and user with privileges on the database for the bot
- insert the MySQL host, user, password and database in the config.json
5. Add the addon to the garrysmod server
- Download the .gma file from [here]() and put it in the garrysmod/addons folder
- Or add the [workshop object]() to the servers collection
### Usage
- Start the bot by runing the node command with the `ttt_discord_bot/discord_bot/` directory
- Connect your Steam Account with the bot by typing `!discord YourDiscordTag` in the ingame chat. E.g `!discord marcel.js#4402`. If you're lazy and there is nobody else with your discord discriminator (`#4402`) in the ttt channel, it's enough if you use this. E.g. `!discord 4402`
- If you're **dead in Garry's Mod**, the **game-state is in progress**, you're **connected with discord** and you're in the **configured voice channel**, the bot will mute you.
- If you're in the **configured voice channel**, the game state is **in progress**, you're **connected with discord** and you die in TTT, the bot will mute you!
## Credits
Expand Down
14 changes: 0 additions & 14 deletions config.json.example

This file was deleted.

7 changes: 7 additions & 0 deletions discord_bot/config.json.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"discord": {
"token": "",
"guild": "",
"channel": ""
}
}
172 changes: 101 additions & 71 deletions discord_bot/index.js
Original file line number Diff line number Diff line change
@@ -1,98 +1,128 @@
const Discord = require('discord.js');
const MySQL = require('mysql');
const config = require('../config.json');
const config = require('./config.json');
const {log,error} = console;
const http = require('http');
const fs = require('fs');

const PORT = 37405; //unused port and since now the OFFICIAL ttt_discord_bot port ;)

var guild, channel;
var loggedin = false;
var lastqueryresult;

var muted = {};

var get = [];

//create discord client
const client = new Discord.Client();
client.login(config.discord.token);

client.on('ready', () => {
log('Bot is ready! :)');
log('Bot is ready to mute them all! :)');
guild = client.guilds.find('id',config.discord.guild);
channel = guild.channels.find('id',config.discord.channel);

loggedin = true; //use client.status?? TODO
update();
});
client.on('voiceStateUpdate',(oldMember,newMember) => {//player joins or leaves the ttt-channel
if (oldMember.voiceChannel != newMember.voiceChannel && (isMemberInVoiceChannel(oldMember) || isMemberInVoiceChannel(newMember))) {
updateDiscordTag(newMember);//update the discordtag to the steamid in the db
update(lastqueryresult);
client.on('voiceStateUpdate',(oldMember,newMember) => {//player leaves the ttt-channel
if (oldMember.voiceChannel != newMember.voiceChannel && isMemberInVoiceChannel(oldMember)) {
if (isMemberMutedByBot(newMember) && newMember.serverMute) newMember.setMute(false).then(()=>{
setMemberMutedByBot(newMember,false);
});
}
});
client.on('guildMemberUpdate',(oldMember,newMember) => {
if (isMemberInVoiceChannel(newMember))
updateDiscordTag(newMember);//if somebody changes his discordtag while beeing in the ttt-voice-channel
})

//create mysql pool
var pool = MySQL.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database,
multipleStatements: false
});

//create trable if not exists
mysql('create table if not exists players (steamid varchar(255),discordid varchar(255) PRIMARY KEY,discordtag varchar(255),dead bool default 0,muted bool default 0)',res => {
checkDatabase();
});
function checkDatabase() {
mysql('select discordid,dead,muted from players', res => {
if (JSON.stringify(res) != JSON.stringify(lastqueryresult)) {
lastqueryresult = res;
update(lastqueryresult);
}
setTimeout(checkDatabase, config['refresh-interval']);
});
}
isMemberInVoiceChannel = (member) => member.voiceChannelID == config.discord.channel;
isMemberMutedByBot = (member) => muted[member] == true;
setMemberMutedByBot = (member,set=true) => muted[member] = set;

function updateDiscordTag(member) {
mysql('insert into players(discordid,discordtag) values("'+member.id+'","'+member.user.tag+'") on duplicate key update discordtag="'+member.user.tag+'"');
}

function update(queryresult) {
if (!loggedin) return;
get['connect'] = (params,ret) => {
let tag = params.tag;

let found = guild.members.filterArray(val => val.user.tag.match(new RegExp('.*'+tag+'.*')));

for (i in queryresult) { //loop all players in db
let row = queryresult[i];
let member = guild.members.find('id',row.discordid);
if(member) {//if member is valid / exists
// log(member.nickname);
if (found.length > 1) {
ret({
answer: 1 //pls specify
});
}else if (found.length < 1) {
ret({
answer: 0 //no found
});
}else {
ret({
tag: found[0].user.tag,
id: found[0].id
});
}
};

if (row.dead == 1 && isMemberInVoiceChannel(member)) //if member is dead and in the voice channel
muteMember(member,true);
if (row.muted == 1 && (row.dead == 0 || !isMemberInVoiceChannel(member))) //if member is muted and (not dead or not in the voice channel)
muteMember(member,false);
get['mute'] = (params,ret) => {
let id = params.id;
let mute = params.mute

}
if (typeof id !== 'string' || typeof mute !== 'boolean') {
ret();
return;
}

}

//mysql query function
function mysql(sql,cb) {
pool.getConnection(function(err, connection) {
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) throw error;
if (cb) cb(results);
let member = guild.members.find('id', id);

if (member) {

if (isMemberInVoiceChannel(member)) {
if (!member.serverMute && mute) {
member.setMute(true,"dead players can't talk!").then(()=>{
setMemberMutedByBot(member);
ret({
success: true
});
}).catch((err)=>{
ret({
success: false,
error: err
});
});
}
if (member.serverMute && !mute) {
member.setMute(false).then(()=>{
setMemberMutedByBot(member,false);
ret({
success: true
});
}).catch((err)=>{
ret({
success: false,
error: err
});
});
}
}
else {
ret();
}

}else {
ret({
success: false,
err: 'member not found!' //TODO lua: remove from ids table + file
});
});
}
}

isMemberInVoiceChannel = (member) => member.voiceChannelID == config.discord.channel
}


function muteMember(member,mute) {
member.setMute(mute,"dead players cant talk!")
.then(() => {
mysql('update players set muted='+(mute?'1':'0')+' where discordid="'+member.id+'"');
}).catch(error);
}
http.createServer((req,res)=>{
if (typeof req.headers.params === 'string' && typeof req.headers.req === 'string' && typeof get[req.headers.req] === 'function') {
try {
let params = JSON.parse(req.headers.params);
get[req.headers.req](params,(ret)=>res.end(JSON.stringify(ret)));
}catch(e) {
res.end('no valid JSON in params');
}
}else
res.end();
}).listen({
port: PORT,
host: 'localhost'
},()=>{
log('http interface is ready :)')
});
3 changes: 1 addition & 2 deletions discord_bot/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
"description": "the discord bot part of the ttt_discord_bot",
"main": "index.js",
"dependencies": {
"discord.js": "^11.3.2",
"mysql": "^2.15.0"
"discord.js": "^11.3.2"
},
"devDependencies": {},
"scripts": {
Expand Down
7 changes: 1 addition & 6 deletions addon.json → gmod_addon/addon.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,5 @@
"title" : "TTT Discord Bot",
"type" : "ServerContent",
"tags" : [ "roleplay", "realism" ],
"ignore" :
[
".*",
"discord_bot/*",
"images/*"
]
"ignore" : []
}
Loading

0 comments on commit e094644

Please sign in to comment.