Add info command, update wumpfetch and add raw to stats

This commit is contained in:
Wessel T
2019-02-20 22:32:56 +01:00
parent 395e36873e
commit c2e818c668
13 changed files with 259 additions and 55 deletions

View File

@@ -10,7 +10,7 @@
- [x] Use
- [x] List
- [ ] Edit
- [ ] Info
- [x] Info
- [x] Create
- [x] Delete
- [x] Source

View File

@@ -20,7 +20,7 @@
"sharp": "^0.21.3",
"table": "^5.2.3",
"vm2": "^3.6.10",
"wumpfetch": "^0.0.7"
"wumpfetch": "^0.0.8"
},
"devDependencies": {
"eslint": "^5.6.0"

View File

@@ -52,6 +52,14 @@ tags:
4: <:wumpus_love:506200781549076482>
5: <:wumpus_love:506200781549076482>
info:
0: <:wumpus_blob:541629681120837648> # Invalid tag
1: <:send:544872984708513825> # Name
2: <:wumpus_love:506200781549076482> # Used
3: <:wumpking:544167185329815589> # Creator
4: <:wumplus:542809926414761995> # Creation
5: <:spacewump:542723940997529641> # History
list:
0 : <:wumpus_blob:541629681120837648>
1 : <:ok_hand:497396122416054287>

View File

@@ -171,9 +171,17 @@ tags:
- ''
- '$[tag:list]'
extend: '$[emoji#2] [Click here for a list of all tags]($[tag:full])'
info:
- '$[emoji#1] **Name**: $[tag:name]'
- '$[emoji#2] **Used**: $[tag:uses] time(s)'
- '$[emoji#3] **Creator**: $[tag:creator#tag]'
- '$[emoji#4] **Creation**: $[tag:creation]'
- '$[emoji#5] **Recent history**:'
- '$[tag:history]'
add:
success: '$[emoji#1] Your tag (`$[tag:name]`) has been created'
success: '$[emoji#1] Your tag ($[tag:name]) has been created'
invalid: '$[emoji#2] You''ve provided an invalid name for your tag (*It may already exist or it''s the name/alias of a command*)'
content:
- '$[emoji#3] What do you want your tag''s contents to be?'
@@ -183,13 +191,14 @@ tags:
- '$[emoji#6] Reply to this prompt within **30 seconds**, type `--cancel` to cancel it manually.'
delete:
busy: '$[emoji#1] Deleting tag `$[tag:name]`, this may take some time...'
done: '$[emoji#2] The tag `$[tag:name]` has been deleted'
busy: '$[emoji#1] Deleting tag "$[tag:name]"", this may take some time...'
done: '$[emoji#2] The tag "$[tag:name]" has been deleted'
perms: '$[emoji#3] You don''t have sufficient permissions to delete this tag (`TAG_OWNER` / `MANAGE_MESSAGES`)'
invalid: '$[emoji#4] No tags found matching your query'
confirm:
- '$[emoji#5] Are you sure you want to delete the tag `$[tag:name]`? **(** **Y**es **/** **N**o **)**'
- '$[emoji#5] Are you sure you want to delete the tag "$[tag:name]"? **(** **Y**es **/** **N**o **)**'
- '$[emoji#6] Reply to this prompt within **30 seconds**, type `--cancel` to cancel it manually.'
games:
splatoon:
- 'The current maps are:'

View File

@@ -171,9 +171,17 @@ tags:
- ''
- '$[tag:list]'
extend: '$[emoji#2] [klik hier voor een list met al de etiketten]($[tag:full])'
info:
- '$[emoji#1] **Naam**: $[tag:name]'
- '$[emoji#2] **gebruikt**: $[tag:uses] keer'
- '$[emoji#3] **Auteur**: $[tag:creator#tag]'
- '$[emoji#4] **Creatie**: $[tag:creation]'
- '$[emoji#5] **Recente Geschiedenis**:'
- '$[tag:history]'
add:
success: '$[emoji#1] Uw etiket (`$[tag:name]`) is aangemaakt'
success: '$[emoji#1] Uw etiket ($[tag:name]) is aangemaakt'
invalid: '$[emoji#2] U hebt een ongeldige naam opgegeven voor uw etiket (*deze kan al bestaan of is de naam/alias van een commando*)'
content:
- '$[emoji#3] Wat wilt u dat de inhoud van uw etiket is?'
@@ -183,8 +191,8 @@ tags:
- '$[emoji#4] Reageer op dit prompt binnen ** 30 seconden **, typ `--cancel` om het handmatig te annuleren.'
delete:
busy: '$[emoji#1] Aan het verwijderen van etiket `$[tag:name]`, dit kan enige tijd duren...'
done: '$[emoji#2] Het etiket `$[tag:name]` is successvol verwijderd'
busy: '$[emoji#1] Aan het verwijderen van etiket "$[tag:name]", dit kan enige tijd duren...'
done: '$[emoji#2] Het etiket "$[tag:name] is successvol verwijderd'
perms: '$[emoji#3] U hebt onvoldoende machtigingen om dit etiket te verwijderen (`TAG_OWNER` / `MANAGE_MESSAGES`)'
invalid: '$[emoji#4] Geen etiketten gevonden met uw zoekopdracht'
confirm:

View File

@@ -3,6 +3,7 @@ const { DiscordCommand } = require('../../../core');
const os = require('os');
const larg = require('larg');
const moment = require('moment'); require('../../../util/moment/format');
const { table } = require('table');
const { readFileSync } = require('fs');
module.exports = class Stats extends DiscordCommand {
@@ -25,6 +26,34 @@ module.exports = class Stats extends DiscordCommand {
try { this.thumb = readFileSync('./assets/img/thumb/stats.png'); }
catch(ex) { this.thumb = undefined; }
this.mutable = {
TABLE_CONFIG: {
border: {
topBody: `-`,
topJoin: `+`,
topLeft: `+`,
topRight: `+`,
bottomBody: `-`,
bottomJoin: `+`,
bottomLeft: `+`,
bottomRight: `+`,
bodyLeft: `|`,
bodyRight: `|`,
bodyJoin: `|`,
joinBody: `-`,
joinLeft: `+`,
joinRight: `+`,
joinJoin: `+`
},
drawHorizontalLine: (_, s) => {
return _ === 0 || _ === 1 || _ === s;
}
}
};
}
async execute( msg, args ) {
@@ -50,7 +79,7 @@ module.exports = class Stats extends DiscordCommand {
default : platform.platform = 'Unknown';
}
const fields = [];
let fields = [];
if (!args['no-bot']) {
fields.push({
@@ -74,7 +103,7 @@ module.exports = class Stats extends DiscordCommand {
[
`${this.bot.emote('info', 'statistics', '1')} **Operating System**: ${platform.platform} ${platform.release} **(**${platform.arch}**)**`,
`${this.bot.emote('info', 'statistics', '2')} **Process Hash**: ${process.hash}`,
`${this.bot.emote('info', 'statistics', '3')} **Load Average**: ${os.loadavg().join(' **/** ')}`,
`${this.bot.emote('info', 'statistics', '3')} **Load Average**: ${os.loadavg().map(v => v.toFixed(2)).join(' **/** ')}`,
`${this.bot.emote('info', 'statistics', '4')} **OS Uptime**: ${moment.duration(os.uptime() * 1000).format('YYYY[y] MM[M] DD[d] HH[h] mm[m] ss[s]')}`,
`${this.bot.emote('info', 'statistics', '5')} **Uptime**: ${moment.duration(this.bot.uptime).format('YYYY[y] MM[M] DD[d] HH[h] mm[m] ss[s]')}`,
`${this.bot.emote('info', 'statistics', '6')} **Memory**: ${this.formatBytes(process.memoryUsage().heapUsed)} **/** ${this.formatBytes(os.totalmem())} **(**${((process.memoryUsage().heapUsed / os.totalmem()) * 100).toFixed(2)}%**)**`
@@ -96,17 +125,40 @@ module.exports = class Stats extends DiscordCommand {
inline: true
});
}
if (args['raw']) {
fields = {
raw: true,
content: [
[ 'Key', 'Value' ],
[ 'Shards [Current / Total]', `${msg.channel.guild.shard.id} / ${this.bot.shards.size}` ],
[ 'Cache [Users / Guilds]', `${this.bot.cache.get('users').length || 0} / ${this.bot.cache.get('guilds').length || 0}`],
[ 'Channels', Object.keys(this.bot.channelGuildMap).length ],
[ 'Guilds', this.bot.guilds.size ],
[ 'Users', this.bot.users.size ],
[ '', '' ],
[ 'OS', `${platform.platform} ${platform.release} (${platform.arch})` ],
[ 'Uptime', moment.duration(this.bot.uptime).format('YYYY[y] MM[M] DD[d] HH[h] mm[m] ss[s]') ],
[ 'OS Uptime', moment.duration(os.uptime() * 1000).format('YYYY[y] MM[M] DD[d] HH[h] mm[m] ss[s]') ],
[ 'User-Agent', this.bot.ua ],
[ 'Memory Usage', `${this.formatBytes(process.memoryUsage().heapUsed)} / ${this.formatBytes(os.totalmem())} (${((process.memoryUsage().heapUsed / os.totalmem()) * 100).toFixed(2)}%)` ],
[ 'Process Hash', process.hash ],
[ 'Load average', os.loadavg().map(v => v.toFixed(2)).join(' / ') ]
]
};
}
msg.channel.createMessage({
content: '',
embed: {
color : this.bot.col['info']['stats'],
fields : fields,
thumbnail: { url: !args['no-thumb'] ? 'attachment://thumb.png' : '' }
}
},
this.thumb && !args['no-thumb'] ? { file: this.thumb, name: 'thumb.png' } : '');
msg.channel.createMessage(
fields.raw ? `\`\`\`${table(fields.content, this.mutable.TABLE_CONFIG)}\`\`\`` :
{
content: '',
embed: {
color : this.bot.col['info']['stats'],
fields : fields,
thumbnail: { url: !args['no-thumb'] ? 'attachment://thumb.png' : '' }
}
},
this.thumb && !fields.raw && !args['no-thumb'] ? { file: this.thumb, name: 'thumb.png' } : '');
message.delete();
}

View File

@@ -31,7 +31,7 @@ module.exports = class TagAdd extends DiscordCommand {
creation: new Date(),
history: [
`TAG_CREATE:${msg.author.id}@${m(new Date()).format('DD-MM-YYYY')}`
`TAG_CREATE:${msg.author.id}@${Date.now()}`
],
author : {
id : msg.author.id,
@@ -82,13 +82,12 @@ module.exports = class TagAdd extends DiscordCommand {
} finally {
let entry = await this.bot.m.connection.collection('dTags').findOne({ name: tag.name, 'author.guild': msg.channel.guild.id });
if (entry !== null || this.bot.cmds.filter((v) => v.extData.name === tag.name || v.extData.aliases.includes(tag.name)).length > 0) {
return msg.channel.createMessage(this._localize(msg.author.locale.tags.add.invalid));
}
entry = new this.bot.schema.tag(tag);
await entry.save();
msg.channel.createMessage(this._localize(msg.author.locale.tags.add.success, { name: tag.name.replace(/`/g, '`\u200b') }));
msg.channel.createMessage(this._localize(msg.author.locale.tags.add.success, { name: this.bot.util.escapeMarkdown(tag.name) }));
}
}

View File

@@ -41,7 +41,7 @@ module.exports = class TagDel extends DiscordCommand {
mess.delete().catch(() => { return; });
}
msg.channel.createMessage(this._localize(msg.author.locale.tags.delete.done, { name: tag.name.replace(/`/g, '`\u200b') }));
msg.channel.createMessage(this._localize(msg.author.locale.tags.delete.done, { name: this.bot.util.escapeMarkdown(tag.name) }));
} else {
if (mess) {
return mess.edit(this._localize(msg.author.locale.cancelled));

View File

@@ -0,0 +1,63 @@
const { DiscordCommand } = require('../../../core');
const moment = require('moment');
module.exports = class TagInfo extends DiscordCommand {
constructor(bot) {
super(bot, {
name : 'tag-info',
syntax : 'tag-info <...tag:str>',
aliases : [],
argument : [ '<...tag:str>' ],
description : 'Info about a tag',
hidden : false,
enabled : true,
cooldown : 2500,
category : 'Tags',
ownerOnly : false,
guildOnly : true,
permissions : []
});
this.mutable = {
MAX_INT32: 2147483647
};
}
async execute(msg, args) {
const tag = await this.bot.m.connection.collection('dTags').findOne({ name: args.join(' '), 'author.guild': msg.channel.guild.id });
if (!tag || tag === null) {
return msg.channel.createMessage(this._localize(msg.author.locale.tags.exec));
}
msg.channel.createMessage({
embed: {
description: this._localize(msg.author.locale.tags.info.join('\n'), { tag: tag })
}
});
}
_localize(msg, extData = {}) {
try {
if (extData) {
if (extData.tag) {
msg = msg
.replace(/\$\[tag:name]/g, this.bot.util.escapeMarkdown(extData.tag.name))
.replace(/\$\[tag:uses]/g, extData.tag.uses)
.replace(/\$\[tag:history]/g, extData.tag.history.splice(0, 10).join('\n'))
.replace(/\$\[tag:creation]/g, moment(new Date(extData.tag.creation)).format('DD[-]MM[-]YYYY HH[:]mm[:]ss'))
.replace(/\$\[tag:creator#tag]/g, this.bot.util.escapeMarkdown(`${extData.tag.author.name}#${extData.tag.author.discrim}`));
}
}
return msg
.replace(/\$\[emoji#0]/g, this.bot.emote('tags', 'info', '0'))
.replace(/\$\[emoji#1]/g, this.bot.emote('tags', 'info', '1'))
.replace(/\$\[emoji#2]/g, this.bot.emote('tags', 'info', '2'))
.replace(/\$\[emoji#3]/g, this.bot.emote('tags', 'info', '3'))
.replace(/\$\[emoji#4]/g, this.bot.emote('tags', 'info', '4'))
.replace(/\$\[emoji#5]/g, this.bot.emote('tags', 'info', '5'));
} catch(ex) {}
}
};

View File

@@ -61,7 +61,7 @@ module.exports = class Tags extends DiscordCommand {
}
const extData = {
tags: Array.list(tags.map((v) => `${v.name.replace(/\*/g, '*\u200b').replace(/`/g, '*\u200b')} (\`${v.uses}\`)`).slice(0, this.mutable.LIMIT), '**,** ', '**and** '),
tags: Array.list(tags.map((v) => `${this.bot.util.escapeMarkdown(v.name)} (\`${v.uses}\`)`).slice(0, this.mutable.LIMIT), '**,** ', '**and** '),
guild: msg.channel.guild.name
};

View File

@@ -85,7 +85,7 @@ if (conf['discord']['enabled']) {
autoreconnect: true
},
ua : `${pkg.displayName}/${pkg.version}/${conf['nightly'] ? 'nightly' : 'distribution'} (https://github.com/PassTheWessel/wump)`,
ua : `${pkg.displayName}/${pkg.version}/${conf['nightly'] ? 'nightly' : 'distribution'}`,
db : mongoose,
pkg : pkg,
colors: col,

View File

@@ -6,42 +6,107 @@ const { strip } = require('../util/colors');
const conf = yaml.safeLoad(fs.readFileSync('application.yml', { encoding: 'utf8' }));
module.exports = class WumpUtil {
/**
* Print `msg` to the console with debug `lvl`
*
* @param {Number} lvl - The logging level
* @param {String} msg - The message to log
* @returns {Boolean} If the message logged or not
*/
static print(lvl = 0, msg = '') {
const log = `tmp/log/${moment(new Date).format('DD[-]MM[-]YYYY')}.log`;
try {
const log = `tmp/log/${moment(new Date).format('DD[-]MM[-]YYYY')}.log`;
fs.mkdir('tmp', 777, (err) => { if (err && err.code !== 'EEXIST') throw err; });
fs.mkdir('tmp/log', 777, (err) => { if (err && err.code !== 'EEXIST') throw err; });
fs.mkdir('tmp', 777, (err) => { if (err && err.code !== 'EEXIST') throw err; });
fs.mkdir('tmp/log', 777, (err) => { if (err && err.code !== 'EEXIST') throw err; });
if (lvl === 1 && conf.debug && conf.debug >= 1) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 2 && conf.debug && conf.debug >= 2) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 3 && conf.debug && conf.debug >= 3) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 4 && conf.debug && conf.debug >= 4) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 0) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
if (lvl === 1 && conf.debug && conf.debug >= 1) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 2 && conf.debug && conf.debug >= 2) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 3 && conf.debug && conf.debug >= 3) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 4 && conf.debug && conf.debug >= 4) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
} else if (lvl === 0) {
console.log(`[${moment(new Date).format( 'HH[:]mm[:]ss' )} / ${process.hash}] ${msg}`);
fs.appendFileSync(log, `[${moment(new Date).format('HH[:]mm[:]ss')} / ${process.hash}] ${strip(msg)}\r\n`);
}
return true;
} catch (ex) {
return false;
}
}
static getPercentage(o, n) {
return (( o - n ) / o) * 100;
/**
* Get the percentage diffrence between `a` and `b`
*
* @param {Number} a - The number to get the percentage of
* @param {Number} b - The number to get the precentage from `a` of
* @returns {Number} - The percentage diffrence
*/
static getPercentage(a, b) {
return ((( a - b ) / a) * 100);
}
static shorten(t = '', m = 2000) {
return t.length > m ? `${t.substr( 0, m - 3 )}...` : t;
/**
* Shorten `text` to `max` characters
*
* @param {String} text - The string to shorten
* @param {Number} max - The max length of the string
*/
static shorten(text = '', max = 2000) {
return text.length > max ? `${text.substr( 0, max - 3 )}...` : text;
}
/**
* Escape all markdown from a string
*
* @param {String} text - The string to escape
* @param {Boolean} onlyCodeBlock - Only escape codeblocks
* @param {Boolean} onlyInlineCode - Only escape inlince code
* @returns {String} - The modified string
*/
static escapeMarkdown(text, onlyCodeBlock = false, onlyInlineCode = false) {
if (onlyCodeBlock) return text.replace(/```/g, '`\u200b``');
if (onlyInlineCode) return text.replace(/\\(`|\\)/g, '$1').replace(/(`|\\)/g, '\\$1');
return text.replace(/\\(\*|_|`|~|\\)/g, '$1').replace(/(\*|_|`|~|\\)/g, '\\$1');
}
/**
* Remove all markdown from a string
*
* @param {String} text - The string to escape
* @param {Boolean} onlyCodeBlock - Only remove codeblocks
* @param {Boolean} onlyInlineCode - Only remove inlince code
* @returns {String} - The modified string
*/
static removeMarkdown(text, onlyCodeBlock = false, onlyInlineCode = false) {
if (onlyCodeBlock) return text.replace(/```/g, '');
if (onlyInlineCode) return text.replace(/\\(`|\\)/g, '').replace(/(`|\\)/g, '');
return text.replace(/\\(\*|_|`|~|\\)/g, '$1').replace(/(\*|_|`|~|\\)/g, '');
}
/**
* Check if `array` includes `needle`
*
* @param {Array} array - The array to check
* @param {*} needle - The item to find in `array`
* @param {*} exact - Exact result or not
*/
contains(array, needle, exact = false) {
for (let _ in array) {
if (exact) {
if (array[_] === needle) return array[_];
} else {
if (array[_].includes(needle)) return array[_];
}
}
}
};

View File

@@ -1485,10 +1485,10 @@ ws@^6.0.0:
dependencies:
async-limiter "~1.0.0"
wumpfetch@^0.0.7:
version "0.0.7"
resolved "https://registry.yarnpkg.com/wumpfetch/-/wumpfetch-0.0.7.tgz#2c113aa35035772c43468da191ae8ac959146ead"
integrity sha512-Q+h9dO/5gNQmmIMK1hdPlNbR03u+OmBLaDWH7KIXyNk3pDuBbWuf60kcQ2ofjt8vjr3MVGUoBj9sroIZKXfHqg==
wumpfetch@^0.0.8:
version "0.0.8"
resolved "https://registry.yarnpkg.com/wumpfetch/-/wumpfetch-0.0.8.tgz#4a3f86a7d966846f4ef68ffe98027b05e36cef56"
integrity sha512-RXwB+JwUTMYWHaKQ0n32CoCLwJVO8jU4BTPC2qqhhgmyKawIdu+Dq/m73aUW4y1AZvM8iBcDcMBELmVgT8bMJA==
xtend@^4.0.0:
version "4.0.1"