Browse Source

Merge branch 'command-framework'

master
benji7425 4 years ago
parent
commit
8f9acdb455
  1. 20
      app/commands.json
  2. 44
      app/commands/add-feed.js
  3. 18
      app/commands/remove-feed.js
  4. 16
      app/commands/view-feeds.js
  5. 104
      app/index.js
  6. 83
      app/models/feed-data.js
  7. 20
      app/models/guild-data.js
  8. 4
      discord-bot-core/.gitrepo
  9. 9
      discord-bot-core/Client.js
  10. 0
      discord-bot-core/Command.js
  11. 20
      discord-bot-core/HandleMessage.js
  12. 0
      discord-bot-core/Util.js
  13. 2
      discord-bot-core/index.js
  14. 3
      discord-bot-core/package.json

20
app/commands.json

@ -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

@ -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");
});
});
}

18
app/commands/remove-feed.js

@ -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!");
}

16
app/commands/view-feeds.js

@ -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"));
}

104
app/index.js

@ -1,83 +1,37 @@
const GetUrls = require("get-urls"); //for extracting urls from messages
const Core = require("../discord-bot-core");
const GetUrls = require("get-urls");
const GuildData = require("./models/guild-data.js");
const FeedData = require("./models/feed-data.js");
// @ts-ignore
const Config = require("./config.json");
//IMPLEMENTATIONS//
function onReady(coreClient) {
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) {
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 }) {
const feedUrl = [...GetUrls(message.content)][0];
const 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();
const token = require("../" + process.argv[2]).token,
dataFile = process.argv[3];
const feedData = new FeedData({
url: feedUrl,
channelName: channel.name,
roleName: role ? role.name : null,
maxCacheSize: Config.maxCacheSize
});
const client = new Core.Client(token, dataFile, __dirname + "/commands", GuildData);
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 => {
client.on("beforeLogin", () => {
setInterval(() => checkFeedsInGuilds(client.guildsData), Config.feedCheckIntervalSec * 1000);
});
//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: [] });
client.on("ready", () => {
parseLinksInGuilds(client.guilds, client.guildsData)
.then(() => checkFeedsInGuilds(client.guildsData));
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");
client.on("message", message => {
const guildData = client.guildsData[message.guild.id];
if (guildData)
guildData.feeds.forEach(feedData => {
if (message.channel.name === feedData.channelName)
feedData.cachedLinks.push(...GetUrls(message.content));
});
});
}
function removeFeed({ command, params, guildData, botName, message, coreClient }) {
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"));
}
client.bootstrap();
//INTERNAL FUNCTIONS//
function checkFeedsInGuilds(guilds, guildsData) {
Object.keys(guildsData).forEach(key => guildsData[key].checkFeeds(guilds));
function checkFeedsInGuilds(guildsData) {
Object.keys(guildsData).forEach(key => guildsData[key].checkFeeds(client.guilds));
}
function parseLinksInGuilds(guilds, guildsData) {
@ -88,18 +42,4 @@ function parseLinksInGuilds(guilds, guildsData) {
promises.push(guildData.cachePastPostedLinks(guilds.get(guildId)));
}
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();
}

83
app/models/feed-data.js

@ -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
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.url = url;
this.channelName = channelName;
this.roleName = roleName;
this.channelID = channelID;
this.roleID = roleID;
this.cachedLinks = cachedLinks || [];
this.maxCacheSize = maxCacheSize || 10;
this.cachedLinks.push = (...elements) => {
const unique = elements
.map(el => normaliseUrl(el)) //normalise all the urls
.filter(el => !this.cachedLinks.includes(el)); //filter out any already cached
Array.prototype.push.apply(this.cachedLinks, unique);
Array.prototype.push.apply(
this.cachedLinks,
elements
.map(el => normaliseUrl(el))
.filter(el => !this.cachedLinks.includes(el))
);
if (this.cachedLinks.length > this.maxCacheSize)
this.cachedLinks.splice(0, this.cachedLinks.length - this.maxCacheSize); //remove the # of elements above the max from the beginning
//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);
};
}
/**
* 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
*/
/**@param param*/
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) => {
channel.fetchMessages({ limit: 100 })
.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
resolve(this);
/* we want to push the links in oldest first, but discord.js returns messages newest first, so we need to reverse them
* 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);
});
}
check(guild) {
Dns.resolve(Url.parse(this.url).host || "", err => { //check we can resolve the host, so we can throw an appropriate error if it fails
/**@param param */
fetchLatest(guild) {
Dns.resolve(Url.parse(this.url).host || "", 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
FeedRead(this.url, (err, articles) => { //check the feed
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}`));
}
}
});
this._doFetchRSS(guild);
});
}
toString() {
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}`));
}
});
}
};

20
app/models/guild-data.js

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

4
discord-bot-core/.gitrepo

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

9
discord-bot-core/client.js → discord-bot-core/Client.js

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

0
discord-bot-core/command.js → discord-bot-core/Command.js

20
discord-bot-core/HandleMessage.js

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

0
discord-bot-core/util.js → discord-bot-core/Util.js

2
discord-bot-core/index.js

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

3
discord-bot-core/package.json

@ -5,7 +5,8 @@
"discord.js": "11.2.0",
"jsonfile": "3.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",
"repository": {

Loading…
Cancel
Save