Merge branch 'command-framework'

This commit is contained in:
benji7425 2017-10-01 23:27:51 +01:00
commit 8f9acdb455
14 changed files with 183 additions and 160 deletions

View File

@ -1,20 +0,0 @@
{
"addFeed": {
"command": "add-feed",
"description": "Add an RSS feed to be posted in a channel, with an optional role to tag",
"syntax": "add-feed <url> <#channel> [@role]",
"admin": true
},
"removeFeed": {
"command": "remove-feed",
"description": "Remove an RSS feed by it's ID",
"syntax": "remove-feed <id>",
"admin": true
},
"viewFeeds": {
"command": "view-feeds",
"description": "View a list of configured feeds and their associated details",
"syntax": "view-feed",
"admin": true
}
}

44
app/commands/add-feed.js Normal file
View File

@ -0,0 +1,44 @@
const Core = require("../../discord-bot-core");
const GetUrls = require("get-urls");
const FeedData = require("../models/feed-data.js");
const GuildData = require("../models/guild-data.js");
// @ts-ignore
const Config = require("../config.json");
module.exports = new Core.Command({
name: "add-feed",
description: "Add an RSS feed to be posted in a channel, with an optional role to tag",
syntax: "add-feed <url> <#channel> [@role]",
admin: true,
invoke: invoke
});
function invoke({ message, params, guildData, client }) {
const feedUrl = [...GetUrls(message.content)][0],
channel = message.mentions.channels.first();
if (!feedUrl || !channel)
return Promise.reject("Please provide both a channel and an RSS feed URL. You can optionally @mention a role also.");
const role = message.mentions.roles.first(),
feedData = new FeedData({
url: feedUrl,
channelID: channel.id,
roleID: role ? role.id : null,
maxCacheSize: Config.maxCacheSize
});
return new Promise((resolve, reject) => {
//ask the user if they're happy with the details they set up, save if yes, don't if no
Core.util.ask(client, message.channel, message.member, "Are you happy with this (yes/no)?\n" + feedData.toString())
.then(responseMessage => {
if (responseMessage.content.toLowerCase() === "yes") {
guildData.feeds.push(feedData);
guildData.cachePastPostedLinks(message.guild)
.then(() => resolve("Your new feed has been saved!"));
}
else
reject("Your feed has not been saved, please add it again with the correct details");
});
});
}

View File

@ -0,0 +1,18 @@
const Core = require("../../discord-bot-core");
module.exports = new Core.Command({
name: "remove-feed",
description: "Remove an RSS feed by it's ID",
syntax: "remove-feed <dir>",
admin: true,
invoke: invoke
});
function invoke({ message, params, guildData, client }) {
const idx = guildData.feeds.findIndex(feed => feed.id === params[2]);
if (!Number.isInteger(idx))
return Promise.reject("Can't find feed with id " + params[2]);
guildData.feeds.splice(idx, 1);
return Promise.resolve("Feed removed!");
}

View File

@ -0,0 +1,16 @@
const Core = require("../../discord-bot-core");
module.exports = new Core.Command({
name: "view-feeds",
description: "View a list of configured feeds and their associated details",
syntax: "view-feed",
admin: true,
invoke: invoke
});
function invoke({ message, params, guildData, client }) {
if (!guildData)
return Promise.reject("Guild not setup");
return Promise.resolve(guildData.feeds.map(f => f.toString()).join("\n"));
}

View File

