<commit_before>const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = ">"

const JOSH = "292971521159200768";
const WILLY = "259209114268336129";
client.on("debug", console.log);
client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', msg => {
  let channel = msg.channel;

  if (msg.content === prefix + 'Sinbadx')
    channel.send('The one, the only!');

  else if (msg.content === prefix + 'Xena')
    channel.send('Do not touch my master!');

  else if (msg.content === prefix + 'Pixel')
    channel.send('Pixelate that. - Pixel, 2k17');

  else if (msg.content === prefix + 'ArX')
    channel.send('Feel the power of the almighty ban hammer!');

  else if (msg.content === prefix + 'hi')
    msg.channel.send('Hoi!');

  else if (msg.content === prefix + 'Dreams')
    msg.channel.send('Dreams will come true, just wait and see.');

  else if(msg.content.startsWith(prefix + 's')){
    if(msg.author.id == JOSH || msg.author.id == WILLY){
      channel.send(msg.content.split(' ').slice(1).join(' '));
      msg.delete();
    }
  }

  else if (msg.content === prefix + 'XenaCorrupt')
    channel.send('You may fall from the sky, you may fall from a tree. But the best way to fall, is in love with me. <3');
});

client.login(process.env.TOKEN);
<commit_msg>Umi command.<commit_after>const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = ">"

const JOSH = "292971521159200768";
const WILLY = "259209114268336129";
client.on("debug", console.log);
client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', msg => {
  let channel = msg.channel;

  if (msg.content === prefix + 'Sinbadx')
    channel.send('The one, the only!');

  else if (msg.content === prefix + 'Xena')
    channel.send('Do not touch my master!');

  else if (msg.content === prefix + 'Pixel')
    channel.send('Pixelate that. - Pixel, 2k17');

  else if (msg.content === prefix + 'ArX')
    channel.send('Feel the power of the almighty ban hammer!');

  else if (msg.content === prefix + 'hi')
    msg.channel.send('Hoi!');

  else if (msg.content === prefix + 'Dreams')
    msg.channel.send('Dreams will come true, just wait and see.');

  else if (msg.content === prefix + 'Umi')
    msg.channel.send('Credits go to my teacher, Umi.');

  else if(msg.content.startsWith(prefix + 's')){
    if(msg.author.id == JOSH || msg.author.id == WILLY){
      channel.send(msg.content.split(' ').slice(1).join(' '));
      msg.delete();
    }
  }

  else if (msg.content === prefix + 'XenaCorrupt')
    channel.send('You may fall from the sky, you may fall from a tree. But the best way to fall, is in love with me. <3');
});

client.login(process.env.TOKEN);
<|endoftext|>


<commit_before>var Discord = require('discord.io');
var winston = require('winston');

var main = require('./index.js');
var config = main.config;
var keys = main.keys;

/**** Bot Initialization ****/
var bot = new Discord.Client({
    autorun: false,
    token: keys.discord,
});

winston.info('Connecting...');
bot.connect();
module.exports = bot;

bot.active = () => {
    return bot.connected && bot.presenceStatus == "online";
};

// Make a temporary channel name with the flag additions
bot.createTemporaryChannelName = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return config.entries[guild_id].tempChannelNameFlag + name;
    }
    else {
        return name + config.entries[guild_id].tempChannelNameFlag;
    }
}
// Remove the temporary flag addition from a name to get just the rest
bot.scrubTemporaryFlag = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.substring(config.entries[guild_id].tempChannelNameFlag.length + 1);
    }
    else {
        return name.substring(0, name.length - config.entries[guild_id].tempChannelNameFlag.length);
    }
}

// Check if name is a temporary channel
bot.isChannelTemporary = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.startsWith(config.entries[guild_id].tempChannelNameFlag);
    }
    else {
        return name.endsWith(config.entries[guild_id].tempChannelNameFlag);
    }
}

