diff --git a/app.js b/app.js index a3b10b8..dc45784 100644 --- a/app.js +++ b/app.js @@ -35,8 +35,12 @@ claimbot.init(slackbot, process.env.CLAIMS_CHANNEL, process.env.RPCUSER, process var pricebot = require('./bots/pricebot'); pricebot.init(process.env.MARKET_TRADING_CHANNEL); +var modbot = require('./bots/modbot'); +modbot.init(process.env.MONGODB_URL, process.env.SLACK_TOKEN, slackbot); + slackbot.on('start', function() { slackbot.on('message', function(data) { + modbot.check(slackbot,data); if (data.type == 'team_join') { setTimeout(function() { sendWelcomeMessage(data.user.id); }, 2000); //Delay because of slow slack api updates which sometimes does not send msg. } diff --git a/bots/modbot.js b/bots/modbot.js new file mode 100644 index 0000000..204fc47 --- /dev/null +++ b/bots/modbot.js @@ -0,0 +1,76 @@ +var needle = require('needle'); +var slackbot; +var mongo; +var command = '!m'; +var apitoken; +module.exports={ + command: command, + init: init, + check: check +}; + +var globalSlackParams = { + icon_emoji: ':lbr:' +}; + +function init(mongodburl,apitoken_, slackbot) { + const MongoClient = require('mongodb').MongoClient; + MongoClient.connect(mongodburl, function (err, db) { + if (err) { + throw err; + } + mongo = db; + + }); + apitoken = apitoken_ + slackbot.getChannels() + .then( data => { + data.channels.forEach(function(ch) { + mongo.collection('m_topic').findOneAndUpdate( + { 'channel': ch.id }, + { 'channel': ch.id, 'topic': ch.topic.value }, + { 'upsert': true, 'returnOriginal': false }, + function (err, obj) { + if(err){ + console.log(err); + } + }); + }, this); + }, err => { + console.log(err); + }) + console.log('Loaded moderationbot!'); +} + + +function check(slackbot, data) { + if(data.text){ + if (data.text.trim().split(' ')[0] === command) { + //Add commands here later aswell! + } + } + if(data.topic){ // Gets called on topic change in a channel + slackbot.getUser(data.user_profile.name) + .then( usr => { + if(usr.is_admin){ + mongo.collection('m_topic').findOneAndUpdate( + { 'channel': data.channel }, + { 'channel': data.channel, 'topic': data.topic }, + { 'upsert': true, 'returnOriginal': false }, + function (err, obj) { + if(err){ + console.log(err); + } + }); + }else if(!usr.is_bot){ + mongo.collection('m_topic').findOne({'channel': data.channel}, function(err, document) { + slackbot.postMessage(data.user,`Hey <@${data.user_profile.name}>, you are not allowed to change the topic in <#${data.channel}>!`, globalSlackParams); + needle.get(`https://slack.com/api/channels.setTopic?token=${apitoken}&channel=${data.channel}&topic=${document.topic}`); + }); + } + }, err => { + console.log(err); + }) + } +} +