@ -1,83 +1,37 @@
const GetUrls = require("get-urls"); //for extracting urls from messages
const Core = require("../discord-bot-core"); const Core = require("../discord-bot-core");
const GetUrls = require("get-urls");
const GuildData = require("./models/guild-data.js"); const GuildData = require("./models/guild-data.js");
const FeedData = require("./models/feed-data.js"); // @ts-ignore
const Config = require("./config.json"); const Config = require("./config.json");
//IMPLEMENTATIONS// const token = require("../" + process.argv[2]).token,
function onReady(coreClient) { dataFile = process.argv[3];
return new Promise((resolve, reject) => {
parseLinksInGuilds(coreClient.actual.guilds, coreClient.guildsData)
.then(() => checkFeedsInGuilds(coreClient.actual.guilds, coreClient.guildsData))
.then(() => setInterval(() => checkFeedsInGuilds(coreClient.actual.guilds, coreClient.guildsData), Config.feedCheckIntervalSec * 1000))
.then(resolve)
.catch(reject);
});
}
function onTextMessage(message, guildData) { const client = new Core.Client(token, dataFile, __dirname + "/commands", GuildData);
guildData.feeds.forEach(feedData => {
if (message.channel.name === feedData.channelName)
feedData.cachedLinks.push(...GetUrls(message.content)); //spread the urlSet returned by GetUrls into the cache array
});
return Promise.resolve();
}
function addFeed({ command, params, guildData, botName, message, coreClient }) { client.on("beforeLogin", () => {
const feedUrl = [...GetUrls(message.content)][0]; setInterval(() => checkFeedsInGuilds(client.guildsData), Config.feedCheckIntervalSec * 1000);
const channel = message.mentions.channels.first(); });
if (!feedUrl || !channel) client.on("ready", () => {
return Promise.reject("Please provide both a channel and an RSS feed URL. You can optionally @mention a role also."); parseLinksInGuilds(client.guilds, client.guildsData)
.then(() => checkFeedsInGuilds(client.guildsData));
const role = message.mentions.roles.first(); client.on("message", message => {
const guildData = client.guildsData[message.guild.id];
const feedData = new FeedData({ if (guildData)
url: feedUrl, guildData.feeds.forEach(feedData => {
channelName: channel.name, if (message.channel.name === feedData.channelName)
roleName: role ? role.name : null, feedData.cachedLinks.push(...GetUrls(message.content));
maxCacheSize: Config.maxCacheSize
});
return new Promise((resolve, reject) => {
//ask the user if they're happy with the details they set up, save if yes, don't if no
Core.util.ask(coreClient.actual, message.channel, message.member, "Are you happy with this (yes/no)?\n" + feedData.toString())
.then(responseMessage => {
//if they responded yes, save the feed and let them know, else tell them to start again
if (responseMessage.content.toLowerCase() === "yes") {
if (!guildData)
guildData = new GuildData({ id: message.guild.id, feeds: [] });
guildData.feeds.push(feedData);
guildData.cachePastPostedLinks(message.guild)
.then(() => resolve("Your new feed has been saved!"));
}
else
reject("Your feed has not been saved, please add it again with the correct details");
}); });
}); });
} });
function removeFeed({ command, params, guildData, botName, message, coreClient }) { client.bootstrap();
const idx = guildData.feeds.findIndex(feed => feed.id === params[2]);
if (!Number.isInteger(idx))
return Promise.reject("Can't find feed with id " + params[2]);
guildData.feeds.splice(idx, 1);
return Promise.resolve("Feed removed!");
}
function viewFeeds({ command, params, guildData, botName, message, coreClient }) {
if (!guildData)
return Promise.reject("Guild not setup");
return Promise.resolve(guildData.feeds.map(f => f.toString()).join("\n"));
}
//INTERNAL FUNCTIONS// //INTERNAL FUNCTIONS//
function checkFeedsInGuilds(guilds, guildsData) { function checkFeedsInGuilds(guildsData) {
Object.keys(guildsData).forEach(key => guildsData[key].checkFeeds(guilds)); Object.keys(guildsData).forEach(key => guildsData[key].checkFeeds(client.guilds));
} }
function parseLinksInGuilds(guilds, guildsData) { function parseLinksInGuilds(guilds, guildsData) {
@ -88,18 +42,4 @@ function parseLinksInGuilds(guilds, guildsData) {
promises.push(guildData.cachePastPostedLinks(guilds.get(guildId))); promises.push(guildData.cachePastPostedLinks(guilds.get(guildId)));
} }
return Promise.all(promises); return Promise.all(promises);
} }
//CLIENT SETUP//
const token = require("../" + process.argv[2]).token,
dataFile = process.argv[3],
commands = require("./commands.json"),
implementations = {
onReady,
onTextMessage,
addFeed,
removeFeed,
viewFeeds
};
const client = new Core.Client(token, dataFile, commands, implementations, GuildData);
client.bootstrap();