bot.createTemporaryChannel = (name, guildID, callback) => {
    bot.createChannel({
        serverID: guildID,
        name: bot.createTemporaryChannelName(name, guildID),
        type: 'voice',
    }, (err,res) => {
        if (err) {
            if (err.statusCode == undefined || err.statusCode != 403) { // Don't have permission
                winston.error('Error creating temporary channel:', err);
            }

            if(callback)callback(err);

        }
        else {
            // Set permissions
            var perm = config.entries[guildID].tempChannelPermissions;
            if (perm && perm.user && perm.role) {
                var count = Object.keys(perm.user).length + Object.keys(perm.role).length;
                var complete = (error) => {
                    count --;
                    if (count == 0 || error) {
                        if(callback) callback(error);
                    }
                }

                Object.keys(perm.user).forEach(uid => {
                    bot._req('post', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + uid, {
                        type: 'member',
                        id: uid,
                        allow: perm.user[uid].allow,
                        deny: perm.user[uid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
                Object.keys(perm.role).forEach(rid => {
                    bot._req('put', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + rid, {
                        type: 'role',
                        id: rid,
                        allow: perm.role[rid].allow,
                        deny: perm.role[rid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
            }

            else if (callback) callback();
        }
    });

    // TODO info and permissions
};

bot.listOfUsersByGames = {}; // { serverID: { gameName: [userID, userID] } }
bot.listOfTempChannels = {}; // channelID: age
bot.everyoneRoles = {}; // serverID: role_ID of @everyone

bot.on('ready', (evt) => {
    winston.info('Logged in as %s - %s', bot.username, bot.id);
    winston.info("Go to https://discordapp.com/api/oauth2/authorize?client_id=" + bot.id + "&scope=bot&permissions=0 to add bot to a server");
    checkTemporaryChannels();
    bot.tempCheckInterval = setInterval(checkTemporaryChannels, config.global.tempChannelCheckInterval);

    // Check users in game to add to list
    Object.keys(bot.servers).forEach(gid => {
        if (!config.entries[gid].autoCreateByGame) return;
        bot.listOfUsersByGames[gid] = {};
        var server = bot.servers[gid];
        Object.keys(server.members).forEach(uid => {
            var user = server.members[uid];
            if (user.game && user.status == 'online') {
                if (bot.inRoles(server, user.roles, config.entries[gid].autoCreateByGameRoles)) {
                    if (bot.listOfUsersByGames[gid][user.game.name] == undefined)
                        bot.listOfUsersByGames[gid][user.game.name] = [];

                    bot.listOfUsersByGames[gid][user.game.name].push(uid);
                }
            }
        });

        checkCommonGames(gid);
    });

});

bot.on('disconnect', () => {
    winston.info('Disconnected');

    if (config.global.autoReconnect) {
        winston.info('Reconnecting in', config.global.autoReconnectInterval/1000, 'seconds');
        setTimeout(()=>bot.connect(), config.global.autoReconnectInterval)
    }
});

bot.on('any', (evt) => {
    // We are joining a server
    // Also fires on already-joined servers when starting up
    if (evt.t == 'GUILD_CREATE') {
        // Check if config entry exists for this server
        // If it doesn't, create one based off default

        if (!config.entries[evt.d.id]){
            config.createNew(evt.d.id, evt.d.name);
        }

        winston.info("Added to server", evt.d.name);
    }

    // We are leaving a server
    else if(evt.t == 'GUILD_DELETE') {
        // Maybe delete config, probably not
        winston.info("Removed from server", evt.d.name);
    }
});

/**** Command Initialization ****/
var normalizedPath = require("path").join(__dirname, "cmds");
var cmds = [];
require("fs").readdirSync(normalizedPath).forEach(function(file) {
    if (file.endsWith('.js')){
        var Clazz = require('./cmds/' + file);
        cmds.push( new Clazz(bot, config) );
    }
});

/**** Command handling ****/
bot.on('message', (user, userID, channelID, msg, evt) => {

    var channel = bot.channels[evt.d.channel_id]
    if (channel == undefined) return; // Is a direct message, don't do anything

    var lower = msg.toLowerCase();
    var server = bot.servers[channel.guild_id];
    cmds.some(cmd => {
        if (lower.startsWith(config.entries[channel.guild_id].commandPrefix + cmd.command)) {
            if (cmd.checkUserPermissions(userID, server)){
                cmd.onCommandEntered(msg, user, userID, channel.guild_id, evt.d.channel_id); // @TODO rewrite cmds to take objects sensibly?
            }
            else {
                bot.sendMessage({
                    to: channelID,
                    message: user + ": You do not have permission to execute that command",
                });
            }

            return true;
        }
        return false;
    });
});

/**** Auto-channel creation ****/
bot.on('presence', (user, uid, status, game, evt) => {
    Object.keys(bot.servers).forEach(guild_id => {
      var server = bot.servers[guild_id];
      if(!config.entries[guild_id].autoCreateByGame) return;

      if (bot.listOfUsersByGames[guild_id] == undefined)
          bot.listOfUsersByGames[guild_id] = {};
      var serverListOfUsersByGames = bot.listOfUsersByGames[guild_id];

      if (server.members[uid]) {

          // First check if user is allowed to cause temp game channels
          if (bot.inRoles(server, evt.d.roles, config.entries[guild_id].autoCreateByGameRoles)) {
              var game = evt.d.game;
              // Add user to game list if playing game
              if (game != null) {

                  // Check if game is exempt
                  if (config.entries[guild_id].exemptAutoCreateGames.indexOf(game.name) !== -1) return;

                  if(!serverListOfUsersByGames[game.name]) serverListOfUsersByGames[game.name] = [];
                  serverListOfUsersByGames[game.name].push(uid);
                  checkCommonGames(guild_id);
              }

              // User not playing game, remove
              else if (game == null || status != 'online') {
                  Object.keys(serverListOfUsersByGames).forEach(gameName => {
                      var userList = serverListOfUsersByGames[gameName];
                      if (userList.indexOf(uid) >= 0) {
                          userList.splice(userList.indexOf(uid), 1);
                      }
                  });
              }

          }

      }
    });
});

function getNumberOfUsersPlayingGame(gameName, guildID){
    if (!bot.listOfUsersByGames[guildID]) return 0;
    if (!bot.listOfUsersByGames[guildID][gameName]) return 0;
    // Update list to only include online members
    var arr = bot.listOfUsersByGames[guildID][gameName];
    arr = bot.listOfUsersByGames[guildID][gameName] = arr.filter(uid => {
      var member = bot.servers[guildID].members[uid];
      return member.status == 'online';
    });

    return bot.listOfUsersByGames[guildID][gameName].length;
}

function checkCommonGames(serverID) {
    if (!config.entries[serverID].autoCreateByGame) return;

    Object.keys(bot.listOfUsersByGames[serverID]).forEach(gameName => {
        // There is at least autoCreateByGameCommon people playing this game
        if (getNumberOfUsersPlayingGame(gameName, serverID) >= config.entries[serverID].autoCreateByGameCommon) {

            // Check if there is already a channel
            var filter = Object.keys(bot.servers[serverID].channels).filter(cid => {
                var channel = bot.channels[cid];
                return channel.name.indexOf(gameName) !== -1;
            });
            if (filter.length == 0)  {
                bot.createTemporaryChannel(' ' + gameName, serverID);
            }
        }
    });
}

/**** Temporary-channel destruction ****/

function checkTemporaryChannels() {
    if (bot && bot.active()) {

        Object.keys(bot.channels).map(chanID => {
            var channel = bot.channels[chanID];
            var guild_id = channel.guild_id;

            // Check if is temp channel
            if (channel.type == 'voice' && bot.isChannelTemporary(channel.name, guild_id)) {
                // Add to age
                if (bot.listOfTempChannels[chanID] != undefined) {
                    // check number of users
                    if (Object.keys(channel.members).length == 0) {

                        // Check to see if game was created for common-games
                        if (config.entries[guild_id].autoCreateByGame) {
                            var gameName = bot.scrubTemporaryFlag(channel.name, guild_id);
                            if (getNumberOfUsersPlayingGame(gameName, guild_id) >= config.entries[guild_id].autoCreateByGameCommon) {
                                bot.listOfTempChannels[chanID] = 0;
                                return;
                            }
                        }

                        bot.listOfTempChannels[chanID] += config.global.tempChannelCheckInterval;
                        if (bot.listOfTempChannels[chanID] >= config.entries[guild_id].tempChannelTimeout) {
                            bot.deleteChannel(chanID, (err, res) => {
                                if (err && (!err.statusCode || err.statusCode != 403))
                                    winston.error('Error deleting temporary channel:', err);
                            });
                            delete bot.listOfTempChannels[chanID];
                        }
                    }
                    else {
                        bot.listOfTempChannels[chanID] = 0;
                    }
                }
                else
                    bot.listOfTempChannels[chanID] = 0;
            }
        });
    }
};

// Checks if any of the roles in roleIDs is in the list of roles
// Second param is comma-delimted string
bot.inRoles = function(server, roleIDs, roles) {
    for(var i = 0; i < roleIDs.length; i++ ){
        var roleID = roleIDs[i];
        var filter = roles.filter(r => roleID == r);
        if (filter.length > 0) return true;
    }
    return false;
};

function hasPermission(bit, perm) {
    return ((perm >> bit) & 1) == 1;
}

bot.isAdministrator = function(guild_id, user_id) {
    var server = bot.servers[guild_id];
    var member = server.members[user_id];
    if (member) {
        for (var i in Object.keys(member.roles)) {
            var role = server.roles[member.roles[i]];
            if ( hasPermission(Discord.Permissions.GENERAL_ADMINISTRATOR, role._permissions) )
                return true;
        }
    }

    return false;
};

<commit_msg>Add ability to @mention bot for commands<commit_after>var Discord = require('discord.io');
var winston = require('winston');

var main = require('./index.js');
var config = main.config;
var keys = main.keys;

/**** Bot Initialization ****/
var bot = new Discord.Client({
    autorun: false,
    token: keys.discord,
});

winston.info('Connecting...');
bot.connect();
module.exports = bot;

bot.active = () => {
    return bot.connected && bot.presenceStatus == "online";
};

// Make a temporary channel name with the flag additions
bot.createTemporaryChannelName = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return config.entries[guild_id].tempChannelNameFlag + name;
    }
    else {
        return name + config.entries[guild_id].tempChannelNameFlag;
    }
}
// Remove the temporary flag addition from a name to get just the rest
bot.scrubTemporaryFlag = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.substring(config.entries[guild_id].tempChannelNameFlag.length + 1);
    }
    else {
        return name.substring(0, name.length - config.entries[guild_id].tempChannelNameFlag.length);
    }
}

// Check if name is a temporary channel
bot.isChannelTemporary = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.startsWith(config.entries[guild_id].tempChannelNameFlag);
    }
    else {
        return name.endsWith(config.entries[guild_id].tempChannelNameFlag);
    }
}

bot.createTemporaryChannel = (name, guildID, callback) => {
    bot.createChannel({
        serverID: guildID,
        name: bot.createTemporaryChannelName(name, guildID),
        type: 'voice',
    }, (err,res) => {
        if (err) {
            if (err.statusCode == undefined || err.statusCode != 403) { // Don't have permission
                winston.error('Error creating temporary channel:', err);
            }

            if(callback)callback(err);

        }
        else {
            // Set permissions
            var perm = config.entries[guildID].tempChannelPermissions;
            if (perm && perm.user && perm.role) {
                var count = Object.keys(perm.user).length + Object.keys(perm.role).length;
                var complete = (error) => {
                    count --;
                    if (count == 0 || error) {
                        if(callback) callback(error);
                    }
                }

                Object.keys(perm.user).forEach(uid => {
                    bot._req('post', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + uid, {
                        type: 'member',
                        id: uid,
                        allow: perm.user[uid].allow,
                        deny: perm.user[uid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
                Object.keys(perm.role).forEach(rid => {
                    bot._req('put', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + rid, {
                        type: 'role',
                        id: rid,
                        allow: perm.role[rid].allow,
                        deny: perm.role[rid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
            }

            else if (callback) callback();
        }
    });

    // TODO info and permissions
};

bot.listOfUsersByGames = {}; // { serverID: { gameName: [userID, userID] } }
bot.listOfTempChannels = {}; // channelID: age
bot.everyoneRoles = {}; // serverID: role_ID of @everyone

bot.on('ready', (evt) => {
    winston.info('Logged in as %s - %s', bot.username, bot.id);
    winston.info("Go to https://discordapp.com/api/oauth2/authorize?client_id=" + bot.id + "&scope=bot&permissions=0 to add bot to a server");
    checkTemporaryChannels();
    bot.tempCheckInterval = setInterval(checkTemporaryChannels, config.global.tempChannelCheckInterval);

    // Check users in game to add to list
    Object.keys(bot.servers).forEach(gid => {
        if (!config.entries[gid].autoCreateByGame) return;
        bot.listOfUsersByGames[gid] = {};
        var server = bot.servers[gid];
        Object.keys(server.members).forEach(uid => {
            var user = server.members[uid];
            if (user.game && user.status == 'online') {
                if (bot.inRoles(server, user.roles, config.entries[gid].autoCreateByGameRoles)) {
                    if (bot.listOfUsersByGames[gid][user.game.name] == undefined)
                        bot.listOfUsersByGames[gid][user.game.name] = [];

                    bot.listOfUsersByGames[gid][user.game.name].push(uid);
                }
            }
        });

        checkCommonGames(gid);
    });

});

bot.on('disconnect', () => {
    winston.info('Disconnected');

    if (config.global.autoReconnect) {
        winston.info('Reconnecting in', config.global.autoReconnectInterval/1000, 'seconds');
        setTimeout(()=>bot.connect(), config.global.autoReconnectInterval)
    }
});

bot.on('any', (evt) => {
    // We are joining a server
    // Also fires on already-joined servers when starting up
    if (evt.t == 'GUILD_CREATE') {
        // Check if config entry exists for this server
        // If it doesn't, create one based off default

        if (!config.entries[evt.d.id]){
            config.createNew(evt.d.id, evt.d.name);
        }

        winston.info("Added to server", evt.d.name);
    }

    // We are leaving a server
    else if(evt.t == 'GUILD_DELETE') {
        // Maybe delete config, probably not
        winston.info("Removed from server", evt.d.name);
    }
});

/**** Command Initialization ****/
var normalizedPath = require("path").join(__dirname, "cmds");
var cmds = [];
require("fs").readdirSync(normalizedPath).forEach(function(file) {
    if (file.endsWith('.js')){
        var Clazz = require('./cmds/' + file);
        cmds.push( new Clazz(bot, config) );
    }
});

/**** Command handling ****/
bot.on('message', (user, userID, channelID, msg, evt) => {

    // Check if metioning us
    var mentioned = evt.d.mentions.some(m => m.id == bot.id );
    // Remove the mention for ease parsing command
    if (mentioned && msg.startsWith('<@!' + bot.id + '>')) {
        msg = msg.substring( ('<@!' + bot.id + '>').length + 1 );
    }

    var channel = bot.channels[evt.d.channel_id]
    if (channel == undefined) return; // Is a direct message, don't do anything

    var lower = msg.toLowerCase();
    var server = bot.servers[channel.guild_id];
    cmds.some(cmd => {
        if (lower.startsWith(config.entries[channel.guild_id].commandPrefix + cmd.command)) {
            if (cmd.checkUserPermissions(userID, server)){
                cmd.onCommandEntered(msg, user, userID, channel.guild_id, evt.d.channel_id); // @TODO rewrite cmds to take objects sensibly?
            }
            else {
                bot.sendMessage({
                    to: channelID,
                    message: user + ": You do not have permission to execute that command",
                });
            }

            return true;
        }
        return false;
    });
});

/**** Auto-channel creation ****/
bot.on('presence', (user, uid, status, game, evt) => {
    Object.keys(bot.servers).forEach(guild_id => {
      var server = bot.servers[guild_id];
      if(!config.entries[guild_id].autoCreateByGame) return;

      if (bot.listOfUsersByGames[guild_id] == undefined)
          bot.listOfUsersByGames[guild_id] = {};
      var serverListOfUsersByGames = bot.listOfUsersByGames[guild_id];

      if (server.members[uid]) {

          // First check if user is allowed to cause temp game channels
          if (bot.inRoles(server, evt.d.roles, config.entries[guild_id].autoCreateByGameRoles)) {
              var game = evt.d.game;
              // Add user to game list if playing game
              if (game != null) {

                  // Check if game is exempt
                  if (config.entries[guild_id].exemptAutoCreateGames.indexOf(game.name) !== -1) return;

                  if(!serverListOfUsersByGames[game.name]) serverListOfUsersByGames[game.name] = [];
                  serverListOfUsersByGames[game.name].push(uid);
                  checkCommonGames(guild_id);
              }

              // User not playing game, remove
              else if (game == null || status != 'online') {
                  Object.keys(serverListOfUsersByGames).forEach(gameName => {
                      var userList = serverListOfUsersByGames[gameName];
                      if (userList.indexOf(uid) >= 0) {
                          userList.splice(userList.indexOf(uid), 1);
                      }
                  });
              }

          }

      }
    });
});

function getNumberOfUsersPlayingGame(gameName, guildID){
    if (!bot.listOfUsersByGames[guildID]) return 0;
    if (!bot.listOfUsersByGames[guildID][gameName]) return 0;
    // Update list to only include online members
    var arr = bot.listOfUsersByGames[guildID][gameName];
    arr = bot.listOfUsersByGames[guildID][gameName] = arr.filter(uid => {
      var member = bot.servers[guildID].members[uid];
      return member.status == 'online';
    });

    return bot.listOfUsersByGames[guildID][gameName].length;
}

function checkCommonGames(serverID) {
    if (!config.entries[serverID].autoCreateByGame) return;

    Object.keys(bot.listOfUsersByGames[serverID]).forEach(gameName => {
        // There is at least autoCreateByGameCommon people playing this game
        if (getNumberOfUsersPlayingGame(gameName, serverID) >= config.entries[serverID].autoCreateByGameCommon) {

            // Check if there is already a channel
            var filter = Object.keys(bot.servers[serverID].channels).filter(cid => {
                var channel = bot.channels[cid];
                return channel.name.indexOf(gameName) !== -1;
            });
            if (filter.length == 0)  {
                bot.createTemporaryChannel(' ' + gameName, serverID);
            }
        }
    });
}

/**** Temporary-channel destruction ****/

function checkTemporaryChannels() {
    if (bot && bot.active()) {

        Object.keys(bot.channels).map(chanID => {
            var channel = bot.channels[chanID];
            var guild_id = channel.guild_id;

            // Check if is temp channel
            if (channel.type == 'voice' && bot.isChannelTemporary(channel.name, guild_id)) {
                // Add to age
                if (bot.listOfTempChannels[chanID] != undefined) {
                    // check number of users
                    if (Object.keys(channel.members).length == 0) {

                        // Check to see if game was created for common-games
                        if (config.entries[guild_id].autoCreateByGame) {
                            var gameName = bot.scrubTemporaryFlag(channel.name, guild_id);
                            if (getNumberOfUsersPlayingGame(gameName, guild_id) >= config.entries[guild_id].autoCreateByGameCommon) {
                                bot.listOfTempChannels[chanID] = 0;
                                return;
                            }
                        }

                        bot.listOfTempChannels[chanID] += config.global.tempChannelCheckInterval;
                        if (bot.listOfTempChannels[chanID] >= config.entries[guild_id].tempChannelTimeout) {
                            bot.deleteChannel(chanID, (err, res) => {
                                if (err && (!err.statusCode || err.statusCode != 403))
                                    winston.error('Error deleting temporary channel:', err);
                            });
                            delete bot.listOfTempChannels[chanID];
                        }
                    }
                    else {
                        bot.listOfTempChannels[chanID] = 0;
                    }
                }
                else
                    bot.listOfTempChannels[chanID] = 0;
            }
        });
    }
};

// Checks if any of the roles in roleIDs is in the list of roles
// Second param is comma-delimted string
bot.inRoles = function(server, roleIDs, roles) {
    for(var i = 0; i < roleIDs.length; i++ ){
        var roleID = roleIDs[i];
        var filter = roles.filter(r => roleID == r);
        if (filter.length > 0) return true;
    }
    return false;
};

function hasPermission(bit, perm) {
    return ((perm >> bit) & 1) == 1;
}

bot.isAdministrator = function(guild_id, user_id) {
    var server = bot.servers[guild_id];
    var member = server.members[user_id];
    if (member) {
        for (var i in Object.keys(member.roles)) {
            var role = server.roles[member.roles[i]];
            if ( hasPermission(Discord.Permissions.GENERAL_ADMINISTRATOR, role._permissions) )
                return true;
        }
    }

    return false;
};

<|endoftext|>


<commit_before>var Botkit = require('botkit');
var mongoStorage = require('botkit-storage-mongo')({
    mongoUri: process.env.MONGODB_URI || 'localhost'
});
const DROPOUTS_TITLE = 'Dropped out';
const SIGNED_UP_TITLE = 'Signed up';

function randomChoice(myArray) {
    return myArray[Math.floor(Math.random() * myArray.length)];
}

function makeMessage(signedUp, dropouts) {
    var msg = {
        "text": "Sign up open for football fives next Monday night! 7pm, £3 at Peffermill as usual.",
        "attachments": [
            {
                "text": "Are you in?",
                "color": "#3AA3E3",
                "callback_id": "initial",
                "attachment_type": "default",
                "fields": [
                ],
                "actions": [
                    {
                        "name": "imIn",
                        "text": ":soccer: I'm in",
                        "style": "default",
                        "type": "button",
                        "value": true,
                    },
                    {
                        "name": "notIn",
                        "text": "I'm not in",
                        "style": "danger",
                        "type": "button",
                        "value": true,
                    },
                    {
                        "name": "addFriend",
                        "text": "Add a friend",
                        "style": "default",
                        "type": "button",
                        "value": true,
                    },
                    {
                        "name": "removeFriend",
                        "text": "Remove a friend",
                        "style": "danger",
                        "type": "button",
                        "value": true,
                    }
                ]
            }
        ]
    };
    if (dropouts.length > 0) {
        msg.attachments[0].fields.push({
            "title": DROPOUTS_TITLE,
            "value": dropouts.map(function (user) {
                return '<@' + user + '>';
            }).join(),
        });
    }
    if (signedUp.length > 0) {
        msg.attachments[0].fields.push({
            "title": SIGNED_UP_TITLE,
            "value": signedUp.map(function (user) {
                return '<@' + user + '>';
            }).join(),
        });
    }
    if (signedUp.length == 10) {
        msg.attachments[0].actions.push({
            "name": "close",
            "text": "Close",
            "style": "primary",
            "type": "button",
            "value": true,
        });
    }
    return msg;
}

function makeFinalMessage(signedUp, dropouts) {
    return {
        "text": "Sign up for football fives closed! :tada:",
        "attachments": [
            {
                "color": "good",
                "callback_id": "final",
                "attachment_type": "default",
                "fields": [
                    {
                        "title": SIGNED_UP_TITLE,
                        "value": signedUp.map(function (user) {
                            return '<@' + user + '>';
                        }).join(),
                    },
                    {
                        "title": "Who's paying?",
                        "value": "<@" + randomChoice(signedUp) + ">",
                    },
                    {
                        "title": "Location",
                        "value": "Peffermill",
                        "short": true
                    },
                    {
                        "title": "Time",
                        "value": "7pm",
                        "short": true
                    }
                ]
            }
        ]
    };
}

function removeUser(userList, user) {
    var idx = userList.indexOf(user);
    if (idx > -1) {
        userList.splice(idx, 1);
    }
    return userList;
}

function addUser(userList, user) {
    var idx = userList.indexOf(user);
    if (idx == -1) {
        userList.push(user);
    }
    return userList;
}

function getUsersByTitle(message, title) {
    var attachments = message.original_message.attachments;
    for (i = 0; i < attachments.length ; i++) {
        var attachment = attachments[i];
        if (!attachment.fields) {
            continue;
        }
        var field = attachment.fields.find(function (f) {
            return f.title == title;
        });
        if (!field) {
            continue;
        }
        return field.value.split(',').map(function (u) {
            return u.substring(2, u.length - 1);
        });
    }
    return [];
}

function getDropouts(message) {
    return getUsersByTitle(message, DROPOUTS_TITLE);
}

function getSignedUp(message) {
    return getUsersByTitle(message, SIGNED_UP_TITLE);
}

function run() {
    var controller = Botkit.slackbot({
        debug: false,
        storage: mongoStorage
    }).configureSlackApp({
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
        scopes: ['commands', 'chat:write:bot'],
    });

    controller.setupWebserver(process.env.PORT, function(err, webserver) {
        controller.createWebhookEndpoints(webserver);
        controller.createOauthEndpoints(webserver, function(err, req, res) {
            if (err) {
                res.status(500).send('ERROR: ' + err);
            } else {
                res.send('Success!');
            }
        });
    });

    controller.on('interactive_message_callback', function(bot, message) {
        if (message.callback_id !== 'initial' && message.callback_id !== 'final') {
            return;
        }

        var action = message.actions[0].name;
        var username = message.user;

        var signedUp = getSignedUp(message);
        var dropouts = getDropouts(message);

        if (action == 'notIn') {
            removeUser(signedUp, username);
            addUser(dropouts, username);
            bot.replyInteractive(message, makeMessage(signedUp, dropouts));
        } else if (action == 'imIn') {
            removeUser(dropouts, username);
            addUser(signedUp, username);
            bot.replyInteractive(message, makeMessage(signedUp, dropouts));
        } else if (action == 'addFriend') {
            addUser(signedUp, username + ' (Friend)');
        } else if (action == 'removeFriend') {
            removeUser(signedUp, username + ' (Friend)');
        } else if (action == 'close') {
            bot.replyInteractive(message, makeFinalMessage(signedUp, dropouts));
        }
    });

    controller.on('slash_command', function(bot, message) {
        if (message.command !== '/jose') {
            return;
        }
        bot.replyPublic(message, makeMessage([], []));
    });

}

if (require.main === module) {
    run();
}

exports.addUser = addUser;
exports.removeUser = removeUser;
exports.getUsersByTitle = getUsersByTitle;
<commit_msg>Fix adding friends<commit_after>var Botkit = require('botkit');
var mongoStorage = require('botkit-storage-mongo')({
    mongoUri: process.env.MONGODB_URI || 'localhost'
});
const DROPOUTS_TITLE = 'Dropped out';
const SIGNED_UP_TITLE = 'Signed up';

function randomChoice(myArray) {
    while (True) {
        var choice = myArray[Math.floor(Math.random() * myArray.length)];
        if (!choice.endsWith('friend')) {
            return choice
        }
    }
}

function makeMessage(signedUp, dropouts) {
    var msg = {
        "text": "Sign up open for football fives next Monday night! 7pm, £3 at Peffermill as usual.",
        "attachments": [
            {
                "text": "Are you in?",
                "color": "#3AA3E3",
                "callback_id": "initial",
                "attachment_type": "default",
                "fields": [
                ],
                "actions": [
                    {
                        "name": "imIn",
                        "text": ":soccer: I'm in",
                        "style": "default",
                        "type": "button",
                        "value": true,
                    },
                    {
                        "name": "notIn",
                        "text": "I'm not in",
                        "style": "danger",
                        "type": "button",
                        "value": true,
                    },
                    {
                        "name": "addFriend",
                        "text": "Add a friend",
                        "style": "default",
                        "type": "button",
                        "value": true,
                    },
                    {
                        "name": "removeFriend",
                        "text": "Remove a friend",
                        "style": "default",
                        "type": "button",
                        "value": true,
                    }
                ]
            }
        ]
    };
    if (dropouts.length > 0) {
        msg.attachments[0].fields.push({
            "title": DROPOUTS_TITLE,
            "value": dropouts.map(function (user) {
                if (user.endsWith('-friend')) {
                    return '<@' + user.split('-friend')[0] + '> (Friend)';
                }
                return '<@' + user + '>';
            }).join(),
        });
    }
    if (signedUp.length > 0) {
        msg.attachments[0].fields.push({
            "title": SIGNED_UP_TITLE,
            "value": signedUp.map(function (user) {
                if (user.endsWith('-friend')) {
                    return '<@' + user.split('-friend')[0] + '> (Friend)';
                }
                return '<@' + user + '>';
            }).join(),
        });
    }
    if (signedUp.length == 10) {
        msg.attachments[0].actions.push({
            "name": "close",
            "text": "Close",
            "style": "primary",
            "type": "button",
            "value": true,
        });
    }
    return msg;
}

function makeFinalMessage(signedUp, dropouts) {
    return {
        "text": "Sign up for football fives closed! :tada:",
        "attachments": [
            {
                "color": "good",
                "callback_id": "final",
                "attachment_type": "default",
                "fields": [
                    {
                        "title": SIGNED_UP_TITLE,
                        "value": signedUp.map(function (user) {
                            if (user.endsWith('-friend')) {
                                return '<@' + user.split('-friend')[0] + '> (Friend)';
                            }
                            return '<@' + user + '>';
                        }).join(),
                    },
                    {
                        "title": "Who's paying?",
                        "value": "<@" + randomChoice(signedUp) + ">",
                    },
                    {
                        "title": "Location",
                        "value": "Peffermill",
                        "short": true
                    },
                    {
                        "title": "Time",
                        "value": "7pm",
                        "short": true
                    }
                ]
            }
        ]
    };
}

function removeUser(userList, user) {
    var idx = userList.indexOf(user);
    if (idx > -1) {
        userList.splice(idx, 1);
    }
    return userList;
}

function addUser(userList, user) {
    var idx = userList.indexOf(user);
    if (idx == -1) {
        userList.push(user);
    }
    return userList;
}

function getUsersByTitle(message, title) {
    var attachments = message.original_message.attachments;
    for (i = 0; i < attachments.length ; i++) {
        var attachment = attachments[i];
        if (!attachment.fields) {
            continue;
        }
        var field = attachment.fields.find(function (f) {
            return f.title == title;
        });
        if (!field) {
            continue;
        }
        return field.value.split(',').map(function (u) {
            return u.substring(2, u.length - 1);
        });
    }
    return [];
}

function getDropouts(message) {
    return getUsersByTitle(message, DROPOUTS_TITLE);
}

function getSignedUp(message) {
    return getUsersByTitle(message, SIGNED_UP_TITLE);
}

function run() {
    var controller = Botkit.slackbot({
        debug: false,
        storage: mongoStorage
    }).configureSlackApp({
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
        scopes: ['commands', 'chat:write:bot'],
    });

    controller.setupWebserver(process.env.PORT, function(err, webserver) {
        controller.createWebhookEndpoints(webserver);
        controller.createOauthEndpoints(webserver, function(err, req, res) {
            if (err) {
                res.status(500).send('ERROR: ' + err);
            } else {
                res.send('Success!');
            }
        });
    });

    controller.on('interactive_message_callback', function(bot, message) {
        if (message.callback_id !== 'initial' && message.callback_id !== 'final') {
            return;
        }

        var action = message.actions[0].name;
        var username = message.user;

        var signedUp = getSignedUp(message);
        var dropouts = getDropouts(message);

        if (action == 'notIn') {
            removeUser(signedUp, username);
            addUser(dropouts, username);
            bot.replyInteractive(message, makeMessage(signedUp, dropouts));
        } else if (action == 'imIn') {
            removeUser(dropouts, username);
            addUser(signedUp, username);
            bot.replyInteractive(message, makeMessage(signedUp, dropouts));
        } else if (action == 'addFriend') {
            addUser(signedUp, username + '-friend');
        } else if (action == 'removeFriend') {
            removeUser(signedUp, username + '-Friend');
        } else if (action == 'close') {
            bot.replyInteractive(message, makeFinalMessage(signedUp, dropouts));
        }
    });

    controller.on('slash_command', function(bot, message) {
        if (message.command !== '/jose') {
            return;
        }
        bot.replyPublic(message, makeMessage([], []));
    });

}

if (require.main === module) {
    run();
}

exports.addUser = addUser;
exports.removeUser = removeUser;
exports.getUsersByTitle = getUsersByTitle;
<|endoftext|>


<commit_before>var config = require('./config.js');
var monkey_island = require('./monkey_island.js');

var TelegramBot = require('node-telegram-bot-api');

var bot = new TelegramBot(config.token, {polling: true});

/**
 * Returns an insult
 * @param {object} message - The message to reply to
 * @param {object} user - The user to insult
 * @returns {string} The insult
 */
function getInsult(message, user) {
  var u = user.first_name;
  var insults = [
    'You fight like a dairy farmer.',
    'You fight like a cow.',
    'So you want to be a pirate, eh? You look more like a flooring inspector.',
    u + '? That’s the most ridiculous name I’ve ever heard!',
    'You’ve got to help me! I’m a victim of society!',
    'Let’s face it, ' + u + '. You are an evil, foul-smelling, vile, codependent villain and that’s just not what I’m looking for in a romantic relationship right now.',
    'I-- --am your brother!',
    u + ', stop babbling.',
    'You’re about as fearsome as a doorstop.',
    'Oh, so your parents were expecting a girl.',
    'Arrgh! Math be hard, let’s go shoppin’!',
    'Life is like pillaging a trading vessel bound, ' + u + '... Ya never know what you’re gonna get.',
    'Ahh, the middle finger, the most communicative of fingers.',
    'Well… you fight like a cow!',
    'Iron Maiden?! Excellent! ... I have no idea why I just said that.',
    'So you’re going to die... again... wonderful!',
    'Sitting in a dark room with a lava lamp and thinking you’re in heaven?',
    'No no, I’m not questioning your professionalism, it’s just that I don’ even the meaning -',
    'Is it over? ...Hello? ...Did I win?'
  ];
  return insults[Math.floor(Math.random() * insults.length)];
}

/**
 * Writes an insult to the chat
 * @param {object} message - The message to reply to
 * @param {object=} user - The user to insult
 */
function writeInsult(message, user) {
  user = user || message.from;
  bot.sendMessage(message.chat.id, getInsult(message, user), {'reply_to_message_id': message.message_id});
}

bot.onText(/@CoredumpFlameBot/, function(message, match) {
  writeInsult(message);
});

bot.on('message', function(message) {
  if (message.new_chat_participant) {
    writeInsult(message, message.new_chat_participant);
  }

  // search for monkey island matches
  if (message.text) {
    var monkey_island_match = monkey_island.search(message.text);
    if (monkey_island_match) {
      bot.sendMessage(message.chat.id, monkey_island_match, {'reply_to_message_id': message.message_id});
      return;
    }
  }

  if (Math.random() * 30 > 1 || message.text && /@CoredumpFlameBot/.test(message.text)) {
    return;
  }

  writeInsult(message);
});
<commit_msg>Add more one-liners<commit_after>var config = require('./config.js');
var monkey_island = require('./monkey_island.js');

var TelegramBot = require('node-telegram-bot-api');

var bot = new TelegramBot(config.token, {polling: true});

/**
 * Returns an insult
 * @param {object} message - The message to reply to
 * @param {object} user - The user to insult
 * @returns {string} The insult
 */
function getInsult(message, user) {
  var u = user.first_name;
  var insults = [
    'You fight like a dairy farmer.',
    'You fight like a cow.',
    'So you want to be a pirate, eh? You look more like a flooring inspector.',
    u + '? That’s the most ridiculous name I’ve ever heard!',
    'You’ve got to help me! I’m a victim of society!',
    'Let’s face it, ' + u + '. You are an evil, foul-smelling, vile, codependent villain and that’s just not what I’m looking for in a romantic relationship right now.',
    'I-- --am your brother!',
    u + ', stop babbling.',
    'You’re about as fearsome as a doorstop.',
    'Oh, so your parents were expecting a girl.',
    'Arrgh! Math be hard, let’s go shoppin’!',
    'Life is like pillaging a trading vessel bound, ' + u + '... Ya never know what you’re gonna get.',
    'Ahh, the middle finger, the most communicative of fingers.',
    'Well… you fight like a cow!',
    'Iron Maiden?! Excellent! ... I have no idea why I just said that.',
    'So you’re going to die... again... wonderful!',
    'Sitting in a dark room with a lava lamp and thinking you’re in heaven?',
    'No no, I’m not questioning your professionalism, it’s just that I don’ even the meaning -',
    'Is it over? ...Hello? ...Did I win?',
    'Aha, mal wieder in der Nase gebohrt, wie?',
    'Willst du mich mit deinem Geschwafel ermüden?',
    'Zu Schade, dass DAS überhaupt niemanden interessiert.',
    'Sollt’ ich in deiner Nähe sterben, möcht’ ich, daß man mich desinfiziert!',
    'Bist du das? Es riecht hier so nach Jauche und Dung!',
    'Ist der Blick in den Spiegel für Dich jeden Tag nicht eine Erniedrigung?',
    'Du hast soviel Sexappeal wie ein Croupier.',
    'Dein Geplänkel kommt nicht richtig in Schwung!',
    'Wurdest du damals von einem Schwein adoptiert?',
    'Das ich nicht lache, ' + u,
    'Deine Mutter trägt ein Toupet.',
    'Dein Geruch allein reicht aus und ich wär’ kollabiert!',
    'Ich glaub’, es gibt für dich noch eine Stelle beim Varieté.',
    'Für dein Gesicht bekommst du ’ne Begnadigung!',
    'unglaublich erbärmlich sag ich',
    'das sind große Worte für ' + u + ' ohne Grips',
    'Dini Mueter.',
  ];
  return insults[Math.floor(Math.random() * insults.length)];
}

/**
 * Writes an insult to the chat
 * @param {object} message - The message to reply to
 * @param {object=} user - The user to insult
 */
function writeInsult(message, user) {
  user = user || message.from;
  bot.sendMessage(message.chat.id, getInsult(message, user), {'reply_to_message_id': message.message_id});
}

bot.onText(/@CoredumpFlameBot/, function(message, match) {
  writeInsult(message);
});

bot.on('message', function(message) {
  if (message.new_chat_participant) {
    writeInsult(message, message.new_chat_participant);
  }

  // search for monkey island matches
  if (message.text) {
    var monkey_island_match = monkey_island.search(message.text);
    if (monkey_island_match) {
      bot.sendMessage(message.chat.id, monkey_island_match, {'reply_to_message_id': message.message_id});
      return;
    }
  }

  if (Math.random() * 30 > 1 || message.text && /@CoredumpFlameBot/.test(message.text)) {
    return;
  }

  writeInsult(message);
});
<|endoftext|>


<commit_before>'use strict'

var Config = require('./config')
var wit = require('./services/wit').getWit()

// LETS SAVE USER SESSIONS
var sessions = {}

var findOrCreateSession = function (fbid) {
  var sessionId

  // DOES USER SESSION ALREADY EXIST?
  Object.keys(sessions).forEach(k => {
    if (sessions[k].fbid === fbid) {
      // YUP
      sessionId = k
    }
  })

  // No session so we will create one
  if (!sessionId) {
    sessionId = new Date().toISOString()
    sessions[sessionId] = {
      fbid: fbid,
      context: {
        _fbid_: fbid
      }
    }
  }

  console.log('fbid is:',sessionId)
  return sessionId
}

var read = function (sender, message, reply) {
	// Let's find the user
	var sessionId = findOrCreateSession(sender)
	console.log ('BOT.JS:user is:',sessionId.fbid)
	var fbid_temp = sessionId.fbid
	//console.log('BOT.JS:Starting context is',context)

	if (message === 'hello') {
		// Let's reply back hello
		message = 'Hello yourself! I am a chat bot. You can say "show me pics of corgis"'
		reply(sender, message)
	} else {
		console.log('BOT.JS:Received message',message)
		// Let's forward the message to the Wit.ai bot engine
		// This will run all actions until there are no more actions left to do
		wit.runActions(
			sessionId, // the user's current session by id
			message,  // the user's message
			sessions[sessionId].context, // the user's session state
			function (error, context) { // callback
			if (error) {
				console.log('BOT.JS: Oops! Got an error from Wit:', error)
			} else {
				// Wit.ai ran all the actions
				// Now it needs more messages
				console.log('BOT.JS:Waiting for further messages')
				fbid_temp = sessions[sessionId].context._fbid_
				// Based on the session state, you might want to reset the session
				// Example:
				// if (context['done']) {
				// 	delete sessions[sessionId]
				// }

				// clear context
				// context = {}
				console.log('BOT.JS:Now context to',context)
				// Updating the user's current session state
				sessions[sessionId].context = {}
				sessions[sessionId].context._fbid_ = fbid_temp

				console.log('BOT.JS:Updated context to',context)
			}
		})
	}
}

module.exports = {
	findOrCreateSession: findOrCreateSession,
	read: read,
}

<commit_msg>retun sessions[]<commit_after>'use strict'

var Config = require('./config')
var wit = require('./services/wit').getWit()

// LETS SAVE USER SESSIONS
var sessions = {}

var findOrCreateSession = function (fbid) {
  var sessionId

  // DOES USER SESSION ALREADY EXIST?
  Object.keys(sessions).forEach(k => {
    if (sessions[k].fbid === fbid) {
      // YUP
      sessionId = k
    }
  })

  // No session so we will create one
  if (!sessionId) {
    sessionId = new Date().toISOString()
    sessions[sessionId] = {
      fbid: fbid,
      context: {
        _fbid_: fbid
      }
    }
  }

  console.log('fbid is:',sessionId)
  return sessions[sessionId]
}

var read = function (sender, message, reply) {
	// Let's find the user
	var sessionId = findOrCreateSession(sender)
	console.log ('BOT.JS:user is:',sessionId.fbid)
	var fbid_temp = sessionId.fbid
	//console.log('BOT.JS:Starting context is',context)

	if (message === 'hello') {
		// Let's reply back hello
		message = 'Hello yourself! I am a chat bot. You can say "show me pics of corgis"'
		reply(sender, message)
	} else {
		console.log('BOT.JS:Received message',message)
		// Let's forward the message to the Wit.ai bot engine
		// This will run all actions until there are no more actions left to do
		wit.runActions(
			sessionId, // the user's current session by id
			message,  // the user's message
			sessions[sessionId].context, // the user's session state
			function (error, context) { // callback
			if (error) {
				console.log('BOT.JS: Oops! Got an error from Wit:', error)
			} else {
				// Wit.ai ran all the actions
				// Now it needs more messages
				console.log('BOT.JS:Waiting for further messages')
				fbid_temp = sessions[sessionId].context._fbid_
				// Based on the session state, you might want to reset the session
				// Example:
				// if (context['done']) {
				// 	delete sessions[sessionId]
				// }

				// clear context
				// context = {}
				console.log('BOT.JS:Now context to',context)
				// Updating the user's current session state
				sessions[sessionId].context = {}
				sessions[sessionId].context._fbid_ = fbid_temp

				console.log('BOT.JS:Updated context to',context)
			}
		})
	}
}

module.exports = {
	findOrCreateSession: findOrCreateSession,
	read: read,
}

<|endoftext|>


<commit_before>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
          \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
           \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
  for a user.

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    set token=<MY TOKEN>

	node bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "who are you?"

  The bot will tell you its name, where it running, and for how long.

  Say: "Call me <nickname>"

  Tell the bot your nickname. Now you are friends.

  Say: "who am I?"

  The bot will tell you your nickname, if it knows one for you.

  Say: "shutdown"

  The bot will ask if you are sure, and then shut itself down.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit is has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var MathHelper = require('./botmath.js');
var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.token
}).startRTM();

controller.hears(['hello','hi','yo'],'direct_message,direct_mention,mention',function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    },function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(',err);
        }
    });

    controller.storage.users.get(message.user,function(err, user) {
        if (user && user.name) {
            bot.reply(message,'Hello ' + user.name + '!!');
        } else {
            bot.reply(message,'Hello.');
        }
    });
});

controller.hears(['call me (.*)'],'direct_message,direct_mention,mention',function(bot, message) {
    var matches = message.text.match(/call me (.*)/i);
    var name = matches[1];
    controller.storage.users.get(message.user,function(err, user) {
        if (!user) {
            user = {
                id: message.user,
            };
        }
        user.name = name;
        controller.storage.users.save(user,function(err, id) {
            bot.reply(message,'Got it. I will call you ' + user.name + ' from now on.');
        });
    });
});

controller.hears(['what is my name','who am i'],'direct_message,direct_mention,mention',function(bot, message) {

    controller.storage.users.get(message.user,function(err, user) {
        if (user && user.name) {
            bot.reply(message,'Your name is ' + user.name);
        } else {
            bot.reply(message,'I don\'t know yet!');
        }
    });
});

controller.hears(['shutdown'],'direct_message,direct_mention,mention',function(bot, message) {

    bot.startConversation(message,function(err, convo) {
        convo.ask('Are you sure you want me to shutdown?',[
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    },3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime','identify yourself','who are you','what is your name'],'direct_message,direct_mention,mention',function(bot, message) {

    var hostname = os.hostname();
    var uptime = formatUptime(process.uptime());

    bot.reply(message,':robot_face: I am a bot named <@' + bot.identity.name + '>. I have been running for ' + uptime + ' on ' + hostname + '.');

});

controller.hears(['fibonacci'], 'direct_message,direct_mention,mention', function(bot, message) {
    if (message.text === 'fibonacci') {
        bot.reply(message, '1, 1, 2, 3, 5');
    }
});

controller.hears(['fibonacci ([0-9]+)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var parameter = parseInt(message.match[1]);

    var fibonacci = calculateFibonacciUpto(parameter);

    if (fibonacci[fibonacci.length-1] !== parameter) {
        bot.reply(message, 'That is not a Fibonacci number!');
    }
    else {
        /*for (var i = 0; i < primes.length; i++) {
            reply += primes[i] + " ";
        }*/
        for (var i = 0; i < 5; i++){
          fibonacci.push(fibonacci[fibonacci.length-2] + fibonacci[fibonacci.length-1])
        }
        bot.reply(message, fibonacci.slice(fibonacci.length-5,fibonacci.length).join(', '));
    }
});

function calculateFibonacciUpto(goal) {
    var fibonacci = [1, 1];

    while (fibonacci[fibonacci.length-1] < goal) {
        fibonacci.push(fibonacci[fibonacci.length-2] + fibonacci[fibonacci.length-1]);
    }

    return fibonacci;
}

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}

controller.hears('prime',['direct_message', 'direct_mention', 'mention'],function(bot,message) {
    if (message.text === "prime") {
        return bot.reply(message, '2, 3, 5, 7, 11, 13, 17, 19, 23, 29');
    }
});

controller.hears('prime (.*)',['direct_message', 'direct_mention', 'mention'],function(bot,message) {

    var parameter = parseInt(message.match[1]);

    if (MathHelper.isPrime(parameter)) {
        var primes = new Array();
        var number = parameter - 1;

        while (primes.length < 10 && number != 0) {

            if (MathHelper.isPrime(number)) {
                primes.push(number);
            }

            number--;
        }

        var reply = "";
        for (var i = 0; i < primes.length; i++) {
            reply += primes[i] + " ";
        }

        return bot.reply(message, reply);
    }
    else {
        return bot.reply(message, "your parameter: " + parameter + " is not Prime number");
    }
});

<commit_msg>speedrun game on branch: coding mission<commit_after>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
          \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
           \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
  for a user.

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    set token=<MY TOKEN>

	node bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "who are you?"

  The bot will tell you its name, where it running, and for how long.

  Say: "Call me <nickname>"

  Tell the bot your nickname. Now you are friends.

  Say: "who am I?"

  The bot will tell you your nickname, if it knows one for you.

  Say: "shutdown"

  The bot will ask if you are sure, and then shut itself down.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit is has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var MathHelper = require('./botmath.js');
var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.token
}).startRTM();

controller.hears(['hello','hi','yo'],'direct_message,direct_mention,mention',function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    },function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(',err);
        }
    });

    controller.storage.users.get(message.user,function(err, user) {
        if (user && user.name) {
            bot.reply(message,'Hello ' + user.name + '!!');
        } else {
            bot.reply(message,'Hello.');
        }
    });
});

controller.hears(['call me (.*)'],'direct_message,direct_mention,mention',function(bot, message) {
    var matches = message.text.match(/call me (.*)/i);
    var name = matches[1];
    controller.storage.users.get(message.user,function(err, user) {
        if (!user) {
            user = {
                id: message.user,
            };
        }
        user.name = name;
        controller.storage.users.save(user,function(err, id) {
            bot.reply(message,'Got it. I will call you ' + user.name + ' from now on.');
        });
    });
});

controller.hears(['what is my name','who am i'],'direct_message,direct_mention,mention',function(bot, message) {

    controller.storage.users.get(message.user,function(err, user) {
        if (user && user.name) {
            bot.reply(message,'Your name is ' + user.name);
        } else {
            bot.reply(message,'I don\'t know yet!');
        }
    });
});

controller.hears(['shutdown'],'direct_message,direct_mention,mention',function(bot, message) {

    bot.startConversation(message,function(err, convo) {
        convo.ask('Are you sure you want me to shutdown?',[
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    },3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime','identify yourself','who are you','what is your name'],'direct_message,direct_mention,mention',function(bot, message) {

    var hostname = os.hostname();
    var uptime = formatUptime(process.uptime());

    bot.reply(message,':robot_face: I am a bot named <@' + bot.identity.name + '>. I have been running for ' + uptime + ' on ' + hostname + '.');

});

controller.hears(['fibonacci'], 'direct_message,direct_mention,mention', function(bot, message) {
    if (message.text === 'fibonacci') {
        bot.reply(message, '1, 1, 2, 3, 5');
    }
});

controller.hears(['fibonacci ([0-9]+)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var parameter = parseInt(message.match[1]);

    var fibonacci = calculateFibonacciUpto(parameter);

    if (fibonacci[fibonacci.length-1] !== parameter) {
        bot.reply(message, 'That is not a Fibonacci number!');
    }
    else {
        /*for (var i = 0; i < primes.length; i++) {
            reply += primes[i] + " ";
        }*/
        for (var i = 0; i < 5; i++){
          fibonacci.push(fibonacci[fibonacci.length-2] + fibonacci[fibonacci.length-1])
        }
        bot.reply(message, fibonacci.slice(fibonacci.length-5,fibonacci.length).join(', '));
    }
});

function calculateFibonacciUpto(goal) {
    var fibonacci = [1, 1];

    while (fibonacci[fibonacci.length-1] < goal) {
        fibonacci.push(fibonacci[fibonacci.length-2] + fibonacci[fibonacci.length-1]);
    }

    return fibonacci;
}

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}

controller.hears('prime',['direct_message', 'direct_mention', 'mention'],function(bot,message) {
    if (message.text === "prime") {
        return bot.reply(message, '2, 3, 5, 7, 11, 13, 17, 19, 23, 29');
    }
});

controller.hears('prime (.*)',['direct_message', 'direct_mention', 'mention'],function(bot,message) {

    var parameter = parseInt(message.match[1]);

    if (MathHelper.isPrime(parameter)) {
        var primes = new Array();
        var number = parameter - 1;

        while (primes.length < 10 && number != 0) {

            if (MathHelper.isPrime(number)) {
                primes.push(number);
            }

            number--;
        }

        var reply = "";
        for (var i = 0; i < primes.length; i++) {
            reply += primes[i] + " ";
        }

        return bot.reply(message, reply);
    }
    else {
        return bot.reply(message, "your parameter: " + parameter + " is not Prime number");
    }
});

controller.hears('game (.*)',['direct_message', 'direct_mention', 'mention'],function(bot,message) {
    var nameOfGame = message.match[1];
    var request = require('request');

    request('http://www.speedrun.com/api_records.php?series=' + nameOfGame, function (error,response, body) {
      if (!error && response.statusCode == 200) {
        var parse = JSON.parse(body);
        bot.reply(message, parse[Object.keys(parse)[0]][Object.keys(parse[Object.keys(parse)[0]])[0]]['time']);
      }
    }

});

<|endoftext|>


<commit_before>var webserver = require('./lib');

var irc = require('irc');
var repl = require('repl');
var opts = require('commander');
var request = require('request');

opts
.option('-c, --console', 'open a console for interactivity with the bot')
.option('-n, --name [name]', 'nickname')
.option('-h, --host [host]', 'IRC host to connect to')
.option('-j, --join <channels>', 'channel(s) to join on start')
.option('-o, --op <users>', 'users to give ops when they join')
.option('-p, --httpPort [port]', 'port for http server to'+
        'listen on. Defaults to 4000')
.parse(process.argv);

if (!opts.httpPort) {
  opts.httpPort = 4000;
}
webserver.init({
  port: opts.httpPort
});
webserver.start();

// all channels in a server
// all users in a channel

var nick = opts.name || 'FernandoBot';
var irchost = opts.host || 'irc.asti-usa.com';
var join = [opts.join] || ['#asti'];

var bot = new irc.Client(irchost, nick, {
  port:     6667,
  debug:    false,
  channels: join
});

function onChannels(){
  return opts.join;
}

function usersInChannel(channel){
  return true;
}

// FIXME merge channel+users list
if (opts.op) {
  for (var oper in opts.op) {
    bot.addListener('join' + join[0], function (nick, message) {
      if (nick === opts.op[oper]) {
        bot.send('mode', opts.join, '+o', nick);
      }
    });
  }
}

bot.addListener('error', function (message) {
  console.log(message);
});

// spawn a console if asked
if (opts.console) {
  var r = repl.start({
    prompt:   'bot> ',
    terminal: true
  });
}

// listen for your name
bot.addListener('pm', function (from, message) {
  console.log(from + ' => ME: ' + message);
});

bot.addListener('message', function (nick, channel, message) {
  request.post('http://localhost:4000/ping', {data: {nick: nick, message: message, channel: channel}});
  //console.log('We have a message from ' + nick + ': '+ channel + " " + message);
});
<commit_msg>funds to get all users in a channel and all channels connected on a server<commit_after>var webserver = require('./lib');

var irc = require('irc');
var repl = require('repl');
var opts = require('commander');
var request = require('request');

opts
.option('-c, --console', 'open a console for interactivity with the bot')
.option('-n, --name [name]', 'nickname')
.option('-h, --host [host]', 'IRC host to connect to')
.option('-j, --join <channels>', 'channel(s) to join on start')
.option('-o, --op <users>', 'users to give ops when they join')
.option('-p, --httpPort [port]', 'port for http server to'+
        'listen on. Defaults to 4000')
.parse(process.argv);

if (!opts.httpPort) {
  opts.httpPort = 4000;
}
webserver.init({
  port: opts.httpPort
});
webserver.start();

var nick = opts.name || 'FernandoBot';
var irchost = opts.host || 'irc.asti-usa.com';
var join = [opts.join] || ['#asti'];

var bot = new irc.Client(irchost, nick, {
  port:     6667,
  debug:    false,
  channels: join
});

// all channels in a server
function onChannels(){
  return Object.keys(bot.chans);
}

// all users in a channel
function inChannel(channel){
  return Object.keys(bot.chans[channel].users);
}

// FIXME merge channel+users list
if (opts.op) {
  for (var oper in opts.op) {
    bot.addListener('join' + join[0], function (nick, message) {
      if (nick === opts.op[oper]) {
        bot.send('mode', opts.join, '+o', nick);
      }
    });
  }
}

bot.addListener('error', function (message) {
  console.log(message);
});

// spawn a console if asked
if (opts.console) {
  var r = repl.start({
    prompt:   'bot> ',
    terminal: true
  });
}

// listen for your name
bot.addListener('pm', function (from, message) {
  console.log(from + ' => ME: ' + message);
});

bot.addListener('message', function (nick, channel, message) {
  request.post('http://localhost:4000/ping', {data: {nick: nick, message: message, channel: channel}});
  //console.log('We have a message from ' + nick + ': '+ channel + " " + message);
});
<|endoftext|>


<commit_before>'use latest';
import bodyParser from 'body-parser';
import express from 'express';
import request from 'request';
import Webtask from 'webtask-tools';
import { MongoClient } from 'mongodb';
import { ObjectID } from 'mongodb';

const collection = 'chatbot.terms';
const server = express();

function Term(key, value) {
  this.key = key;
  this.value = value;
}

var insertTerm = function(term, value, db, cb) {
  db.collection(collection).find().toArray((err, terms) =>  {
    if (err) cb(err);
    else {
      const existing = terms.find(o => o.key === term.toLowerCase());
      if (existing && existing._id !== null) cb(null, `Term \'${term}\' already exists`);
      else {
        db.collection(collection).insertOne(new Term(term.toLowerCase(),value), (err, result) => {
          db.close();
          if (err) cb(err);
          else cb(null, `Added \'${term}\' with response \'${value}\'`);
        });
      }
    }
  });
};

var readTerms = function(db, cb) {
    db.collection(collection).find().toArray((err, terms) =>  {
      db.close();
      if (err) cb(err);
      else cb(null, terms);
    });
};

var updateTerm = function(term, value, db, cb) {
  db.collection(collection).find().toArray((err, terms) =>  {
    if (err) cb(err);
    else {
      var existing = terms.find(o => o.key === term.toLowerCase());
      if (existing && existing._id !== null) {
        db.collection(collection).updateOne({_id: existing._id}, {key: term.toLowerCase(), value: value}, (err, result) => {
          db.close();
          if (err) cb(err);
          else { cb(null, `Updated \'${term}\' with value \'${value}\'`); }
        });
      } else { cb(null, `${term} not found`); }
    }
  });
};

var deleteTerm = function(term, db, cb) {
  db.collection(collection).find().toArray((err, terms) =>  {
      if (err) cb(err);
      else {
        var doomed = terms.find(o => o.key === term.toLowerCase());
        if (doomed) {
          db.collection(collection).remove({_id : doomed._id}, (err, result) => {
            db.close();
            if (err) cb(err);
            else { cb(null, `Term \'${term}\' successfully deleted`); }
          });
        } else { cb(null, `${term} not found`); }
      }
  });
};

var sendToGroupMe = function(text, groupId, botId, cb) {
  request.post("https://api.groupme.com/v3/bots/post",
    {json: {"bot_id": botId, "text": text}},
    (err, res, body) => {
      if (!err && res.statusCode >= 200 && res.statusCode < 300) {
        cb(null, `Successfully posted message \'${text}\'`);
      }
      else cb(err);
    }
  );
};

server.use(bodyParser.json());
server.get('/', (req, res, next) => {
    res.status(200).send('Hello there!');
});

// Receives callback POSTS from GroupMe service
server.post('/', (req, res, next) => {
  const { MONGO_URL, GROUPME_GROUP_ID, GROUPME_BOT_ID } = req.webtaskContext.data;
  MongoClient.connect(MONGO_URL, (err, db) => {
    if (err) return next(err);
    // Expects GroupMe payload
    const comment = req.body.text;
    const parts = comment.split(' ');
    console.log(JSON.stringify(req.body));
    if (req.body.sender_id === 'GROUPME_BOT_ID') res.status(200).send('');
    else {
    if (parts[0].toLowerCase() == '/bot') {
      switch(parts[1]) {
        case 'add':
        case 'new':
        case 'insert':
          insertTerm(parts[2], parts.slice(3, parts.length).join(' '), db, (err, result) => {
            sendToGroupMe(result, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
              res.status(200).send(message);
            });
          });
          break;
        case 'update':
        case 'change':
          updateTerm(parts[2], parts.slice(3, parts.length).join(' '), db, (err, result) => {
            sendToGroupMe(result, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
              res.status(200).send(message);
            });
          });
          break;
        case 'delete':
        case 'remove':
        case 'rm':
          deleteTerm(parts[2], db, (err, result) => {
            sendToGroupMe(result, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
              res.status(200).send(message);
            });
          });
          break;
        default:
          res.status(200).send('Command not found');
      }
    } else {
      readTerms(db, (err, terms) => {
        if (err) res.status(500).send(err);
        else {
          let matches = [];
          for(var i = 0; i < terms.length; i++) {
            if (comment.indexOf(terms[i].key) > -1) matches.push(terms[i].value);
          }
          if (matches.length > 0) {
            matches.forEach(function(match){
              sendToGroupMe(match, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
                res.status(200).send(message);
              });
            });
          } else {res.status(200).send('');}
        }
      });
    }
    }
  });
});

module.exports = Webtask.fromExpress(server);
<commit_msg>Added comment filter for lowercase terms<commit_after>'use latest';
import bodyParser from 'body-parser';
import express from 'express';
import request from 'request';
import Webtask from 'webtask-tools';
import { MongoClient } from 'mongodb';
import { ObjectID } from 'mongodb';

const collection = 'chatbot.terms';
const server = express();

function Term(key, value) {
  this.key = key;
  this.value = value;
}

var insertTerm = function(term, value, db, cb) {
  db.collection(collection).find().toArray((err, terms) =>  {
    if (err) cb(err);
    else {
      const existing = terms.find(o => o.key === term.toLowerCase());
      if (existing && existing._id !== null) cb(null, `Term \'${term}\' already exists`);
      else {
        db.collection(collection).insertOne(new Term(term.toLowerCase(),value), (err, result) => {
          db.close();
          if (err) cb(err);
          else cb(null, `Added \'${term}\' with response \'${value}\'`);
        });
      }
    }
  });
};

var readTerms = function(db, cb) {
    db.collection(collection).find().toArray((err, terms) =>  {
      db.close();
      if (err) cb(err);
      else cb(null, terms);
    });
};

var updateTerm = function(term, value, db, cb) {
  db.collection(collection).find().toArray((err, terms) =>  {
    if (err) cb(err);
    else {
      var existing = terms.find(o => o.key === term.toLowerCase());
      if (existing && existing._id !== null) {
        db.collection(collection).updateOne({_id: existing._id}, {key: term.toLowerCase(), value: value}, (err, result) => {
          db.close();
          if (err) cb(err);
          else { cb(null, `Updated \'${term}\' with value \'${value}\'`); }
        });
      } else { cb(null, `${term} not found`); }
    }
  });
};

var deleteTerm = function(term, db, cb) {
  db.collection(collection).find().toArray((err, terms) =>  {
      if (err) cb(err);
      else {
        var doomed = terms.find(o => o.key === term.toLowerCase());
        if (doomed) {
          db.collection(collection).remove({_id : doomed._id}, (err, result) => {
            db.close();
            if (err) cb(err);
            else { cb(null, `Term \'${term}\' successfully deleted`); }
          });
        } else { cb(null, `${term} not found`); }
      }
  });
};

var sendToGroupMe = function(text, groupId, botId, cb) {
  request.post("https://api.groupme.com/v3/bots/post",
    {json: {"bot_id": botId, "text": text}},
    (err, res, body) => {
      if (!err && res.statusCode >= 200 && res.statusCode < 300) {
        cb(null, `Successfully posted message \'${text}\'`);
      }
      else cb(err);
    }
  );
};

server.use(bodyParser.json());
server.get('/', (req, res, next) => {
    res.status(200).send('Hello there!');
});

// Receives callback POSTS from GroupMe service
server.post('/', (req, res, next) => {
  const { MONGO_URL, GROUPME_GROUP_ID, GROUPME_BOT_ID } = req.webtaskContext.data;
  MongoClient.connect(MONGO_URL, (err, db) => {
    if (err) return next(err);
    // Expects GroupMe payload
    const comment = req.body.text;
    const parts = comment.split(' ');
    console.log(JSON.stringify(req.body));
    if (req.body.sender_id === 'GROUPME_BOT_ID') res.status(200).send('');
    else {
    if (parts[0].toLowerCase() == '/bot') {
      switch(parts[1]) {
        case 'add':
        case 'new':
        case 'insert':
          insertTerm(parts[2], parts.slice(3, parts.length).join(' '), db, (err, result) => {
            sendToGroupMe(result, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
              res.status(200).send(message);
            });
          });
          break;
        case 'update':
        case 'change':
          updateTerm(parts[2], parts.slice(3, parts.length).join(' '), db, (err, result) => {
            sendToGroupMe(result, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
              res.status(200).send(message);
            });
          });
          break;
        case 'delete':
        case 'remove':
        case 'rm':
          deleteTerm(parts[2], db, (err, result) => {
            sendToGroupMe(result, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
              res.status(200).send(message);
            });
          });
          break;
        default:
          res.status(200).send('Command not found');
      }
    } else {
      readTerms(db, (err, terms) => {
        if (err) res.status(500).send(err);
        else {
          let matches = [];
          for(var i = 0; i < terms.length; i++) {
            if (comment.toLowerCase().indexOf(terms[i].key) > -1) matches.push(terms[i].value);
          }
          if (matches.length > 0) {
            matches.forEach(function(match){
              sendToGroupMe(match, GROUPME_GROUP_ID, GROUPME_BOT_ID, (err, message) => {
                res.status(200).send(message);
              });
            });
          } else {res.status(200).send('');}
        }
      });
    }
    }
  });
});

