Skip to content

Commit

Permalink
Merge pull request #6 from brh55/discord-js
Browse files Browse the repository at this point in the history
botkit-discord v0.1.0
  • Loading branch information
brh55 authored Apr 1, 2019
2 parents 05f31fc + b3ffae4 commit d920ea7
Show file tree
Hide file tree
Showing 17 changed files with 1,897 additions and 381 deletions.
44 changes: 30 additions & 14 deletions api/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
// May just copy over client methods
module.exports = (client) => ({
setPresence: client.setPresence,
editUserInfo: client.editUserInfo,
getAllUsers: client.getAllUsers,
fixMessage: client.fixMessage,
simulateTyping: client.simulateTyping,
getMessage: client.getMessage,
getMessages: client.getMessages,
editMessage: client.editMessage,
deleteMessage: client.deleteMessage,
pinMessage: client.pinMessage,
deletePinnedMessage: client.deletePinnedMessage
});
const joinVoiceChannel = (message) => async () => {
if (!message.member.voiceChannel)
throw Error('User is not in a voice channel');

try {
const connection = await message.member.voiceChannel.join();
return connection;
} catch (error) {
throw Error(error);
}
};

const leaveVoiceChannel = (message) => () => {
const voiceChannel = message.member.voiceChannel;
if (voiceChannel) {
voiceChannel.leave();
}
};

module.exports = (bot, message) => {
// Direct message related APIs
if (message.type === 'direct_message') {
return {
}
}

// Guild message types API (mentions, ambient)
return {
joinVoiceChannel: joinVoiceChannel(message),
leaveVoiceChannel: leaveVoiceChannel(message)
}
}
47 changes: 19 additions & 28 deletions bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,31 @@ function botDefinition (botkit, configuration) {
utterance: botkit.utterance
}

const discordClient = botkit.config.client;

bot.send = (message, cb) => {
discordClient.sendMessage({
to: message.to,
message: message.text
}, cb);
if (typeof cb !== 'function') {
cb = (err, resp) => {
if (err) {
return botkit.debug('Message failed to send: ', err);
}

botkit.debug('Message successfully sent: ', resp);
}
}

message.channel.send(message.text, message.options)
.then(success => cb(null, success))
.catch(cb);
}

bot.reply = (src, resp, cb) => {
let message = {};
const message = resp;
if (typeof(resp) == 'string') {
message.text = resp;
} else {
message = resp;
message.text = Object.assign({}, resp);
}

switch(src.type) {
case 'direct_message':
case 'direct_mention':
// In these two cases, we reply directly to the Author with a Direct Message
message.to = src.author.id;
break;
case 'mention':
case 'ambient':
// If the bot was just mentioned or if it's a channel message, we reply in the channel
message.to = src.channelId;
break;
default:
message.to = src.channelId;
}

bot.say(message, cb);
src.response = message;
// sends to format middle before sent
bot.say(src, cb);
}

bot.findConversation = function(message, cb) {
Expand All @@ -57,9 +49,8 @@ function botDefinition (botkit, configuration) {
}
cb();
};


return bot;
};

module.exports = botDefinition;
module.exports = botDefinition;
47 changes: 47 additions & 0 deletions discord-events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
module.exports = [
"channelCreate",
"channelDelete",
"channelPinsUpdate",
"channelUpdate",
"clientUserGuildSettingsUpdate",
"clientUserSettingsUpdate",
// "debug",
"disconnect",
"emojiCreate",
"emojiDelete",
"emojiUpdate",
"error",
"guildBanAdd",
"guildBanRemove",
"guildCreate",
"guildDelete",
"guildMemberAdd",
"guildMemberAvailable",
"guildMemberRemove",
"guildMembersChunk",
"guildMemberSpeaking",
"guildMemberUpdate",
"guildUnavailable",
"guildUpdate",
// "message",
"messageDelete",
"messageDeleteBulk",
"messageReactionAdd",
"messageReactionRemove",
"messageReactionRemoveAll",
"messageUpdate",
"presenceUpdate",
"rateLimit",
// "ready",
"reconnecting",
"resume",
"roleCreate",
"roleDelete",
"roleUpdate",
"typingStart",
"typingStop",
"userNoteUpdate",
"userUpdate",
"voiceStateUpdate",
"warn"
];
90 changes: 36 additions & 54 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,84 +1,66 @@
const Botkit = require('botkit');
const Discord = require('discord.io');

const Discord = require('discord.js');
const discordEvents = require('./discord-events');
const middleware = require('./middleware');
const botDefinition = require('./bot');

const newMessageHandler = (req, res, controller) => {
const payload = req.body;
const newMessageHandler = (message, controller) => {
const bot = controller.spawn({});
controller.ingest(bot, payload, res);
}
const source = {
raw: message
}

controller.ingest(bot, {}, source);
};