View File

@ -9,71 +9,78 @@ const GetUrls = require("get-urls"); //for extracting urls from messages
const ShortID = require("shortid"); //to provide ids for each feed, allowing guilds to remove them const ShortID = require("shortid"); //to provide ids for each feed, allowing guilds to remove them
module.exports = class FeedData { module.exports = class FeedData {
constructor({ id, url, channelName, roleName, cachedLinks, maxCacheSize }) { constructor({ id = null, url, channelID, roleID, cachedLinks = null, maxCacheSize }) {
this.id = id || ShortID.generate(); this.id = id || ShortID.generate();
this.url = url; this.url = url;
this.channelName = channelName; this.channelID = channelID;
this.roleName = roleName; this.roleID = roleID;
this.cachedLinks = cachedLinks || []; this.cachedLinks = cachedLinks || [];
this.maxCacheSize = maxCacheSize || 10; this.maxCacheSize = maxCacheSize || 10;
this.cachedLinks.push = (...elements) => { this.cachedLinks.push = (...elements) => {
const unique = elements Array.prototype.push.apply(
.map(el => normaliseUrl(el)) //normalise all the urls this.cachedLinks,
.filter(el => !this.cachedLinks.includes(el)); //filter out any already cached elements
Array.prototype.push.apply(this.cachedLinks, unique); .map(el => normaliseUrl(el))
.filter(el => !this.cachedLinks.includes(el))
);
if (this.cachedLinks.length > this.maxCacheSize) //seeing as new links come in at the end of the array, we need to remove the old links from the beginning
this.cachedLinks.splice(0, this.cachedLinks.length - this.maxCacheSize); //remove the # of elements above the max from the beginning this.cachedLinks.splice(0, this.cachedLinks.length - this.maxCacheSize);
}; };
} }
/** /**@param param*/
* Returns a promise providing all the links posted in the last 100 messages
* @param {Discord.Guild} guild The guild this feed belongs to
* @returns {Promise<string[]>} Links posted in last 100 messages
*/
updatePastPostedLinks(guild) { updatePastPostedLinks(guild) {
const channel = guild.channels.find(ch => ch.type === "text" && ch.name === this.channelName); const channel = guild.channels.get(this.channelID);
if (!channel)
return Promise.reject("Channel not found!");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
channel.fetchMessages({ limit: 100 }) channel.fetchMessages({ limit: 100 })
.then(messages => { .then(messages => {
new Map([...messages].reverse()).forEach(m => this.cachedLinks.push(...GetUrls(m.content))); //push all the links in each message into our links array /* we want to push the links in oldest first, but discord.js returns messages newest first, so we need to reverse them
resolve(this); * discord.js returns a map, and maps don't have .reverse methods, hence needing to spread the elements into an array first */
[...messages.values()].reverse().forEach(m => this.cachedLinks.push(...GetUrls(m.content)));
resolve();
}) })
.catch(reject); .catch(reject);
}); });
} }
check(guild) { /**@param param */
Dns.resolve(Url.parse(this.url).host || "", err => { //check we can resolve the host, so we can throw an appropriate error if it fails fetchLatest(guild) {
Dns.resolve(Url.parse(this.url).host || "", err => {
if (err) if (err)
DiscordUtil.dateError("Connection Error: Can't resolve host", err); //log our error if we can't resolve the host DiscordUtil.dateError("Connection Error: Can't resolve host", err.message || err);
else else
FeedRead(this.url, (err, articles) => { //check the feed this._doFetchRSS(guild);
if (err)
DiscordUtil.dateError(err);
else {
let latest = articles[0].link; //extract the latest link
latest = normaliseUrl(latest); //standardise it a bit
//if we don't have it cached already, cache it and callback
if (!this.cachedLinks.includes(latest)) {
this.cachedLinks.push(latest);
const channel = guild.channels.find(ch => ch.type === "text" && ch.name.toLowerCase() === this.channelName.toLowerCase());
const role = this.roleName ? guild.roles.find(role => role.name.toLowerCase() === this.roleName.toLowerCase()) : null;
channel.send((role ? role + " " : "") + latest).catch(err => DiscordUtil.dateError(`Error posting in ${channel.id}`));
}
}
});
}); });
} }
toString() { toString() {
const blacklist = ["cachedLinks", "maxCacheSize"]; const blacklist = ["cachedLinks", "maxCacheSize"];
return `\`\`\`JavaScript\n ${JSON.stringify(this, (k, v) => !blacklist.includes(k) ? v : undefined, "\t")} \`\`\``; return `\`\`\`JavaScript\n ${JSON.stringify(this, (k, v) => !blacklist.find(x => x === k) ? v : undefined, "\t")} \`\`\``;
}
_doFetchRSS(guild) {
FeedRead(this.url, (err, articles) => {
if (err)
return DiscordUtil.dateError(err.message || err);
const latest = normaliseUrl(articles[0].link);
if (!this.cachedLinks.includes(latest)) {
this.cachedLinks.push(latest);
const channel = guild.channels.get(this.channelID),
role = guild.roles.get(this.roleID);
channel.send((role ? role + " " : "") + latest)
.catch(err => DiscordUtil.dateError(`Error posting in ${channel.id}: ${err.message || err}`));
}
});
} }
}; };