module.exports = Webtask.fromExpress(server);
<|endoftext|>


<commit_before>// ==UserScript==
// @name        audio
// @name:zh-CN
// @namespace   https://github.com/dodying/Dodying-UserJs
// @description:zh-CN
// @include     *
// @version     1
// @grant       none
// @author      Dodying
// @namespace   https://github.com/dodying/Dodying-UserJs
// @supportURL  https://github.com/dodying/Dodying-UserJs/issues
// @icon        https://raw.githubusercontent.com/dodying/UserJs/master/Logo.png
// @run-at      document-end
// ==/UserScript==
var audio = document.createElement('audio');
audio.src = 'https://github.com/dodying/UserJs/raw/master/HentaiVerse/hvAutoAttack/Win.wav';
audio.controls = true;
document.body.appendChild(audio);
audio.play();<commit_msg>Delete audio.user.js<commit_after><|endoftext|>


<commit_before>var Class = require("./Class");

var EventHandler = new Class(
    {
        [`private listeners`]: null,
        [`private addListener`](evnt, fn, once, related){
            if (this.listeners == null)
                this.listeners = {};

            if (fn instanceof Function) {
                if (!this.listeners.hasOwnProperty(evnt))
                    this.listeners[evnt] = [];

                this.listeners[evnt].push({ once: once, handler: fn, related: related });
            }
            else
                throw TypeError("Only functions can be event handlers!");
        },
        [`private removeRelatives`](relatives) {
            if (Array.isArray(relatives) || (relatives instanceof Array)) {
                for (var i=0; i<relatives.length; ++i) {
                    var relative = relatives[i];
                    this.removeEventListener(relative.event, relative.method);
                }
            }
        },
        [`protected deferCall`](fn, params) {
            setTimeout(this.Delegate(function runDeferredCall() {
                fn.apply(undefined, params);
            }), 0);
        }
    },
    [],
    class EventHandler {
        addEventListener(evnt, fn, related) {
            this.addListener(evnt, fn, false, related);
        }

        addEventListenerOnce(evnt, fn, related) {
            this.addListener(evnt, fn, true, related);
        }

        removeEventListener(evnt, fn, withRelatives) {
            if (this.listeners == null)
                this.listeners = {};

            if (this.listeners.hasOwnProperty(evnt)) {
                var handlers = this.listeners[evnt];
                var index = -1;

                while ((++index < handlers.length) && (handlers[index].handler !== fn));

                if (index  < handlers.length) {
                    var handler = handlers[index];
                    this.listeners[evnt].splice(index, 1);
                }

                if (withRelatives)
                    this.removeRelatives(handler.related);
            }
        }
        addRelatedEventListeners(evntList) {
            for (var i=0; i<evntList.length; ++i) {
                var evntHandler = evntList[i];
                var relatives = evntList.slice(0);
                relatives.splice(i, 1);
                this.addEventListener(evntHandler.event, evntHandler.method, relatives);
            }
        }
        addRelatedEventListenersOnce(evntList) {
            for (var i=0; i<evntList.length; ++i) {
                var evntHandler = evntList[i];
                var relatives = evntList.slice(0);
                relatives.splice(i, 1);
                this.addEventListenerOnce(evntHandler.event, evntHandler.method, relatives);
            }
        }
        removeAllHandlers(evnt) {
            if (evnt && this.listeners.hasOwnProperty(evnt))
                this.listeners[evnt] = [];
            else if (!evnt)
                this.listeners = {};
        }
        fireEvent(evnt, params) {
            if (this.listeners == null)
                this.listeners = {};

            if (this.listeners.hasOwnProperty(evnt)) {
                var handlers = this.listeners[evnt];
                var keep = [];

                console.log("Processing event: " + evnt);
                for (var i=0; i<handlers.length; ++i) {
                    var handler = handlers[i];
                    //Queue the event to be handled at the next earliest convenience...
                    this.deferCall(handler.handler, [ params ]);

                    if (!handler.once)
                        keep.push(handler);
                    else if (handler.related)
                        this.removeRelatives(handler.related);
                }

                this.listeners[evnt] = keep;
            }
        }
        fireEventSync(evnt, params) {
            if (this.listeners == null)
                this.listeners = {};

            if (this.listeners.hasOwnProperty(evnt)) {
                var handlers = this.listeners[evnt];
                var keep = [];

                console.log("Processing event: " + evnt);
                for (var i=0; i<handlers.length; ++i) {
                    var handler = handlers[i];
                    //Handle this event now...
                    handler.handler(params);

                    if (!handler.once)
                        keep.push(handler);
                    else if (handler.related)
                        this.removeRelatives(handler.related);
                }

                this.listeners[evnt] = keep;
            }
        }
    }
);