const DiscordBot = (configuration) => {
const client = new Discord.Client({
token: configuration.token,
autorun: true
});
const client = new Discord.Client({});
configuration.client = client;

const discordBotkit = Botkit.core(configuration || {});
discordBotkit.defineBot(botDefinition);
discordBotkit.api = require('./api')(client);

// Pass along classes
discordBotkit.RichEmbed = Discord.RichEmbed;
discordBotkit.Attachment = Discord.Attachment;

// Attach Handlers and Middlewares
discordBotkit.handleMessageRecieve = newMessageHandler;
discordBotkit.middleware.ingest.use(middleware.ingest.handler);
discordBotkit.middleware.normalize.use(middleware.normalize.handler);
discordBotkit.middleware.categorize.use(middleware.categorize.handler);
discordBotkit.middleware.format.use(middleware.format.handler);
discordBotkit.middleware.receive.use(middleware.receive.handler);

// discord.io forwarding and event handling
// may move this elsewhere
client.on('ready', event => {
// Add some additional data to make it easier to work with
const readyEvent = Object.assign({}, event, {
username: client.username,
id: client.id
});
discordBotkit.trigger('ready', [discordBotkit, readyEvent])
discordBotkit.log('Logged in as %s - %s\n', client.username, client.id);
client.on('ready', () => {
discordBotkit.trigger('ready', [discordBotkit, client.user])
discordBotkit.log('Logged in as %s - %s\n', client.user.username, client.user.id);
});

client.on('message', (user, userID, channelID, message, event) => {
const req = {
body: {
user, userID, channelID, message, event
}
};

discordBotkit.handleMessageRecieve(req, {}, discordBotkit);
});

client.on('disconnect', (errMsg, code) => {
const event = {
message: errMsg,
code
};
discordBotkit.trigger('disconnect', [discordBotkit, event]);
client.on('message', async message => {
discordBotkit.debug(`Received ${message}`);
discordBotkit.handleMessageRecieve(message, discordBotkit);
});

client.on('presence', (user, userID, status, game, event) => {
const presenceEvent = event.d;
discordBotkit.trigger('presence', [discordBotkit, event]);
// Set up triggers for remaining events
discordEvents.map(event => {
client.on(event, (...params) => {
discordBotkit.trigger(event, [discordBotkit, params]);
});
});

client.on('guildMemberAdd', member => discordBotkit.trigger('guild_member_add', [discordBotkit, member]));
client.on('guildMemberUpdate', (oldMember, newMember) =>
discordBotkit.trigger('guild_member_update', [discordBotkit, { oldMember, newMember }]
));
client.on('guildMemberRemove', member => discordBotkit.trigger('guild_member_remove', [discordBotkit, member]));

client.on('guildRoleCreate', role => discordBotkit.trigger('guild_role_create', [discordBotkit, role]));
client.on('guildRoleUpdate', (oldRole, newRole) => discordBotkit.trigger('guild_role_update', [discordBotkit, { oldRole, newRole }]));
client.on('guildRoleDelete', role => discordBotkit.trigger('guild_role_delete', [discordBotkit, role]));
if (configuration.debug) {
client.on('debug', info => {
discordBotkit.debug(info);
discordBotkit.trigger('debug', [discordBotkit, info]);
});
}

client.on('channelCreate', channel => discordBotkit.trigger('guild_role_create', [discordBotkit, channel]));
client.on('channelUpdate', (newChannel, oldChannel) => discordBotkit.trigger('guild_role_update', [discordBotkit, { newChannel, oldChannel }]));
client.on('channelDelete', channel => discordBotkit.trigger('guild_role_delete', [discordBotkit, channel]))

// Stay Alive Please
client.login(configuration.token);
discordBotkit.startTicking();

return discordBotkit
};

module.exports = DiscordBot;
module.exports = DiscordBot;
15 changes: 8 additions & 7 deletions middleware/categorize.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
const isMention = (id, messageText) => messageText.indexOf(id) !== -1;
const isDirectMention = (id, messageText) => messageText.indexOf(id) === 2;

// can rename to something logical
// Recategorize
const categorize = (bot, message) => {
const botId = bot.botkit.config.client.id;
const botId = bot.botkit.config.client.user.id;

if (message.raw_message.event.t == 'MESSAGE_CREATE' && message.guildId) {
if (message.type == 'text'
&& message.guildId) {
message.type = 'ambient';
}

if (
message.raw_message.event.t == 'MESSAGE_CREATE' &&
message.type === 'dm' &&
!message.guildId &&
message.author.id !== botId
message.user.id !== botId
) {
message.type = 'direct_message';
}

if (isMention(botId, message.text)) {
message.type = 'mention';

if (isDirectMention(botId, message.text)) {
message.type = 'direct_mention';
}
Expand All @@ -29,7 +30,7 @@ const categorize = (bot, message) => {
};

module.exports.handler = (bot, message, next) => {
categorize(bot, message);
categorize(bot, message);
next();
};

Expand Down
9 changes: 5 additions & 4 deletions middleware/format.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@

// Will format soon
// Will add more formating options
const format = (bot, message, platform_message) => {
platform_message.to = message.to;
platform_message.text = message.text;
return message;
platform_message.channel = message.channel;
platform_message.text = message.response.text;
// Accepted responses
platform_message.options = message.response;
return platform_message;
};

module.exports.handler = (bot, message, platform_message, next) => {
Expand Down
6 changes: 4 additions & 2 deletions middleware/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module.exports = {
ingest: require('./ingest'),
normalize: require('./normalize'),
categorize: require('./categorize'),
format: require('./format')
}
format: require('./format'),
receive: require('./receive')
}
16 changes: 16 additions & 0 deletions middleware/ingest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const cloneDeep = require('clone-deep');

// Safe clone done prior to ingestion to prevent issues f
// from cloning a WS type
const ingest = (bot, payload, source) => {
payload.raw_message = source.raw;
payload.message = cloneDeep(source.raw);
return payload;
};

module.exports.handler = (bot, opayload, source, next) => {
ingest(bot, opayload, source);
next();
}

module.exports.exec = ingest;
Loading

0 comments on commit d920ea7

Please sign in to comment.