Cleaned up guild checks and return statements

This commit is contained in:
WatDuhHekBro 2021-04-06 01:15:17 -05:00
parent 5402883a2f
commit db33203657
14 changed files with 174 additions and 232 deletions

View File

@ -36,18 +36,16 @@ export default new NamedCommand({
} }
}) })
}, },
id: "user",
user: new Command({ user: new Command({
description: "User to give cookie to.", description: "User to give cookie to.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
const sender = author; const sender = author;
const mention: User = args[0]; const mention: User = args[0];
if (mention.id == sender.id) { if (mention.id == sender.id) return channel.send("You can't give yourself cookies!");
channel.send("You can't give yourself cookies!");
return;
}
channel.send( return channel.send(
`:cookie: <@${sender.id}> ${parseVars(random(cookies), { `:cookie: <@${sender.id}> ${parseVars(random(cookies), {
target: mention.toString() target: mention.toString()
})}` })}`

View File

@ -18,6 +18,7 @@ export default new NamedCommand({
shop: ShopCommand, shop: ShopCommand,
monday: MondayCommand monday: MondayCommand
}, },
id: "user",
user: new Command({ user: new Command({
description: "See how much money someone else has by using their user ID or pinging them.", description: "See how much money someone else has by using their user ID or pinging them.",
async run({guild, channel, args}) { async run({guild, channel, args}) {

View File

@ -5,11 +5,8 @@ export default new NamedCommand({
description: "Generates a figlet of your input.", description: "Generates a figlet of your input.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
const input = args.join(" "); const input = args.join(" ");
if (!args[0]) { if (!args[0]) return channel.send("You have to provide input for me to create a figlet!");
channel.send("You have to provide input for me to create a figlet!"); return channel.send(
return;
}
channel.send(
"```" + "```" +
figlet.textSync(`${input}`, { figlet.textSync(`${input}`, {
horizontalLayout: "full" horizontalLayout: "full"

View File

@ -1,13 +1,10 @@
import {Command, NamedCommand} from "../../core"; import {Command, NamedCommand, CHANNEL_TYPE} from "../../core";
export default new NamedCommand({ export default new NamedCommand({
description: "Chooses someone to love.", description: "Chooses someone to love.",
async run({message, channel, guild, author, member, client, args}) { channelType: CHANNEL_TYPE.GUILD,
if (guild) { async run({message, channel, guild, author, client, args}) {
const member = guild.members.cache.random(); const member = guild!.members.cache.random();
channel.send(`I love ${member.user.username}!`); channel.send(`I love ${member.nickname ?? member.user.username}!`);
} else {
channel.send("You must use this command in a guild!");
}
} }
}); });

View File

@ -112,6 +112,7 @@ export const PayCommand = new NamedCommand({
description: "Send money to someone.", description: "Send money to someone.",
usage: "<user> <amount>", usage: "<user> <amount>",
run: "Who are you sending this money to?", run: "Who are you sending this money to?",
id: "user",
user: new Command({ user: new Command({
run: "You need to enter an amount you're sending!", run: "You need to enter an amount you're sending!",
number: new Command({ number: new Command({

View File

@ -45,15 +45,10 @@ export default new NamedCommand({
description: "Image type to send.", description: "Image type to send.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
const arg = args[0]; const arg = args[0];
if (!(arg in endpoints.sfw)) return channel.send("Couldn't find that endpoint!");
if (!(arg in endpoints.sfw)) {
channel.send("Couldn't find that endpoint!");
return;
}
let url = new URL(`https://nekos.life/api/v2${endpoints.sfw[arg]}`); let url = new URL(`https://nekos.life/api/v2${endpoints.sfw[arg]}`);
const content = await getContent(url.toString()); const content = await getContent(url.toString());
channel.send(content.url); return channel.send(content.url);
} }
}) })
}); });

View File

@ -6,11 +6,8 @@ const weather = require("weather-js");
export default new NamedCommand({ export default new NamedCommand({
description: "Shows weather info of specified location.", description: "Shows weather info of specified location.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (args.length == 0) { if (args.length == 0) return channel.send("You need to provide a city.");
channel.send("You need to provide a city."); return weather.find(
return;
}
weather.find(
{ {
search: args.join(" "), search: args.join(" "),
degreeType: "C" degreeType: "C"

View File

@ -1,5 +1,5 @@
import {User} from "discord.js"; import {User} from "discord.js";
import {Command, NamedCommand, getMemberByUsername} from "../../core"; import {Command, NamedCommand, getMemberByUsername, CHANNEL_TYPE} from "../../core";
// Quotes must be used here or the numbers will change // Quotes must be used here or the numbers will change
const registry: {[id: string]: string} = { const registry: {[id: string]: string} = {
@ -46,6 +46,7 @@ export default new NamedCommand({
channel.send("You haven't been added to the registry yet!"); channel.send("You haven't been added to the registry yet!");
} }
}, },
id: "user",
user: new Command({ user: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
const user: User = args[0]; const user: User = args[0];
@ -54,31 +55,28 @@ export default new NamedCommand({
if (id in registry) { if (id in registry) {
channel.send(`\`${user.username}\` - ${registry[id]}`); channel.send(`\`${user.username}\` - ${registry[id]}`);
} else { } else {
channel.send(`\`${user.username}#${user.discriminator}\` hasn't been added to the registry yet!`); channel.send(`\`${user.tag}\` hasn't been added to the registry yet!`);
} }
} }
}), }),
any: new Command({ any: new Command({
async run({message, channel, guild, author, member, client, args}) { channelType: CHANNEL_TYPE.GUILD,
if (guild) { async run({message, channel, guild, author, client, args}) {
const query: string = args.join(" "); const query = args.join(" ") as string;
const member = await getMemberByUsername(guild, query); const member = await getMemberByUsername(guild!, query);
if (member && member.id in registry) { if (member && member.id in registry) {
const id = member.id; const id = member.id;
if (id in registry) { if (id in registry) {
channel.send(`\`${member.user.username}\` - ${registry[member.id]}`); channel.send(`\`${member.nickname ?? member.user.username}\` - ${registry[member.id]}`);
} else {
channel.send(`\`${member.user.username}\` hasn't been added to the registry yet!`);
}
} else { } else {
channel.send(`Couldn't find a user by the name of \`${query}\`!`); channel.send(
`\`${member.nickname ?? member.user.username}\` hasn't been added to the registry yet!`
);
} }
} else { } else {
channel.send( channel.send(`Couldn't find a user by the name of \`${query}\`!`);
"You must run this in a guild! (*If you have the user's ID, you don't have to be in a guild.*)"
);
} }
} }
}) })

View File

@ -1,7 +1,7 @@
import {Command, NamedCommand, botHasPermission, getPermissionLevel, getPermissionName} from "../../core"; import {Command, NamedCommand, botHasPermission, getPermissionLevel, getPermissionName, CHANNEL_TYPE} from "../../core";
import {clean} from "../../lib"; import {clean} from "../../lib";
import {Config, Storage} from "../../structures"; import {Config, Storage} from "../../structures";
import {Permissions} from "discord.js"; import {Permissions, TextChannel} from "discord.js";
import {logs} from "../../modules/globals"; import {logs} from "../../modules/globals";
function getLogBuffer(type: string) { function getLogBuffer(type: string) {
@ -22,8 +22,6 @@ export default new NamedCommand({
description: description:
"An all-in-one command to do admin stuff. You need to be either an admin of the server or one of the bot's mechanics to use this command.", "An all-in-one command to do admin stuff. You need to be either an admin of the server or one of the bot's mechanics to use this command.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (!member)
return channel.send("Couldn't find a member object for you! Did you make sure you used this in a server?");
const permLevel = getPermissionLevel(author, member); const permLevel = getPermissionLevel(author, member);
return channel.send(`${author}, your permission level is \`${getPermissionName(permLevel)}\` (${permLevel}).`); return channel.send(`${author}, your permission level is \`${getPermissionName(permLevel)}\` (${permLevel}).`);
}, },
@ -32,12 +30,13 @@ export default new NamedCommand({
description: "Set different per-guild settings for the bot.", description: "Set different per-guild settings for the bot.",
run: "You have to specify the option you want to set.", run: "You have to specify the option you want to set.",
permission: PERMISSIONS.ADMIN, permission: PERMISSIONS.ADMIN,
channelType: CHANNEL_TYPE.GUILD,
subcommands: { subcommands: {
prefix: new NamedCommand({ prefix: new NamedCommand({
description: "Set a custom prefix for your guild. Removes your custom prefix if none is provided.", description: "Set a custom prefix for your guild. Removes your custom prefix if none is provided.",
usage: "(<prefix>)", usage: "(<prefix>)",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
Storage.getGuild(guild?.id || "N/A").prefix = null; Storage.getGuild(guild!.id).prefix = null;
Storage.save(); Storage.save();
channel.send( channel.send(
`The custom prefix for this guild has been removed. My prefix is now back to \`${Config.prefix}\`.` `The custom prefix for this guild has been removed. My prefix is now back to \`${Config.prefix}\`.`
@ -45,7 +44,7 @@ export default new NamedCommand({
}, },
any: new Command({ any: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
Storage.getGuild(guild?.id || "N/A").prefix = args[0]; Storage.getGuild(guild!.id).prefix = args[0];
Storage.save(); Storage.save();
channel.send(`The custom prefix for this guild is now \`${args[0]}\`.`); channel.send(`The custom prefix for this guild is now \`${args[0]}\`.`);
} }
@ -61,36 +60,24 @@ export default new NamedCommand({
"Sets how welcome messages are displayed for your server. Removes welcome messages if unspecified.", "Sets how welcome messages are displayed for your server. Removes welcome messages if unspecified.",
usage: "`none`/`text`/`graphical`", usage: "`none`/`text`/`graphical`",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { Storage.getGuild(guild!.id).welcomeType = "none";
Storage.getGuild(guild.id).welcomeType = "none"; Storage.save();
Storage.save(); channel.send("Set this server's welcome type to `none`.");
channel.send("Set this server's welcome type to `none`.");
} else {
channel.send("You must use this command in a server.");
}
}, },
// I should probably make this a bit more dynamic... Oh well. // I should probably make this a bit more dynamic... Oh well.
subcommands: { subcommands: {
text: new NamedCommand({ text: new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { Storage.getGuild(guild!.id).welcomeType = "text";
Storage.getGuild(guild.id).welcomeType = "text"; Storage.save();
Storage.save(); channel.send("Set this server's welcome type to `text`.");
channel.send("Set this server's welcome type to `text`.");
} else {
channel.send("You must use this command in a server.");
}
} }
}), }),
graphical: new NamedCommand({ graphical: new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { Storage.getGuild(guild!.id).welcomeType = "graphical";
Storage.getGuild(guild.id).welcomeType = "graphical"; Storage.save();
Storage.save(); channel.send("Set this server's welcome type to `graphical`.");
channel.send("Set this server's welcome type to `graphical`.");
} else {
channel.send("You must use this command in a server.");
}
} }
}) })
} }
@ -99,34 +86,17 @@ export default new NamedCommand({
description: "Sets the welcome channel for your server. Type `#` to reference the channel.", description: "Sets the welcome channel for your server. Type `#` to reference the channel.",
usage: "(<channel mention>)", usage: "(<channel mention>)",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { Storage.getGuild(guild!.id).welcomeChannel = channel.id;
Storage.getGuild(guild.id).welcomeChannel = channel.id; Storage.save();
Storage.save(); channel.send(`Successfully set ${channel} as the welcome channel for this server.`);
channel.send(`Successfully set ${channel} as the welcome channel for this server.`);
} else {
channel.send("You must use this command in a server.");
}
}, },
// If/when channel types come out, this will be the perfect candidate to test it. id: "channel",
any: new Command({ channel: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { const result = args[0] as TextChannel;
const match = args[0].match(/^<#(\d{17,19})>$/); Storage.getGuild(guild!.id).welcomeChannel = result.id;
Storage.save();
if (match) { channel.send(`Successfully set this server's welcome channel to ${result}.`);
Storage.getGuild(guild.id).welcomeChannel = match[1];
Storage.save();
channel.send(
`Successfully set this server's welcome channel to ${match[0]}.`
);
} else {
channel.send(
"You must provide a reference channel. You can do this by typing `#` then searching for the proper channel."
);
}
} else {
channel.send("You must use this command in a server.");
}
} }
}) })
}), }),
@ -135,24 +105,16 @@ export default new NamedCommand({
"Sets a custom welcome message for your server. Use `%user%` as the placeholder for the user.", "Sets a custom welcome message for your server. Use `%user%` as the placeholder for the user.",
usage: "(<message>)", usage: "(<message>)",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { Storage.getGuild(guild!.id).welcomeMessage = null;
Storage.getGuild(guild.id).welcomeMessage = null; Storage.save();
Storage.save(); channel.send("Reset your server's welcome message to the default.");
channel.send("Reset your server's welcome message to the default.");
} else {
channel.send("You must use this command in a server.");
}
}, },
any: new Command({ any: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { const newMessage = args.join(" ");
const message = args.join(" "); Storage.getGuild(guild!.id).welcomeMessage = newMessage;
Storage.getGuild(guild.id).welcomeMessage = message; Storage.save();
Storage.save(); channel.send(`Set your server's welcome message to \`${newMessage}\`.`);
channel.send(`Set your server's welcome message to \`${message}\`.`);
} else {
channel.send("You must use this command in a server.");
}
} }
}) })
}) })
@ -202,9 +164,10 @@ export default new NamedCommand({
purge: new NamedCommand({ purge: new NamedCommand({
description: "Purges the bot's own messages.", description: "Purges the bot's own messages.",
permission: PERMISSIONS.BOT_SUPPORT, permission: PERMISSIONS.BOT_SUPPORT,
channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
// It's probably better to go through the bot's own messages instead of calling bulkDelete which requires MANAGE_MESSAGES. // It's probably better to go through the bot's own messages instead of calling bulkDelete which requires MANAGE_MESSAGES.
if (botHasPermission(guild, Permissions.FLAGS.MANAGE_MESSAGES) && channel.type !== "dm") { if (botHasPermission(guild, Permissions.FLAGS.MANAGE_MESSAGES)) {
message.delete(); message.delete();
const msgs = await channel.messages.fetch({ const msgs = await channel.messages.fetch({
limit: 100 limit: 100
@ -216,7 +179,7 @@ export default new NamedCommand({
timeout: 5000 timeout: 5000
}) })
); );
await channel.bulkDelete(travMessages); await (channel as TextChannel).bulkDelete(travMessages);
} else { } else {
channel.send( channel.send(
"This command must be executed in a guild where I have the `MANAGE_MESSAGES` permission." "This command must be executed in a guild where I have the `MANAGE_MESSAGES` permission."
@ -227,17 +190,16 @@ export default new NamedCommand({
clear: new NamedCommand({ clear: new NamedCommand({
description: "Clears a given amount of messages.", description: "Clears a given amount of messages.",
usage: "<amount>", usage: "<amount>",
channelType: CHANNEL_TYPE.GUILD,
run: "A number was not provided.", run: "A number was not provided.",
number: new Command({ number: new Command({
description: "Amount of messages to delete.", description: "Amount of messages to delete.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (channel.type === "dm") return channel.send("Can't clear messages in the DMs!");
message.delete(); message.delete();
const fetched = await channel.messages.fetch({ const fetched = await channel.messages.fetch({
limit: args[0] limit: args[0]
}); });
await channel.bulkDelete(fetched); return await (channel as TextChannel).bulkDelete(fetched);
return;
} }
}) })
}), }),
@ -261,9 +223,10 @@ export default new NamedCommand({
nick: new NamedCommand({ nick: new NamedCommand({
description: "Change the bot's nickname.", description: "Change the bot's nickname.",
permission: PERMISSIONS.BOT_SUPPORT, permission: PERMISSIONS.BOT_SUPPORT,
channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
const nickName = args.join(" "); const nickName = args.join(" ");
await guild?.me?.setNickname(nickName); await guild!.me?.setNickname(nickName);
if (botHasPermission(guild, Permissions.FLAGS.MANAGE_MESSAGES)) message.delete({timeout: 5000}); if (botHasPermission(guild, Permissions.FLAGS.MANAGE_MESSAGES)) message.delete({timeout: 5000});
channel.send(`Nickname set to \`${nickName}\``).then((m) => m.delete({timeout: 5000})); channel.send(`Nickname set to \`${nickName}\``).then((m) => m.delete({timeout: 5000}));
} }
@ -308,15 +271,20 @@ export default new NamedCommand({
syslog: new NamedCommand({ syslog: new NamedCommand({
description: "Sets up the current channel to receive system logs.", description: "Sets up the current channel to receive system logs.",
permission: PERMISSIONS.BOT_ADMIN, permission: PERMISSIONS.BOT_ADMIN,
channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { Config.systemLogsChannel = channel.id;
Config.systemLogsChannel = channel.id; Config.save();
channel.send(`Successfully set ${channel} as the system logs channel.`);
},
channel: new Command({
async run({message, channel, guild, author, member, client, args}) {
const targetChannel = args[0] as TextChannel;
Config.systemLogsChannel = targetChannel.id;
Config.save(); Config.save();
channel.send(`Successfully set ${channel} as the system logs channel.`); channel.send(`Successfully set ${targetChannel} as the system logs channel.`);
} else {
channel.send("DM system log channels aren't supported.");
} }
} })
}) })
} }
}); });

View File

@ -5,22 +5,18 @@ import {MessageEmbed} from "discord.js";
export default new NamedCommand({ export default new NamedCommand({
description: "Calculates a specified math expression.", description: "Calculates a specified math expression.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (!args[0]) { if (!args[0]) return channel.send("Please provide a calculation.");
channel.send("Please provide a calculation.");
return;
}
let resp; let resp;
try { try {
resp = math.evaluate(args.join(" ")); resp = math.evaluate(args.join(" "));
} catch (e) { } catch (e) {
channel.send("Please provide a *valid* calculation."); return channel.send("Please provide a *valid* calculation.");
return;
} }
const embed = new MessageEmbed() const embed = new MessageEmbed()
.setColor(0xffffff) .setColor(0xffffff)
.setTitle("Math Calculation") .setTitle("Math Calculation")
.addField("Input", `\`\`\`js\n${args.join("")}\`\`\``) .addField("Input", `\`\`\`js\n${args.join("")}\`\`\``)
.addField("Output", `\`\`\`js\n${resp}\`\`\``); .addField("Output", `\`\`\`js\n${resp}\`\`\``);
channel.send(embed); return channel.send(embed);
} }
}); });

View File

@ -6,24 +6,14 @@ export default new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
const voiceChannel = message.member?.voice.channel; const voiceChannel = message.member?.voice.channel;
if (!voiceChannel) { if (!voiceChannel) return channel.send("You are not in a voice channel.");
channel.send("You are not in a voice channel."); if (!voiceChannel.guild.me?.hasPermission("MANAGE_CHANNELS"))
return; return channel.send("I am lacking the required permissions to perform this action.");
} if (args.length === 0) return channel.send("Please provide a new voice channel name.");
if (!voiceChannel.guild.me?.hasPermission("MANAGE_CHANNELS")) {
channel.send("I am lacking the required permissions to perform this action.");
return;
}
if (args.length === 0) {
channel.send("Please provide a new voice channel name.");
return;
}
const prevName = voiceChannel.name; const prevName = voiceChannel.name;
const newName = args.join(" "); const newName = args.join(" ");
await voiceChannel.setName(newName); await voiceChannel.setName(newName);
await channel.send(`Changed channel name from "${prevName}" to "${newName}".`); return await channel.send(`Changed channel name from "${prevName}" to "${newName}".`);
} }
}); });

View File

@ -1,14 +1,16 @@
import {MessageEmbed, version as djsversion, Guild} from "discord.js"; import {MessageEmbed, version as djsversion, Guild, User, GuildMember} from "discord.js";
import ms from "ms"; import ms from "ms";
import os from "os"; import os from "os";
import {Command, NamedCommand, getMemberByUsername} from "../../core"; import {Command, NamedCommand, getMemberByUsername, CHANNEL_TYPE} from "../../core";
import {formatBytes, trimArray} from "../../lib"; import {formatBytes, trimArray} from "../../lib";
import {verificationLevels, filterLevels, regions} from "../../defs/info"; import {verificationLevels, filterLevels, regions} from "../../defs/info";
import moment, {utc} from "moment"; import moment, {utc} from "moment";
export default new NamedCommand({ export default new NamedCommand({
description: "Command to provide all sorts of info about the current server, a user, etc.", description: "Command to provide all sorts of info about the current server, a user, etc.",
run: "Please provide an argument.\nFor help, run `%prefix%help info`.", async run({message, channel, guild, author, member, client, args}) {
channel.send(await getUserInfo(author, member));
},
subcommands: { subcommands: {
avatar: new NamedCommand({ avatar: new NamedCommand({
description: "Shows your own, or another user's avatar.", description: "Shows your own, or another user's avatar.",
@ -16,6 +18,7 @@ export default new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
channel.send(author.displayAvatarURL({dynamic: true, size: 2048})); channel.send(author.displayAvatarURL({dynamic: true, size: 2048}));
}, },
id: "user",
user: new Command({ user: new Command({
description: "Shows your own, or another user's avatar.", description: "Shows your own, or another user's avatar.",
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
@ -29,21 +32,20 @@ export default new NamedCommand({
}), }),
any: new Command({ any: new Command({
description: "Shows another user's avatar by searching their name", description: "Shows another user's avatar by searching their name",
async run({message, channel, guild, author, member, client, args}) { channelType: CHANNEL_TYPE.GUILD,
if (guild) { async run({message, channel, guild, author, client, args}) {
const name = args.join(" "); const name = args.join(" ");
const member = await getMemberByUsername(guild, name); const member = await getMemberByUsername(guild!, name);
if (member) { if (member) {
channel.send( channel.send(
member.user.displayAvatarURL({ member.user.displayAvatarURL({
dynamic: true, dynamic: true,
size: 2048 size: 2048
}) })
); );
} else { } else {
channel.send(`No user found by the name \`${name}\`!`); channel.send(`No user found by the name \`${name}\`!`);
}
} }
} }
}) })
@ -92,12 +94,9 @@ export default new NamedCommand({
guild: new NamedCommand({ guild: new NamedCommand({
description: "Displays info about the current guild or another guild.", description: "Displays info about the current guild or another guild.",
usage: "(<guild name>/<guild ID>)", usage: "(<guild name>/<guild ID>)",
channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (guild) { channel.send(await getGuildInfo(guild!, guild));
channel.send(await getGuildInfo(guild, guild));
} else {
channel.send("Please execute this command in a guild.");
}
}, },
any: new Command({ any: new Command({
description: "Display info about a guild by finding its name or ID.", description: "Display info about a guild by finding its name or ID.",
@ -105,19 +104,21 @@ export default new NamedCommand({
// If a guild ID is provided (avoid the "number" subcommand because of inaccuracies), search for that guild // If a guild ID is provided (avoid the "number" subcommand because of inaccuracies), search for that guild
if (args.length === 1 && /^\d{17,19}$/.test(args[0])) { if (args.length === 1 && /^\d{17,19}$/.test(args[0])) {
const id = args[0]; const id = args[0];
const guild = client.guilds.cache.get(id); const targetGuild = client.guilds.cache.get(id);
if (guild) { if (targetGuild) {
channel.send(await getGuildInfo(guild, guild)); channel.send(await getGuildInfo(targetGuild, guild));
} else { } else {
channel.send(`None of the servers I'm in matches the guild ID \`${id}\`!`); channel.send(`None of the servers I'm in matches the guild ID \`${id}\`!`);
} }
} else { } else {
const query: string = args.join(" ").toLowerCase(); const query: string = args.join(" ").toLowerCase();
const guild = client.guilds.cache.find((guild) => guild.name.toLowerCase().includes(query)); const targetGuild = client.guilds.cache.find((guild) =>
guild.name.toLowerCase().includes(query)
);
if (guild) { if (targetGuild) {
channel.send(await getGuildInfo(guild, guild)); channel.send(await getGuildInfo(targetGuild, guild));
} else { } else {
channel.send(`None of the servers I'm in matches the query \`${query}\`!`); channel.send(`None of the servers I'm in matches the query \`${query}\`!`);
} }
@ -126,55 +127,62 @@ export default new NamedCommand({
}) })
}) })
}, },
id: "user",
user: new Command({ user: new Command({
description: "Displays info about mentioned user.", description: "Displays info about mentioned user.",
async run({message, channel, guild, author, client, args}) { async run({message, channel, guild, author, client, args}) {
const user = args[0] as User;
// Transforms the User object into a GuildMember object of the current guild. // Transforms the User object into a GuildMember object of the current guild.
const member = await guild?.members.fetch(args[0]); const member = guild?.members.resolve(args[0]);
channel.send(await getUserInfo(user, member));
if (!member) {
channel.send(
"No member object was found by that user! Are you sure you used this command in a server?"
);
return;
}
const roles = member.roles.cache
.sort((a: {position: number}, b: {position: number}) => b.position - a.position)
.map((role: {toString: () => any}) => role.toString())
.slice(0, -1);
const userFlags = (await member.user.fetchFlags()).toArray();
const embed = new MessageEmbed()
.setThumbnail(member.user.displayAvatarURL({dynamic: true, size: 512}))
.setColor(member.displayHexColor || "BLUE")
.addField("User", [
`** Username:** ${member.user.username}`,
`** Discriminator:** ${member.user.discriminator}`,
`** ID:** ${member.id}`,
`** Flags:** ${userFlags.length ? userFlags.join(", ") : "None"}`,
`** Avatar:** [Link to avatar](${member.user.displayAvatarURL({
dynamic: true
})})`,
`** Time Created:** ${moment(member.user.createdTimestamp).format("LT")} ${moment(
member.user.createdTimestamp
).format("LL")} ${moment(member.user.createdTimestamp).fromNow()}`,
`** Status:** ${member.user.presence.status}`,
`** Game:** ${member.user.presence.activities || "Not playing a game."}`
])
.addField("Member", [
`** Highest Role:** ${member.roles.highest.id === guild?.id ? "None" : member.roles.highest.name}`,
`** Server Join Date:** ${moment(member.joinedAt).format("LL LTS")}`,
`** Hoist Role:** ${member.roles.hoist ? member.roles.hoist.name : "None"}`,
`** Roles:** [${roles.length}]: ${
roles.length == 0 ? "None" : roles.length <= 10 ? roles.join(", ") : trimArray(roles).join(", ")
}`
]);
channel.send(embed);
} }
}) })
}); });
async function getUserInfo(user: User, member: GuildMember | null | undefined): Promise<MessageEmbed> {
const userFlags = (await user.fetchFlags()).toArray();
const embed = new MessageEmbed()
.setThumbnail(user.displayAvatarURL({dynamic: true, size: 512}))
.setColor("BLUE")
.addField("User", [
`** Username:** ${user.username}`,
`** Discriminator:** ${user.discriminator}`,
`** ID:** ${user.id}`,
`** Flags:** ${userFlags.length ? userFlags.join(", ") : "None"}`,
`** Avatar:** [Link to avatar](${user.displayAvatarURL({
dynamic: true
})})`,
`** Time Created:** ${moment(user.createdTimestamp).format("LT")} ${moment(user.createdTimestamp).format(
"LL"
)} ${moment(user.createdTimestamp).fromNow()}`,
`** Status:** ${user.presence.status}`,
`** Game:** ${user.presence.activities || "Not playing a game."}`
]);
if (member) {
const roles = member.roles.cache
.sort((a: {position: number}, b: {position: number}) => b.position - a.position)
.map((role: {toString: () => any}) => role.toString())
.slice(0, -1);
embed
.setColor(member.displayHexColor)
.addField("Member", [
`** Highest Role:** ${
member.roles.highest.id === member.guild.id ? "None" : member.roles.highest.name
}`,
`** Server Join Date:** ${moment(member.joinedAt).format("LL LTS")}`,
`** Hoist Role:** ${member.roles.hoist ? member.roles.hoist.name : "None"}`,
`** Roles:** [${roles.length}]: ${
roles.length == 0 ? "None" : roles.length <= 10 ? roles.join(", ") : trimArray(roles).join(", ")
}`
]);
}
return embed;
}
async function getGuildInfo(guild: Guild, currentGuild: Guild | null) { async function getGuildInfo(guild: Guild, currentGuild: Guild | null) {
const members = await guild.members.fetch({ const members = await guild.members.fetch({
withPresences: true, withPresences: true,

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand} from "../../core"; import {Command, NamedCommand, CHANNEL_TYPE} from "../../core";
import {pluralise} from "../../lib"; import {pluralise} from "../../lib";
import moment from "moment"; import moment from "moment";
import {Collection, TextChannel} from "discord.js"; import {Collection, TextChannel} from "discord.js";
@ -8,26 +8,21 @@ const lastUsedTimestamps: {[id: string]: number} = {};
export default new NamedCommand({ export default new NamedCommand({
description: description:
"Scans all text channels in the current guild and returns the number of times each emoji specific to the guild has been used. Has a cooldown of 24 hours per guild.", "Scans all text channels in the current guild and returns the number of times each emoji specific to the guild has been used. Has a cooldown of 24 hours per guild.",
channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({message, channel, guild, author, member, client, args}) {
if (!guild) {
channel.send(`You must use this command on a server!`);
return;
}
// Test if the command is on cooldown. This isn't the strictest cooldown possible, because in the event that the bot crashes, the cooldown will be reset. But for all intends and purposes, it's a good enough cooldown. It's a per-server cooldown. // Test if the command is on cooldown. This isn't the strictest cooldown possible, because in the event that the bot crashes, the cooldown will be reset. But for all intends and purposes, it's a good enough cooldown. It's a per-server cooldown.
const startTime = Date.now(); const startTime = Date.now();
const cooldown = 86400000; // 24 hours const cooldown = 86400000; // 24 hours
const lastUsedTimestamp = lastUsedTimestamps[guild.id] ?? 0; const lastUsedTimestamp = lastUsedTimestamps[guild!.id] ?? 0;
const difference = startTime - lastUsedTimestamp; const difference = startTime - lastUsedTimestamp;
const howLong = moment(startTime).to(lastUsedTimestamp + cooldown); const howLong = moment(startTime).to(lastUsedTimestamp + cooldown);
// If it's been less than an hour since the command was last used, prevent it from executing. // If it's been less than an hour since the command was last used, prevent it from executing.
if (difference < cooldown) { if (difference < cooldown)
channel.send( return channel.send(
`This command requires a day to cooldown. You'll be able to activate this command ${howLong}.` `This command requires a day to cooldown. You'll be able to activate this command ${howLong}.`
); );
return; else lastUsedTimestamps[guild!.id] = startTime;
} else lastUsedTimestamps[guild.id] = startTime;
const stats: { const stats: {
[id: string]: { [id: string]: {
@ -39,7 +34,7 @@ export default new NamedCommand({
} = {}; } = {};
let totalUserEmoteUsage = 0; let totalUserEmoteUsage = 0;
// IMPORTANT: You MUST check if the bot actually has access to the channel in the first place. It will get the list of all channels, but that doesn't mean it has access to every channel. Without this, it'll require admin access and throw an annoying unhelpful DiscordAPIError: Missing Access otherwise. // IMPORTANT: You MUST check if the bot actually has access to the channel in the first place. It will get the list of all channels, but that doesn't mean it has access to every channel. Without this, it'll require admin access and throw an annoying unhelpful DiscordAPIError: Missing Access otherwise.
const allTextChannelsInCurrentGuild = guild.channels.cache.filter( const allTextChannelsInCurrentGuild = guild!.channels.cache.filter(
(channel) => channel.type === "text" && channel.viewable (channel) => channel.type === "text" && channel.viewable
) as Collection<string, TextChannel>; ) as Collection<string, TextChannel>;
let messagesSearched = 0; let messagesSearched = 0;
@ -52,7 +47,7 @@ export default new NamedCommand({
// Initialize the emote stats object with every emote in the current guild. // Initialize the emote stats object with every emote in the current guild.
// The goal here is to cut the need to access guild.emojis.get() which'll make it faster and easier to work with. // The goal here is to cut the need to access guild.emojis.get() which'll make it faster and easier to work with.
for (let emote of guild.emojis.cache.values()) { for (let emote of guild!.emojis.cache.values()) {
// If you don't include the "a" for animated emotes, it'll not only not show up, but also cause all other emotes in the same message to not show up. The emote name is self-correcting but it's better to keep the right value since it'll be used to calculate message lengths that fit. // If you don't include the "a" for animated emotes, it'll not only not show up, but also cause all other emotes in the same message to not show up. The emote name is self-correcting but it's better to keep the right value since it'll be used to calculate message lengths that fit.
stats[emote.id] = { stats[emote.id] = {
name: emote.name, name: emote.name,
@ -186,6 +181,6 @@ export default new NamedCommand({
); );
} }
await channel.send(lines, {split: true}); return await channel.send(lines, {split: true});
} }
}); });

View File

@ -374,6 +374,7 @@ export default new NamedCommand({
run: DST_NOTE_INFO run: DST_NOTE_INFO
}) })
}, },
id: "user",
user: new Command({ user: new Command({
description: "See what time it is for someone else.", description: "See what time it is for someone else.",
async run({channel, args}) { async run({channel, args}) {