This repository has been archived by the owner on Aug 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
331 additions
and
100 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,97 +1,111 @@ | ||
const request = require('request') | ||
const winston = require('winston') | ||
const fetch = require('node-fetch') | ||
const { URLSearchParams } = require('url') | ||
const match = require('@menadevs/objectron') | ||
const { pre } = require('../utils.js') | ||
const secret = require('../secret.json') | ||
|
||
const Plugin = require('../utils.js').Plugin | ||
const verbose = ` | ||
How to use this pluginL | ||
const META = { | ||
name: 'sentiment', | ||
short: 'provides a sentiment analysis on the last 10 messages of a user', | ||
examples: [ | ||
'analyse jordan' | ||
] | ||
} | ||
analyse jordan | ||
` | ||
|
||
function findUser (bot, name) { | ||
return new Promise((resolve, reject) => { | ||
const members = bot.users.filter(m => m.name === name) | ||
|
||
if (members.length !== 1) { | ||
reject(`I don't know of a ${name}`) | ||
} else { | ||
resolve(members[0]) | ||
} | ||
}) | ||
} | ||
/** | ||
* find the user based on the passed name and return the first one found | ||
* returns undefined if no user was found | ||
* @param {*} users | ||
* @param {*} name | ||
*/ | ||
async function findUser (users, name) { | ||
const { members } = await users.list() | ||
|
||
function pickTarget (bot, channel) { | ||
return [...bot.channels, ...bot.groups].filter(c => c.id === channel)[0] | ||
return members.filter(member => member.profile.display_name.toLowerCase() === name.toLowerCase())[0] | ||
} | ||
|
||
function loadRecentMessages (options, channel, user) { | ||
return new Promise((resolve, reject) => { | ||
const target = pickTarget(options.bot, channel) | ||
let source = options.web.channels | ||
|
||
if (target.is_group) { | ||
source = options.web.groups | ||
} | ||
/** | ||
* find the channel or group in the list of workspace channels/groups | ||
* returns undefined if the channel/group didn't match | ||
* @param {*} conversations (could be a channel, a group or an im) | ||
* @param {*} channel | ||
*/ | ||
async function getTargetChannel (conversations, channel) { | ||
const { channels } = await conversations.list() | ||
|
||
source.history(channel, { count: 1000 }, (error, response) => { | ||
if (error) { | ||
reject(error) | ||
} else { | ||
let messages = response.messages.filter(m => m.user === user.id) | ||
return channels.filter(c => c.id === channel && c.is_archived === false)[0] | ||
} | ||
|
||
if (messages.length > options.config.plugins.sentiment.recent) { | ||
messages = messages.slice(1, options.config.plugins.sentiment.recent) | ||
} | ||
/** | ||
* get the user messages in the last 100 messages in the provided channel | ||
* @param {*} channel | ||
* @param {*} user | ||
*/ | ||
async function getUserMessagesInChannel (conversations, channel, user) { | ||
const { messages } = await conversations.history({ channel: channel.id, limit: 1000 }) | ||
const lastTenMessagesByUser = messages.filter(message => message.user === user.id).slice(0, 10) | ||
|
||
if (messages.length === 0) { | ||
reject('User has not spoken recently') | ||
} else { | ||
const text = messages.map(m => m.text).join('\n') | ||
resolve(text) | ||
} | ||
} | ||
}) | ||
}) | ||
return lastTenMessagesByUser | ||
} | ||
|
||
function analyseSentiment (secret, messages) { | ||
return new Promise((resolve, reject) => { | ||
request.post({ | ||
url: 'http://api.datumbox.com/1.0/SentimentAnalysis.json', | ||
form: { | ||
api_key: secret.datumbox, | ||
text: messages | ||
}, | ||
headers: { | ||
'User-Agent': 'request' | ||
} | ||
}, (error, response, body) => { | ||
if (error) { | ||
reject(error) | ||
} else { | ||
resolve(JSON.parse(body)) | ||
} | ||
}) | ||
}) | ||
/** | ||
* Send the messages to the api and return response | ||
* @param {*} secret | ||
* @param {*} messages | ||
*/ | ||
async function analyseSentiment (messages) { | ||
const params = new URLSearchParams() | ||
params.set('api_key', secret.datumbox) | ||
params.append('text', messages) | ||
const response = await fetch('http://api.datumbox.com/1.0/SentimentAnalysis.json', { method: 'POST', body: params }) | ||
const jsonResult = await response.json() | ||
return jsonResult | ||
} | ||
|
||
function analyse (options, message, target) { | ||
findUser(options.bot, target) | ||
.then(user => loadRecentMessages(options, message.channel, user)) | ||
.then(messages => analyseSentiment(options.secret, messages)) | ||
.then(sentiment => message.reply_thread(`${target} has recently been ${sentiment.output.result}`)) | ||
.catch(error => winston.error(`${META.name} - Error: ${error}`)) | ||
async function analyse (options, message, target) { | ||
try { | ||
const user = await findUser(options.web.users, target) | ||
if (!user) { | ||
message.reply_thread(`I don't know of a ${target}. Please validate you entered the correct person's name.`) | ||
return | ||
} | ||
|
||
const targetChannel = await getTargetChannel(options.web.conversations, message.channel) | ||
if (!targetChannel) { | ||
message.reply_thread('Are you in a channel or group? sentiment doesn\'t work in a direct message') | ||
return | ||
} | ||
|
||
const messages = await getUserMessagesInChannel(options.web.conversations, targetChannel, user) | ||
if (messages.length !== 0) { | ||
const response = await analyseSentiment(messages.map(m => m.text).join('\n')) | ||
message.reply_thread(`${target} has recently been ${response.output.result}`) | ||
} else { | ||
message.reply_thread(`'User ${target} has not spoken recently'`) | ||
} | ||
} catch (error) { | ||
console.error(error) | ||
message.reply_thread(`Something went wrong! this has nothing to do with the sentiments of ${target}. Please check the logs.`) | ||
options.logger.error(`${module.exports.name} - something went wrong. Here's the error: ${pre(error)}`) | ||
} | ||
} | ||
|
||
function register (bot, rtm, web, config, secret) { | ||
const plugin = new Plugin({ bot, rtm, web, config, secret }) | ||
plugin.route(/^analyse (.+)/, analyse, {}) | ||
const events = { | ||
message: (options, message) => { | ||
match(message, { | ||
type: 'message', | ||
text: /^analyse (?<name>.+)/ | ||
}, result => analyse(options, message, result.groups.name)) | ||
} | ||
} | ||
|
||
module.exports = { | ||
register, | ||
META | ||
name: 'sentiment', | ||
help: 'provides a sentiment analysis on the last 10 messages of a user', | ||
verbose, | ||
events, | ||
findUser, | ||
getTargetChannel, | ||
getUserMessagesInChannel, | ||
analyseSentiment, | ||
analyse | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.