View File

@ -1,23 +1,27 @@
const DiscordUtil = require("../../discord-bot-core").util; const DiscordUtil = require("../../discord-bot-core").util;
const Core = require("../../discord-bot-core");
const FeedData = require("./feed-data.js"); const FeedData = require("./feed-data.js");
module.exports = class GuildData { module.exports = class GuildData extends Core.BaseGuildData {
constructor({ id, feeds }) { constructor({ id, feeds = [] }) {
this.id = id; super(id);
this.feeds = (feeds || []).map(feed => new FeedData(feed)); this.feeds = feeds.map(feed => new FeedData(feed));
} }
cachePastPostedLinks(guild) { cachePastPostedLinks(guild) {
const promises = []; const promises = [];
this.feeds.forEach(feed => { this.feeds.forEach(feed =>
promises.push(feed.updatePastPostedLinks(guild).catch(err => DiscordUtil.dateError(`Error reading history in ${err.path}`))); promises.push(
}); feed.updatePastPostedLinks(guild)
.catch(err => DiscordUtil.dateError(`Error reading history in ${err.path}`))
)
);
return Promise.all(promises); return Promise.all(promises);
} }
checkFeeds(guilds) { checkFeeds(guilds) {
this.feeds.forEach(feed => feed.check(guilds.get(this.id))); this.feeds.forEach(feed => feed.fetchLatest(guilds.get(this.id)));
} }
}; };

View File

@ -6,7 +6,7 @@
[subrepo] [subrepo]
remote = git@github.com:benji7425/discord-bot-core.git remote = git@github.com:benji7425/discord-bot-core.git
branch = master branch = master
commit = 180d069b012d38d6d3c539df5a04475683139b01 commit = 9f209e1091fc160491a2b63099c442aff0a125e8
parent = 176b7b8ad9ca41d1b9f7a15869ed5ed95ccad25d parent = 00f9f48764fe44417cf29374d22d510ec34bdc5f
method = merge method = merge
cmdver = 0.3.1 cmdver = 0.3.1

View File