module.exports = EventHandler;
<commit_msg>Removed privilege specifiers from es6 version.<commit_after>var Class = require("./Class");

var EventHandler = new Class(
    {
        listeners: null,
        addListener(evnt, fn, once, related){
            if (this.listeners == null)
                this.listeners = {};

            if (fn instanceof Function) {
                if (!this.listeners.hasOwnProperty(evnt))
                    this.listeners[evnt] = [];

                this.listeners[evnt].push({ once: once, handler: fn, related: related });
            }
            else
                throw TypeError("Only functions can be event handlers!");
        },
        removeRelatives(relatives) {
            if (Array.isArray(relatives) || (relatives instanceof Array)) {
                for (var i=0; i<relatives.length; ++i) {
                    var relative = relatives[i];
                    this.removeEventListener(relative.event, relative.method);
                }
            }
        },
        deferCall(fn, params) {
            setTimeout(this.Delegate(function runDeferredCall() {
                fn.apply(undefined, params);
            }), 0);
        }
    },
    [ "deferCall" ],
    class EventHandler {
        addEventListener(evnt, fn, related) {
            this.addListener(evnt, fn, false, related);
        }

        addEventListenerOnce(evnt, fn, related) {
            this.addListener(evnt, fn, true, related);
        }

        removeEventListener(evnt, fn, withRelatives) {
            if (this.listeners == null)
                this.listeners = {};

            if (this.listeners.hasOwnProperty(evnt)) {
                var handlers = this.listeners[evnt];
                var index = -1;

                while ((++index < handlers.length) && (handlers[index].handler !== fn));

                if (index  < handlers.length) {
                    var handler = handlers[index];
                    this.listeners[evnt].splice(index, 1);
                }

                if (withRelatives)
                    this.removeRelatives(handler.related);
            }
        }
        addRelatedEventListeners(evntList) {
            for (var i=0; i<evntList.length; ++i) {
                var evntHandler = evntList[i];
                var relatives = evntList.slice(0);
                relatives.splice(i, 1);
                this.addEventListener(evntHandler.event, evntHandler.method, relatives);
            }
        }
        addRelatedEventListenersOnce(evntList) {
            for (var i=0; i<evntList.length; ++i) {
                var evntHandler = evntList[i];
                var relatives = evntList.slice(0);
                relatives.splice(i, 1);
                this.addEventListenerOnce(evntHandler.event, evntHandler.method, relatives);
            }
        }
        removeAllHandlers(evnt) {
            if (evnt && this.listeners.hasOwnProperty(evnt))
                this.listeners[evnt] = [];
            else if (!evnt)
                this.listeners = {};
        }
        fireEvent(evnt, params) {
            if (this.listeners == null)
                this.listeners = {};

            if (this.listeners.hasOwnProperty(evnt)) {
                var handlers = this.listeners[evnt];
                var keep = [];

                console.log("Processing event: " + evnt);
                for (var i=0; i<handlers.length; ++i) {
                    var handler = handlers[i];
                    //Queue the event to be handled at the next earliest convenience...
                    this.deferCall(handler.handler, [ params ]);

                    if (!handler.once)
                        keep.push(handler);
                    else if (handler.related)
                        this.removeRelatives(handler.related);
                }

                this.listeners[evnt] = keep;
            }
        }
        fireEventSync(evnt, params) {
            if (this.listeners == null)
                this.listeners = {};

            if (this.listeners.hasOwnProperty(evnt)) {
                var handlers = this.listeners[evnt];
                var keep = [];

                console.log("Processing event: " + evnt);
                for (var i=0; i<handlers.length; ++i) {
                    var handler = handlers[i];
                    //Handle this event now...
                    handler.handler(params);

                    if (!handler.once)
                        keep.push(handler);
                    else if (handler.related)
                        this.removeRelatives(handler.related);
                }

                this.listeners[evnt] = keep;
            }
        }
    }
);

module.exports = EventHandler;
<|endoftext|>