@ -2,7 +2,7 @@ const FileSystem = require("fs");
const Discord = require("discord.js"); const Discord = require("discord.js");
const JsonFile = require("jsonfile"); const JsonFile = require("jsonfile");
const RequireAll = require("require-all"); const RequireAll = require("require-all");
const CoreUtil = require("./util.js"); const CoreUtil = require("./Util.js");
const HandleMessage = require("./HandleMessage.js"); const HandleMessage = require("./HandleMessage.js");
// @ts-ignore // @ts-ignore
const InternalConfig = require("./internal-config.json"); const InternalConfig = require("./internal-config.json");
@ -47,8 +47,11 @@ module.exports = class Client extends Discord.Client {
} }
onMessage(message) { onMessage(message) {
if (message.channel.type === "text" && message.member) if (message.channel.type === "text" && message.member) {
HandleMessage(message, this.commands, this.guildsData[message.guild.id] || new this.guildDataModel(message.guild.id)); if(!this.guildsData[message.guild.id])
this.guildsData[message.guild.id] = new this.guildDataModel({ id: message.guild.id });
HandleMessage(this, message, this.commands, this.guildsData[message.guild.id]);
}
} }
onDebug(info) { onDebug(info) {

View File

@ -1,8 +1,9 @@
// @ts-ignore // @ts-ignore
const ParentPackageJSON = require("../package.json"); const ParentPackageJSON = require("../package.json");
const CoreUtil = require("./Util.js");
/**@param param*/ /**@param param*/
function handleMessage(message, commands, guildData) { function handleMessage(client, message, commands, guildData) {
if (!message.content.startsWith(message.guild.me.toString())) //criteria for a command is the bot being tagged if (!message.content.startsWith(message.guild.me.toString())) //criteria for a command is the bot being tagged
return; return;
@ -13,18 +14,27 @@ function handleMessage(message, commands, guildData) {
command = commands[Object.keys(commands).find(x => commands[x].name.toLowerCase() === (split[1] || "").toLowerCase())]; command = commands[Object.keys(commands).find(x => commands[x].name.toLowerCase() === (split[1] || "").toLowerCase())];
if (!command) if (!command)
handleInternalCommand(message, params); handleInternalCommand(message, split);
else if (params.length < command.expectedParamCount) else if (params.length < command.expectedParamCount)
message.reply(`Incorrect syntax!\n**Expected:** *${botName} ${command.syntax}*\n**Need help?** *${botName} help*`); message.reply(`Incorrect syntax!\n**Expected:** *${botName} ${command.syntax}*\n**Need help?** *${botName} help*`);
else if(isMemberAdmin || !command.admin) else if (isMemberAdmin || !command.admin)
command.invoke({ message, params, guildData }); command.invoke({ message, params, guildData, client })
.then(response => {
client.writeFile();
if (response)
message.reply(response);
})
.catch(err => {
if (err)
message.reply(err);
});
} }
/**@param param*/ /**@param param*/
function handleInternalCommand(message, split) { function handleInternalCommand(message, split) {
if (split[1].toLowerCase() === "version") if (split[1].toLowerCase() === "version")
message.reply(`${ParentPackageJSON.name} v${ParentPackageJSON.version}`); message.reply(`${ParentPackageJSON.name} v${ParentPackageJSON.version}`);
else if(split[1].toLowerCase() === "help") else if (split[1].toLowerCase() === "help")
message.reply(createHelpEmbed()); message.reply(createHelpEmbed());
} }

View File

@ -2,7 +2,7 @@
const InternalConfig = require("./internal-config.json"); const InternalConfig = require("./internal-config.json");
module.exports = { module.exports = {
Client: require("./client.js"), Client: require("./Client.js"),
BaseGuildData: require("./BaseGuildData.js"), BaseGuildData: require("./BaseGuildData.js"),
Command: require("./Command.js"), Command: require("./Command.js"),
util: require("./Util.js"), util: require("./Util.js"),

View File

@ -5,7 +5,8 @@
"discord.js": "11.2.0", "discord.js": "11.2.0",
"jsonfile": "3.0.1", "jsonfile": "3.0.1",
"parent-package-json": "2.0.1", "parent-package-json": "2.0.1",
"simple-file-writer": "2.0.0" "simple-file-writer": "2.0.0",
"require-all": "2.2.0"
}, },
"name": "discord-bot-core", "name": "discord-bot-core",
"repository": { "repository": {