Merge pull request #35 from keanuplayz/omnibus

This commit is contained in:
Keanu Timmermans 2021-04-12 09:07:20 +02:00 committed by GitHub
commit 4241f57f46
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
64 changed files with 2136 additions and 1505 deletions

View File

@ -1,4 +1,20 @@
# 3.2.0 - Internal refactor, more subcommand types, and more command type guards (2021-??-??) # 3.2.1
- `vaporwave`: Transforms input into full-width text
- `eco post`: A play on `eco get`
- `admin set prefix <prefix> (<@bot>)`: Allows you to target a bot when setting a prefix if two bots have conflicting prefixes
- `party`: Sets the bot's status to streaming with a certain URL
- `eco award`: Awards users with Mons, only accessible by that person
- `thonk`: A result can now be discarded if the person who called the command reacts with ❌
- `scanemotes forcereset`: Removes the cooldown on `scanemotes`, only accessible by bot support and up
- `urban`: Bug fixes
- Changed `help` to display a paginated embed
- Various changes to core
- Added `guild` subcommand type (only accessible when `id: "guild"`)
- Further reduced `channel.send()` to `send()` because it's used in *every, single, command*
- Added a `RestCommand` type, declaratively states that the following command will do `args.join(" ")`, preventing any other subcommands from being added
- Is no longer lenient to arguments when no proper subcommand fits (now it doesn't silently fail anymore), you now have to explicitly declare a `RestCommand` to get an arbitrary number of arguments
# 3.2.0 - Internal refactor, more subcommand types, and more command type guards (2021-04-09)
- The custom logger changed: `$.log` no longer exists, it's just `console.log`. Now you don't have to do `import $ from "../core/lib"` at the top of every file that uses the custom logger. - The custom logger changed: `$.log` no longer exists, it's just `console.log`. Now you don't have to do `import $ from "../core/lib"` at the top of every file that uses the custom logger.
- Utility functions are no longer attached to the command menu. Stuff like `$.paginate()` and `$(5).pluralise()` instead need to be imported and used as regular functions. - Utility functions are no longer attached to the command menu. Stuff like `$.paginate()` and `$(5).pluralise()` instead need to be imported and used as regular functions.
- The `paginate` function was reworked to reduce the amount of repetition you had to do. - The `paginate` function was reworked to reduce the amount of repetition you had to do.

View File

@ -71,6 +71,10 @@ Boolean subcommand types won't be implemented:
For common use cases, there wouldn't be a need to go accept numbers of different bases. The only time it would be applicable is if there was some sort of base converter command, and even then, it'd be better to just implement custom logic. For common use cases, there wouldn't be a need to go accept numbers of different bases. The only time it would be applicable is if there was some sort of base converter command, and even then, it'd be better to just implement custom logic.
## User Mention + Search by Username Type
While it's a pretty common pattern, it's probably a bit too specific for the `Command` class itself. Instead, this pattern will be comprised of two subcommands: A `user` type and an `any` type.
# The Command Handler # The Command Handler
## The Scope of the Command Handler ## The Scope of the Command Handler

View File

@ -65,6 +65,7 @@ Because versions are assigned to batches of changes rather than single changes (
- `%author%` - A user mention of the person who called the command. - `%author%` - A user mention of the person who called the command.
- `%prefix%` - The prefix of the current guild. - `%prefix%` - The prefix of the current guild.
- `%command%` - The command's execution path up to the current subcommand.
# Utility Functions # Utility Functions
@ -72,28 +73,33 @@ Because versions are assigned to batches of changes rather than single changes (
`paginate()` `paginate()`
```ts ```ts
const pages = ['one', 'two', 'three']; const pages = ["one", "two", "three"];
const msg = await channel.send(pages[0]);
paginate(msg, author.id, pages.length, (page) => { paginate(send, author.id, pages.length, page => {
msg.edit(pages[page]); return {content: pages[page]};
}); });
``` ```
`prompt()` `poll()`
```ts ```ts
const msg = await channel.send('Are you sure you want to delete this?'); const results = await poll(await send("Do you agree with this decision?"), ["✅", "❌"]);
results["✅"]; // number
prompt(msg, author.id, () => { results["❌"]; // number
//...
});
``` ```
`callMemberByUsername()` `confirm()`
```ts ```ts
callMemberByUsername(message, args.join(" "), (member) => { const result = await confirm(await send("Are you sure you want to delete this?"), author.id); // boolean | null
channel.send(`Your nickname is ${member.nickname}.`); ```
});
`askMultipleChoice()`
```ts
const result = await askMultipleChoice(await send("Which of the following numbers is your favorite?"), author.id, 4, 10000); // number (0 to 3) | null
```
`askForReply()`
```ts
const reply = await askForReply(await send("What is your favorite thing to do?"), author.id, 10000); // Message | null
``` ```
## [src/lib](../src/lib.ts) - General utility functions ## [src/lib](../src/lib.ts) - General utility functions

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "travebot", "name": "travebot",
"version": "3.2.0", "version": "3.2.1",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "travebot", "name": "travebot",
"version": "3.2.0", "version": "3.2.1",
"hasInstallScript": true, "hasInstallScript": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {

View File

@ -1,6 +1,6 @@
{ {
"name": "travebot", "name": "travebot",
"version": "3.2.0", "version": "3.2.1",
"description": "TravBot Discord bot.", "description": "TravBot Discord bot.",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {

View File

@ -26,14 +26,13 @@ const responses = [
export default new NamedCommand({ export default new NamedCommand({
description: "Answers your question in an 8-ball manner.", description: "Answers your question in an 8-ball manner.",
endpoint: false,
usage: "<question>", usage: "<question>",
run: "Please provide a question.", run: "Please provide a question.",
any: new Command({ any: new Command({
description: "Question to ask the 8-ball.", description: "Question to ask the 8-ball.",
async run({message, channel, guild, author, member, client, args}) { async run({send, message}) {
const sender = message.author; const sender = message.author;
channel.send(`${random(responses)} <@${sender.id}>`); send(`${random(responses)} <@${sender.id}>`);
} }
}) })
}); });

View File

@ -31,21 +31,21 @@ export default new NamedCommand({
run: ":cookie: Here's a cookie!", run: ":cookie: Here's a cookie!",
subcommands: { subcommands: {
all: new NamedCommand({ all: new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({send, author}) {
channel.send(`${author} gave everybody a cookie!`); send(`${author} gave everybody a cookie!`);
} }
}) })
}, },
id: "user", 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({send, author, args}) {
const sender = author; const sender = author;
const mention: User = args[0]; const mention: User = args[0];
if (mention.id == sender.id) return channel.send("You can't give yourself cookies!"); if (mention.id == sender.id) return send("You can't give yourself cookies!");
return channel.send( return send(
`:cookie: <@${sender.id}> ${parseVars(random(cookies), { `:cookie: <@${sender.id}> ${parseVars(random(cookies), {
target: mention.toString() target: mention.toString()
})}` })}`

View File

@ -1,14 +1,14 @@
import {Command, NamedCommand, callMemberByUsername} from "../../core"; import {Command, NamedCommand, getMemberByName, RestCommand} from "../../core";
import {isAuthorized, getMoneyEmbed} from "./modules/eco-utils"; import {isAuthorized, getMoneyEmbed} from "./modules/eco-utils";
import {DailyCommand, PayCommand, GuildCommand, LeaderboardCommand} from "./modules/eco-core"; import {DailyCommand, PayCommand, GuildCommand, LeaderboardCommand} from "./modules/eco-core";
import {BuyCommand, ShopCommand} from "./modules/eco-shop"; import {BuyCommand, ShopCommand} from "./modules/eco-shop";
import {MondayCommand} from "./modules/eco-extras"; import {MondayCommand, AwardCommand} from "./modules/eco-extras";
import {BetCommand} from "./modules/eco-bet"; import {BetCommand} from "./modules/eco-bet";
export default new NamedCommand({ export default new NamedCommand({
description: "Economy command for Monika.", description: "Economy command for Monika.",
async run({guild, channel, author}) { async run({send, guild, channel, author}) {
if (isAuthorized(guild, channel)) channel.send(getMoneyEmbed(author)); if (isAuthorized(guild, channel)) send(getMoneyEmbed(author));
}, },
subcommands: { subcommands: {
daily: DailyCommand, daily: DailyCommand,
@ -18,22 +18,28 @@ export default new NamedCommand({
buy: BuyCommand, buy: BuyCommand,
shop: ShopCommand, shop: ShopCommand,
monday: MondayCommand, monday: MondayCommand,
bet: BetCommand bet: BetCommand,
award: AwardCommand,
post: new NamedCommand({
description: "A play on `eco get`",
run: "`405 Method Not Allowed`"
})
}, },
id: "user", 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({send, guild, channel, args}) {
if (isAuthorized(guild, channel)) channel.send(getMoneyEmbed(args[0])); if (isAuthorized(guild, channel)) send(getMoneyEmbed(args[0]));
} }
}), }),
any: new Command({ any: new RestCommand({
description: "See how much money someone else has by using their username.", description: "See how much money someone else has by using their username.",
async run({guild, channel, args, message}) { async run({send, guild, channel, combined}) {
if (isAuthorized(guild, channel)) if (isAuthorized(guild, channel)) {
callMemberByUsername(message, args.join(" "), (member) => { const member = await getMemberByName(guild!, combined);
channel.send(getMoneyEmbed(member.user)); if (typeof member !== "string") send(getMoneyEmbed(member.user));
}); else send(member);
}
} }
}) })
}); });

View File

@ -1,17 +1,19 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import figlet from "figlet"; import figlet from "figlet";
export default new NamedCommand({ 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}) { run: "You have to provide input for me to create a figlet!",
const input = args.join(" "); any: new RestCommand({
if (!args[0]) return channel.send("You have to provide input for me to create a figlet!"); async run({send, combined}) {
return channel.send( return send(
"```" + figlet.textSync(combined, {
figlet.textSync(`${input}`, {
horizontalLayout: "full" horizontalLayout: "full"
}) + }),
"```" {
); code: true
} }
);
}
})
}); });

View File

@ -1,11 +1,11 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand} from "../../core";
export default new NamedCommand({ export default new NamedCommand({
description: "Insult TravBot! >:D", description: "Insult TravBot! >:D",
async run({message, channel, guild, author, member, client, args}) { async run({send, channel, author}) {
channel.startTyping(); channel.startTyping();
setTimeout(() => { setTimeout(() => {
channel.send( send(
`${author} What the fuck did you just fucking say about me, you little bitch? I'll have you know I graduated top of my class in the Navy Seals, and I've been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills. I am trained in gorilla warfare and I'm the top sniper in the entire US armed forces. You are nothing to me but just another target. I will wipe you the fuck out with precision the likes of which has never been seen before on this Earth, mark my fucking words. You think you can get away with saying that shit to me over the Internet? Think again, fucker. As we speak I am contacting my secret network of spies across the USA and your IP is being traced right now so you better prepare for the storm, maggot. The storm that wipes out the pathetic little thing you call your life. You're fucking dead, kid. I can be anywhere, anytime, and I can kill you in over seven hundred ways, and that's just with my bare hands. Not only am I extensively trained in unarmed combat, but I have access to the entire arsenal of the United States Marine Corps and I will use it to its full extent to wipe your miserable ass off the face of the continent, you little shit. If only you could have known what unholy retribution your little "clever" comment was about to bring down upon you, maybe you would have held your fucking tongue. But you couldn't, you didn't, and now you're paying the price, you goddamn idiot. I will shit fury all over you and you will drown in it. You're fucking dead, kiddo.` `${author} What the fuck did you just fucking say about me, you little bitch? I'll have you know I graduated top of my class in the Navy Seals, and I've been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills. I am trained in gorilla warfare and I'm the top sniper in the entire US armed forces. You are nothing to me but just another target. I will wipe you the fuck out with precision the likes of which has never been seen before on this Earth, mark my fucking words. You think you can get away with saying that shit to me over the Internet? Think again, fucker. As we speak I am contacting my secret network of spies across the USA and your IP is being traced right now so you better prepare for the storm, maggot. The storm that wipes out the pathetic little thing you call your life. You're fucking dead, kid. I can be anywhere, anytime, and I can kill you in over seven hundred ways, and that's just with my bare hands. Not only am I extensively trained in unarmed combat, but I have access to the entire arsenal of the United States Marine Corps and I will use it to its full extent to wipe your miserable ass off the face of the continent, you little shit. If only you could have known what unholy retribution your little "clever" comment was about to bring down upon you, maybe you would have held your fucking tongue. But you couldn't, you didn't, and now you're paying the price, you goddamn idiot. I will shit fury all over you and you will drown in it. You're fucking dead, kiddo.`
); );
channel.stopTyping(); channel.stopTyping();

View File

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

View File

@ -1,7 +1,7 @@
import {Command, NamedCommand, askYesOrNo} from "../../../core"; import {Command, NamedCommand, confirm, poll} from "../../../core";
import {pluralise} from "../../../lib"; import {pluralise} from "../../../lib";
import {Storage} from "../../../structures"; import {Storage} from "../../../structures";
import {isAuthorized, getMoneyEmbed, getSendEmbed, ECO_EMBED_COLOR} from "./eco-utils"; import {isAuthorized, getMoneyEmbed} from "./eco-utils";
import {User} from "discord.js"; import {User} from "discord.js";
export const BetCommand = new NamedCommand({ export const BetCommand = new NamedCommand({
@ -11,21 +11,21 @@ export const BetCommand = new NamedCommand({
user: new Command({ user: new Command({
description: "User to bet with.", description: "User to bet with.",
// handles missing amount argument // handles missing amount argument
async run({args, author, channel, guild}) { async run({send, args, author, channel, guild}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const target = args[0]; const target = args[0];
// handle invalid target // handle invalid target
if (target.id == author.id) return channel.send("You can't bet Mons with yourself!"); if (target.id == author.id) return send("You can't bet Mons with yourself!");
else if (target.bot && process.argv[2] !== "dev") return channel.send("You can't bet Mons with a bot!"); else if (target.bot && process.argv[2] !== "dev") return send("You can't bet Mons with a bot!");
return channel.send("How much are you betting?"); return send("How much are you betting?");
} else return; } else return;
}, },
number: new Command({ number: new Command({
description: "Amount of Mons to bet.", description: "Amount of Mons to bet.",
// handles missing duration argument // handles missing duration argument
async run({args, author, channel, guild}) { async run({send, args, author, channel, guild}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const sender = Storage.getUser(author.id); const sender = Storage.getUser(author.id);
const target = args[0] as User; const target = args[0] as User;
@ -33,23 +33,22 @@ export const BetCommand = new NamedCommand({
const amount = Math.floor(args[1]); const amount = Math.floor(args[1]);
// handle invalid target // handle invalid target
if (target.id == author.id) return channel.send("You can't bet Mons with yourself!"); if (target.id == author.id) return send("You can't bet Mons with yourself!");
else if (target.bot && process.argv[2] !== "dev") else if (target.bot && process.argv[2] !== "dev") return send("You can't bet Mons with a bot!");
return channel.send("You can't bet Mons with a bot!");
// handle invalid amount // handle invalid amount
if (amount <= 0) return channel.send("You must bet at least one Mon!"); if (amount <= 0) return send("You must bet at least one Mon!");
else if (sender.money < amount) else if (sender.money < amount)
return channel.send("You don't have enough Mons for that.", getMoneyEmbed(author)); return send("You don't have enough Mons for that.", getMoneyEmbed(author));
else if (receiver.money < amount) else if (receiver.money < amount)
return channel.send("They don't have enough Mons for that.", getMoneyEmbed(target)); return send("They don't have enough Mons for that.", getMoneyEmbed(target));
return channel.send("How long until the bet ends?"); return send("How long until the bet ends?");
} else return; } else return;
}, },
any: new Command({ any: new Command({
description: "Duration of the bet.", description: "Duration of the bet.",
async run({client, args, author, message, channel, guild}) { async run({send, client, args, author, message, channel, guild}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
// [Pertinence to make configurable on the fly.] // [Pertinence to make configurable on the fly.]
// Lower and upper bounds for bet // Lower and upper bounds for bet
@ -62,107 +61,94 @@ export const BetCommand = new NamedCommand({
const duration = parseDuration(args[2].trim()); const duration = parseDuration(args[2].trim());
// handle invalid target // handle invalid target
if (target.id == author.id) return channel.send("You can't bet Mons with yourself!"); if (target.id == author.id) return send("You can't bet Mons with yourself!");
else if (target.bot && process.argv[2] !== "dev") else if (target.bot && !IS_DEV_MODE) return send("You can't bet Mons with a bot!");
return channel.send("You can't bet Mons with a bot!");
// handle invalid amount // handle invalid amount
if (amount <= 0) return channel.send("You must bet at least one Mon!"); if (amount <= 0) return send("You must bet at least one Mon!");
else if (sender.money < amount) else if (sender.money < amount)
return channel.send("You don't have enough Mons for that.", getMoneyEmbed(author)); return send("You don't have enough Mons for that.", getMoneyEmbed(author));
else if (receiver.money < amount) else if (receiver.money < amount)
return channel.send("They don't have enough Mons for that.", getMoneyEmbed(target)); return send("They don't have enough Mons for that.", getMoneyEmbed(target));
// handle invalid duration // handle invalid duration
if (duration <= 0) return channel.send("Invalid bet duration"); if (duration <= 0) return send("Invalid bet duration");
else if (duration <= parseDuration(durationBounds.min)) else if (duration <= parseDuration(durationBounds.min))
return channel.send(`Bet duration is too short, maximum duration is ${durationBounds.min}`); return send(`Bet duration is too short, maximum duration is ${durationBounds.min}`);
else if (duration >= parseDuration(durationBounds.max)) else if (duration >= parseDuration(durationBounds.max))
return channel.send(`Bet duration is too long, maximum duration is ${durationBounds.max}`); return send(`Bet duration is too long, maximum duration is ${durationBounds.max}`);
// Ask target whether or not they want to take the bet. // Ask target whether or not they want to take the bet.
const takeBet = await askYesOrNo( const takeBet = await confirm(
await channel.send( await send(
`<@${target.id}>, do you want to take this bet of ${pluralise(amount, "Mon", "s")}` `<@${target.id}>, do you want to take this bet of ${pluralise(amount, "Mon", "s")}`
), ),
target.id target.id
); );
if (takeBet) { if (!takeBet) return send(`<@${target.id}> has rejected your bet, <@${author.id}>`);
// [MEDIUM PRIORITY: bet persistence to prevent losses in case of shutdown.]
// Remove amount money from both parts at the start to avoid duplication of money.
sender.money -= amount;
receiver.money -= amount;
// Very hacky solution for persistence but better than no solution, backup returns runs during the bot's setup code.
sender.ecoBetInsurance += amount;
receiver.ecoBetInsurance += amount;
Storage.save();
// Notify both users. // [MEDIUM PRIORITY: bet persistence to prevent losses in case of shutdown.]
await channel.send( // Remove amount money from both parts at the start to avoid duplication of money.
`<@${target.id}> has taken <@${author.id}>'s bet, the bet amount of ${pluralise( sender.money -= amount;
amount, receiver.money -= amount;
"Mon", // Very hacky solution for persistence but better than no solution, backup returns runs during the bot's setup code.
"s" sender.ecoBetInsurance += amount;
)} has been deducted from each of them.` receiver.ecoBetInsurance += amount;
); Storage.save();
// Wait for the duration of the bet. // Notify both users.
return client.setTimeout(async () => { send(
// In debug mode, saving the storage will break the references, so you have to redeclare sender and receiver for it to actually save. `<@${target.id}> has taken <@${author.id}>'s bet, the bet amount of ${pluralise(
const sender = Storage.getUser(author.id); amount,
const receiver = Storage.getUser(target.id); "Mon",
// [TODO: when D.JSv13 comes out, inline reply to clean up.] "s"
// When bet is over, give a vote to ask people their thoughts. )} has been deducted from each of them.`
const voteMsg = await channel.send( );
// Wait for the duration of the bet.
return client.setTimeout(async () => {
// In debug mode, saving the storage will break the references, so you have to redeclare sender and receiver for it to actually save.
const sender = Storage.getUser(author.id);
const receiver = Storage.getUser(target.id);
// [TODO: when D.JSv13 comes out, inline reply to clean up.]
// When bet is over, give a vote to ask people their thoughts.
// Filter reactions to only collect the pertinent ones.
const results = await poll(
await send(
`VOTE: do you think that <@${ `VOTE: do you think that <@${
target.id target.id
}> has won the bet?\nhttps://discord.com/channels/${guild!.id}/${channel.id}/${ }> has won the bet?\nhttps://discord.com/channels/${guild!.id}/${channel.id}/${
message.id message.id
}` }`
),
["✅", "❌"],
// [Pertinence to make configurable on the fly.]
parseDuration("2m")
);
// Count votes
const ok = results["✅"];
const no = results["❌"];
if (ok > no) {
receiver.money += amount * 2;
send(`By the people's votes, ${target} has won the bet that ${author} had sent them.`);
} else if (ok < no) {
sender.money += amount * 2;
send(`By the people's votes, ${target} has lost the bet that ${author} had sent them.`);
} else {
sender.money += amount;
receiver.money += amount;
send(
`By the people's votes, ${target} couldn't be determined to have won or lost the bet that ${author} had sent them.`
); );
await voteMsg.react("✅"); }
await voteMsg.react("❌");
// Filter reactions to only collect the pertinent ones. sender.ecoBetInsurance -= amount;
voteMsg receiver.ecoBetInsurance -= amount;
.awaitReactions( Storage.save();
(reaction, user) => { }, duration);
return ["✅", "❌"].includes(reaction.emoji.name);
},
// [Pertinence to make configurable on the fly.]
{time: parseDuration("2m")}
)
.then((reactions) => {
// Count votes
const okReaction = reactions.get("✅");
const noReaction = reactions.get("❌");
const ok = okReaction ? (okReaction.count ?? 1) - 1 : 0;
const no = noReaction ? (noReaction.count ?? 1) - 1 : 0;
if (ok > no) {
receiver.money += amount * 2;
channel.send(
`By the people's votes, <@${target.id}> has won the bet that <@${author.id}> had sent them.`
);
} else if (ok < no) {
sender.money += amount * 2;
channel.send(
`By the people's votes, <@${target.id}> has lost the bet that <@${author.id}> had sent them.`
);
} else {
sender.money += amount;
receiver.money += amount;
channel.send(
`By the people's votes, <@${target.id}> couldn't be determined to have won or lost the bet that <@${author.id}> had sent them.`
);
}
sender.ecoBetInsurance -= amount;
receiver.ecoBetInsurance -= amount;
Storage.save();
});
}, duration);
} else return await channel.send(`<@${target.id}> has rejected your bet, <@${author.id}>`);
} else return; } else return;
} }
}) })

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand, prompt} from "../../../core"; import {Command, getMemberByName, NamedCommand, confirm, RestCommand} from "../../../core";
import {pluralise} from "../../../lib"; import {pluralise} from "../../../lib";
import {Storage} from "../../../structures"; import {Storage} from "../../../structures";
import {isAuthorized, getMoneyEmbed, getSendEmbed, ECO_EMBED_COLOR} from "./eco-utils"; import {isAuthorized, getMoneyEmbed, getSendEmbed, ECO_EMBED_COLOR} from "./eco-utils";
@ -6,7 +6,7 @@ import {isAuthorized, getMoneyEmbed, getSendEmbed, ECO_EMBED_COLOR} from "./eco-
export const DailyCommand = new NamedCommand({ export const DailyCommand = new NamedCommand({
description: "Pick up your daily Mons. The cooldown is per user and every 22 hours to allow for some leeway.", description: "Pick up your daily Mons. The cooldown is per user and every 22 hours to allow for some leeway.",
aliases: ["get"], aliases: ["get"],
async run({author, channel, guild}) { async run({send, author, channel, guild}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const user = Storage.getUser(author.id); const user = Storage.getUser(author.id);
const now = Date.now(); const now = Date.now();
@ -15,7 +15,7 @@ export const DailyCommand = new NamedCommand({
user.money++; user.money++;
user.lastReceived = now; user.lastReceived = now;
Storage.save(); Storage.save();
channel.send({ send({
embed: { embed: {
title: "Daily Reward", title: "Daily Reward",
description: "You received 1 Mon!", description: "You received 1 Mon!",
@ -23,7 +23,7 @@ export const DailyCommand = new NamedCommand({
} }
}); });
} else } else
channel.send({ send({
embed: { embed: {
title: "Daily Reward", title: "Daily Reward",
description: `It's too soon to pick up your daily Mons. You have about ${( description: `It's too soon to pick up your daily Mons. You have about ${(
@ -39,7 +39,7 @@ export const DailyCommand = new NamedCommand({
export const GuildCommand = new NamedCommand({ export const GuildCommand = new NamedCommand({
description: "Get info on the guild's economy as a whole.", description: "Get info on the guild's economy as a whole.",
async run({guild, channel}) { async run({send, guild, channel}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const users = Storage.users; const users = Storage.users;
let totalAmount = 0; let totalAmount = 0;
@ -49,7 +49,7 @@ export const GuildCommand = new NamedCommand({
totalAmount += user.money; totalAmount += user.money;
} }
channel.send({ send({
embed: { embed: {
title: `The Bank of ${guild!.name}`, title: `The Bank of ${guild!.name}`,
color: ECO_EMBED_COLOR, color: ECO_EMBED_COLOR,
@ -77,7 +77,7 @@ export const GuildCommand = new NamedCommand({
export const LeaderboardCommand = new NamedCommand({ export const LeaderboardCommand = new NamedCommand({
description: "See the richest players.", description: "See the richest players.",
aliases: ["top"], aliases: ["top"],
async run({guild, channel, client}) { async run({send, guild, channel, client}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const users = Storage.users; const users = Storage.users;
const ids = Object.keys(users); const ids = Object.keys(users);
@ -89,12 +89,12 @@ export const LeaderboardCommand = new NamedCommand({
const user = await client.users.fetch(id); const user = await client.users.fetch(id);
fields.push({ fields.push({
name: `#${i + 1}. ${user.username}#${user.discriminator}`, name: `#${i + 1}. ${user.tag}`,
value: pluralise(users[id].money, "Mon", "s") value: pluralise(users[id].money, "Mon", "s")
}); });
} }
channel.send({ send({
embed: { embed: {
title: "Top 10 Richest Players", title: "Top 10 Richest Players",
color: ECO_EMBED_COLOR, color: ECO_EMBED_COLOR,
@ -116,24 +116,23 @@ export const PayCommand = new NamedCommand({
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({
async run({args, author, channel, guild}): Promise<any> { async run({send, args, author, channel, guild}): Promise<any> {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const amount = Math.floor(args[1]); const amount = Math.floor(args[1]);
const sender = Storage.getUser(author.id); const sender = Storage.getUser(author.id);
const target = args[0]; const target = args[0];
const receiver = Storage.getUser(target.id); const receiver = Storage.getUser(target.id);
if (amount <= 0) return channel.send("You must send at least one Mon!"); if (amount <= 0) return send("You must send at least one Mon!");
else if (sender.money < amount) else if (sender.money < amount)
return channel.send("You don't have enough Mons for that.", getMoneyEmbed(author)); return send("You don't have enough Mons for that.", getMoneyEmbed(author));
else if (target.id === author.id) return channel.send("You can't send Mons to yourself!"); else if (target.id === author.id) return send("You can't send Mons to yourself!");
else if (target.bot && process.argv[2] !== "dev") else if (target.bot && !IS_DEV_MODE) return send("You can't send Mons to a bot!");
return channel.send("You can't send Mons to a bot!");
sender.money -= amount; sender.money -= amount;
receiver.money += amount; receiver.money += amount;
Storage.save(); Storage.save();
return channel.send(getSendEmbed(author, target, amount)); return send(getSendEmbed(author, target, amount));
} }
} }
}) })
@ -141,71 +140,55 @@ export const PayCommand = new NamedCommand({
number: new Command({ number: new Command({
run: "You must use the format `eco pay <user> <amount>`!" run: "You must use the format `eco pay <user> <amount>`!"
}), }),
any: new Command({ any: new RestCommand({
async run({args, author, channel, guild}) { async run({send, args, author, channel, guild, combined}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const last = args.pop(); const last = args.pop();
if (!/\d+/g.test(last) && args.length === 0) if (!/\d+/g.test(last) && args.length === 0) return send("You need to enter an amount you're sending!");
return channel.send("You need to enter an amount you're sending!");
const amount = Math.floor(last); const amount = Math.floor(last);
const sender = Storage.getUser(author.id); const sender = Storage.getUser(author.id);
if (amount <= 0) return channel.send("You must send at least one Mon!"); if (amount <= 0) return send("You must send at least one Mon!");
else if (sender.money < amount) else if (sender.money < amount)
return channel.send("You don't have enough Mons to do that!", getMoneyEmbed(author)); return send("You don't have enough Mons to do that!", getMoneyEmbed(author));
else if (!guild) else if (!guild)
return channel.send("You have to use this in a server if you want to send Mons with a username!"); return send("You have to use this in a server if you want to send Mons with a username!");
const username = args.join(" "); const member = await getMemberByName(guild, combined);
const member = ( if (typeof member === "string") return send(member);
await guild.members.fetch({ else if (member.user.id === author.id) return send("You can't send Mons to yourself!");
query: username, else if (member.user.bot && process.argv[2] !== "dev") return send("You can't send Mons to a bot!");
limit: 1
})
).first();
if (!member)
return channel.send(
`Couldn't find a user by the name of \`${username}\`! If you want to send Mons to someone in a different server, you have to use their user ID!`
);
else if (member.user.id === author.id) return channel.send("You can't send Mons to yourself!");
else if (member.user.bot && process.argv[2] !== "dev")
return channel.send("You can't send Mons to a bot!");
const target = member.user; const target = member.user;
return prompt( const result = await confirm(
await channel.send( await send(`Are you sure you want to send ${pluralise(amount, "Mon", "s")} to this person?`, {
`Are you sure you want to send ${pluralise( embed: {
amount, color: ECO_EMBED_COLOR,
"Mon", author: {
"s" name: target.tag,
)} to this person?\n*(This message will automatically be deleted after 10 seconds.)*`, icon_url: target.displayAvatarURL({
{ format: "png",
embed: { dynamic: true
color: ECO_EMBED_COLOR, })
author: {
name: `${target.username}#${target.discriminator}`,
icon_url: target.displayAvatarURL({
format: "png",
dynamic: true
})
}
} }
} }
), }),
author.id, author.id
() => {
const receiver = Storage.getUser(target.id);
sender.money -= amount;
receiver.money += amount;
Storage.save();
channel.send(getSendEmbed(author, target, amount));
}
); );
if (result) {
const receiver = Storage.getUser(target.id);
sender.money -= amount;
receiver.money += amount;
Storage.save();
send(getSendEmbed(author, target, amount));
}
} }
return;
} }
}) })
}); });

View File

@ -1,12 +1,14 @@
import {Command, NamedCommand} from "../../../core"; import {Command, NamedCommand} from "../../../core";
import {Storage} from "../../../structures"; import {Storage} from "../../../structures";
import {isAuthorized, getMoneyEmbed} from "./eco-utils"; import {isAuthorized, getMoneyEmbed} from "./eco-utils";
import {User} from "discord.js";
import {pluralise} from "../../../lib";
const WEEKDAY = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; const WEEKDAY = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
export const MondayCommand = new NamedCommand({ export const MondayCommand = new NamedCommand({
description: "Use this on a UTC Monday to get an extra Mon. Does not affect your 22 hour timer for `eco daily`.", description: "Use this on a UTC Monday to get an extra Mon. Does not affect your 22 hour timer for `eco daily`.",
async run({guild, channel, author}) { async run({send, guild, channel, author}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
const user = Storage.getUser(author.id); const user = Storage.getUser(author.id);
const now = new Date(); const now = new Date();
@ -19,16 +21,55 @@ export const MondayCommand = new NamedCommand({
user.money++; user.money++;
user.lastMonday = now.getTime(); user.lastMonday = now.getTime();
Storage.save(); Storage.save();
channel.send("It is **Mon**day, my dudes.", getMoneyEmbed(author)); send("It is **Mon**day, my dudes.", getMoneyEmbed(author));
} else channel.send("You've already claimed your **Mon**day reward for this week."); } else send("You've already claimed your **Mon**day reward for this week.");
} else { } else {
const weekdayName = WEEKDAY[weekday]; const weekdayName = WEEKDAY[weekday];
const hourText = now.getUTCHours().toString().padStart(2, "0"); const hourText = now.getUTCHours().toString().padStart(2, "0");
const minuteText = now.getUTCMinutes().toString().padStart(2, "0"); const minuteText = now.getUTCMinutes().toString().padStart(2, "0");
channel.send( send(
`Come back when it's **Mon**day. Right now, it's ${weekdayName}, ${hourText}:${minuteText} (UTC).` `Come back when it's **Mon**day. Right now, it's ${weekdayName}, ${hourText}:${minuteText} (UTC).`
); );
} }
} }
} }
}); });
export const AwardCommand = new NamedCommand({
description: "Only usable by Mon, awards one or a specified amount of Mons to the user.",
usage: "<user> (<amount>)",
aliases: ["give"],
run: "You need to specify a user!",
user: new Command({
async run({send, message, channel, guild, author, member, client, args}) {
if (author.id === "394808963356688394" || IS_DEV_MODE) {
const target = args[0] as User;
const user = Storage.getUser(target.id);
user.money++;
Storage.save();
send(`1 Mon given to ${target.username}.`, getMoneyEmbed(target));
} else {
send("This command is restricted to the bean.");
}
},
number: new Command({
async run({send, message, channel, guild, author, member, client, args}) {
if (author.id === "394808963356688394" || IS_DEV_MODE) {
const target = args[0] as User;
const amount = Math.floor(args[1]);
if (amount > 0) {
const user = Storage.getUser(target.id);
user.money += amount;
Storage.save();
send(`${pluralise(amount, "Mon", "s")} given to ${target.username}.`, getMoneyEmbed(target));
} else {
send("You need to enter a number greater than 0.");
}
} else {
send("This command is restricted to the bean.");
}
}
})
})
});

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand, paginate} from "../../../core"; import {Command, NamedCommand, paginate, RestCommand} from "../../../core";
import {pluralise, split} from "../../../lib"; import {pluralise, split} from "../../../lib";
import {Storage, getPrefix} from "../../../structures"; import {Storage, getPrefix} from "../../../structures";
import {isAuthorized, ECO_EMBED_COLOR} from "./eco-utils"; import {isAuthorized, ECO_EMBED_COLOR} from "./eco-utils";
@ -7,7 +7,7 @@ import {EmbedField} from "discord.js";
export const ShopCommand = new NamedCommand({ export const ShopCommand = new NamedCommand({
description: "Displays the list of items you can buy in the shop.", description: "Displays the list of items you can buy in the shop.",
async run({guild, channel, author}) { async run({send, guild, channel, author}) {
if (isAuthorized(guild, channel)) { if (isAuthorized(guild, channel)) {
function getShopEmbed(selection: ShopItem[], title: string) { function getShopEmbed(selection: ShopItem[], title: string) {
const fields: EmbedField[] = []; const fields: EmbedField[] = [];
@ -34,7 +34,7 @@ export const ShopCommand = new NamedCommand({
const shopPages = split(ShopItems, 5); const shopPages = split(ShopItems, 5);
const pageAmount = shopPages.length; const pageAmount = shopPages.length;
paginate(channel, author.id, pageAmount, (page, hasMultiplePages) => { paginate(send, author.id, pageAmount, (page, hasMultiplePages) => {
return getShopEmbed( return getShopEmbed(
shopPages[page], shopPages[page],
hasMultiplePages ? `Shop (Page ${page + 1} of ${pageAmount})` : "Shop" hasMultiplePages ? `Shop (Page ${page + 1} of ${pageAmount})` : "Shop"
@ -47,37 +47,37 @@ export const ShopCommand = new NamedCommand({
export const BuyCommand = new NamedCommand({ export const BuyCommand = new NamedCommand({
description: "Buys an item from the shop.", description: "Buys an item from the shop.",
usage: "<item>", usage: "<item>",
async run({guild, channel, args, message, author}) { run: "You need to specify an item to buy.",
if (isAuthorized(guild, channel)) { any: new RestCommand({
let found = false; async run({send, guild, channel, args, message, author, combined}) {
if (isAuthorized(guild, channel)) {
let found = false;
let amount = 1; // The amount the user is buying.
let amount = 1; // The amount the user is buying. // For now, no shop items support being bought multiple times. Uncomment these 2 lines when it's supported/needed.
//if (/\d+/g.test(args[args.length - 1]))
//amount = parseInt(args.pop());
// For now, no shop items support being bought multiple times. Uncomment these 2 lines when it's supported/needed. for (let item of ShopItems) {
//if (/\d+/g.test(args[args.length - 1])) if (item.usage === combined) {
//amount = parseInt(args.pop()); const user = Storage.getUser(author.id);
const cost = item.cost * amount;
let requested = args.join(" "); // The item the user is buying. if (cost > user.money) {
send("Not enough Mons!");
} else {
user.money -= cost;
Storage.save();
item.run(message, cost, amount);
}
for (let item of ShopItems) { found = true;
if (item.usage === requested) { break;
const user = Storage.getUser(author.id);
const cost = item.cost * amount;
if (cost > user.money) {
channel.send("Not enough Mons!");
} else {
user.money -= cost;
Storage.save();
item.run(message, cost, amount);
} }
found = true;
break;
} }
}
if (!found) channel.send(`There's no item in the shop that goes by \`${requested}\`!`); if (!found) send(`There's no item in the shop that goes by \`${combined}\`!`);
}
} }
} })
}); });

View File

@ -42,11 +42,11 @@ export function getSendEmbed(sender: User, receiver: User, amount: number): obje
description: `${sender.toString()} has sent ${pluralise(amount, "Mon", "s")} to ${receiver.toString()}!`, description: `${sender.toString()} has sent ${pluralise(amount, "Mon", "s")} to ${receiver.toString()}!`,
fields: [ fields: [
{ {
name: `Sender: ${sender.username}#${sender.discriminator}`, name: `Sender: ${sender.tag}`,
value: pluralise(Storage.getUser(sender.id).money, "Mon", "s") value: pluralise(Storage.getUser(sender.id).money, "Mon", "s")
}, },
{ {
name: `Receiver: ${receiver.username}#${receiver.discriminator}`, name: `Receiver: ${receiver.tag}`,
value: pluralise(Storage.getUser(receiver.id).money, "Mon", "s") value: pluralise(Storage.getUser(receiver.id).money, "Mon", "s")
} }
], ],

View File

@ -36,19 +36,17 @@ const endpoints: {sfw: {[key: string]: string}} = {
export default new NamedCommand({ export default new NamedCommand({
description: "Provides you with a random image with the selected argument.", description: "Provides you with a random image with the selected argument.",
async run({message, channel, guild, author, member, client, args}) { async run({send}) {
channel.send( send(`Please provide an image type. Available arguments:\n\`[${Object.keys(endpoints.sfw).join(", ")}]\`.`);
`Please provide an image type. Available arguments:\n\`[${Object.keys(endpoints.sfw).join(", ")}]\`.`
);
}, },
any: new Command({ any: new Command({
description: "Image type to send.", description: "Image type to send.",
async run({message, channel, guild, author, member, client, args}) { async run({send, 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)) return send("Couldn't find that endpoint!");
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());
return channel.send(content.url); return send(content.url);
} }
}) })
}); });

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand} from "../../core";
import {random} from "../../lib"; import {random} from "../../lib";
const responses = [ const responses = [
@ -61,7 +61,7 @@ const responses = [
export default new NamedCommand({ export default new NamedCommand({
description: "Sends random ok message.", description: "Sends random ok message.",
async run({message, channel, guild, author, member, client, args}) { async run({send}) {
channel.send(`ok ${random(responses)}`); send(`ok ${random(responses)}`);
} }
}); });

View File

@ -1,12 +1,15 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import {getContent} from "../../lib"; import {getContent} from "../../lib";
import {URL} from "url"; import {URL} from "url";
export default new NamedCommand({ export default new NamedCommand({
description: "OwO-ifies the input.", description: "OwO-ifies the input.",
async run({message, channel, guild, author, member, client, args}) { run: "You need to specify some text to owoify.",
let url = new URL(`https://nekos.life/api/v2/owoify?text=${args.join(" ")}`); any: new RestCommand({
const content = (await getContent(url.toString())) as any; // Apparently, the object in question is {owo: string}. async run({send, combined}) {
channel.send(content.owo); let url = new URL(`https://nekos.life/api/v2/owoify?text=${combined}`);
} const content = (await getContent(url.toString())) as any; // Apparently, the object in question is {owo: string}.
send(content.owo);
}
})
}); });

13
src/commands/fun/party.ts Normal file
View File

@ -0,0 +1,13 @@
import {NamedCommand} from "../../core";
export default new NamedCommand({
description: "Initiates a celebratory stream from the bot.",
async run({send, client}) {
send("This calls for a celebration!");
client.user!.setActivity({
type: "STREAMING",
url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
name: "Celebration!"
});
}
});

View File

@ -1,13 +1,13 @@
import {MessageEmbed} from "discord.js"; import {MessageEmbed} from "discord.js";
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
export default new NamedCommand({ export default new NamedCommand({
description: "Create a poll.", description: "Create a poll.",
usage: "<question>", usage: "<question>",
run: "Please provide a question.", run: "Please provide a question.",
any: new Command({ any: new RestCommand({
description: "Question for the poll.", description: "Question for the poll.",
async run({message, channel, guild, author, member, client, args}) { async run({send, message, combined}) {
const embed = new MessageEmbed() const embed = new MessageEmbed()
.setAuthor( .setAuthor(
`Poll created by ${message.author.username}`, `Poll created by ${message.author.username}`,
@ -15,8 +15,8 @@ export default new NamedCommand({
) )
.setColor(0xffffff) .setColor(0xffffff)
.setFooter("React to vote.") .setFooter("React to vote.")
.setDescription(args.join(" ")); .setDescription(combined);
const msg = await channel.send(embed); const msg = await send(embed);
await msg.react("✅"); await msg.react("✅");
await msg.react("⛔"); await msg.react("⛔");
message.delete({ message.delete({

View File

@ -4,8 +4,8 @@ import {Random} from "../../lib";
export default new NamedCommand({ export default new NamedCommand({
description: "Ravioli ravioli...", description: "Ravioli ravioli...",
usage: "[number from 1 to 9]", usage: "[number from 1 to 9]",
async run({message, channel, guild, author, member, client, args}) { async run({send}) {
channel.send({ send({
embed: { embed: {
title: "Ravioli ravioli...", title: "Ravioli ravioli...",
image: { image: {
@ -18,11 +18,11 @@ export default new NamedCommand({
}); });
}, },
number: new Command({ number: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, args}) {
const arg: number = args[0]; const arg: number = args[0];
if (arg >= 1 && arg <= 9) { if (arg >= 1 && arg <= 9) {
channel.send({ send({
embed: { embed: {
title: "Ravioli ravioli...", title: "Ravioli ravioli...",
image: { image: {
@ -31,7 +31,7 @@ export default new NamedCommand({
} }
}); });
} else { } else {
channel.send("Please provide a number between 1 and 9."); send("Please provide a number between 1 and 9.");
} }
} }
}) })

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
const letters: {[letter: string]: string[]} = { const letters: {[letter: string]: string[]} = {
a: "aáàảãạâấầẩẫậăắằẳẵặ".split(""), a: "aáàảãạâấầẩẫậăắằẳẵặ".split(""),
@ -34,8 +34,26 @@ let phrase = "I have no currently set phrase!";
export default new NamedCommand({ export default new NamedCommand({
description: "Transforms your text into .", description: "Transforms your text into .",
usage: "thonk ([text])", usage: "thonk ([text])",
async run({message, channel, guild, author, member, client, args}) { async run({send, author}) {
if (args.length > 0) phrase = args.join(" "); const msg = await send(transform(phrase));
channel.send(transform(phrase)); msg.createReactionCollector(
} (reaction, user) => {
if (user.id === author.id && reaction.emoji.name === "❌") msg.delete();
return false;
},
{time: 60000}
);
},
any: new RestCommand({
async run({send, author, combined}) {
const msg = await send(transform(combined));
msg.createReactionCollector(
(reaction, user) => {
if (user.id === author.id && reaction.emoji.name === "❌") msg.delete();
return false;
},
{time: 60000}
);
}
})
}); });

View File

@ -1,27 +1,31 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import {MessageEmbed} from "discord.js"; import {MessageEmbed} from "discord.js";
// Anycasting Alert import urban from "relevant-urban";
const urban = require("relevant-urban");
export default new NamedCommand({ export default new NamedCommand({
description: "Gives you a definition of the inputted word.", description: "Gives you a definition of the inputted word.",
async run({message, channel, guild, author, member, client, args}) { run: "Please input a word.",
if (!args[0]) { any: new RestCommand({
channel.send("Please input a word."); async run({send, combined}) {
// [Bug Fix]: Use encodeURIComponent() when emojis are used: "TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters"
urban(encodeURIComponent(combined))
.then((res) => {
const embed = new MessageEmbed()
.setColor(0x1d2439)
.setTitle(res.word)
.setURL(res.urbanURL)
.setDescription(`**Definition:**\n*${res.definition}*\n\n**Example:**\n*${res.example}*`)
// [Bug Fix] When an embed field is empty (if the author field is missing, like the top entry for "british"): "RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty."
.addField("Author", res.author || "N/A", true)
.addField("Rating", `**\`Upvotes: ${res.thumbsUp} | Downvotes: ${res.thumbsDown}\`**`);
if (res.tags && res.tags.length > 0 && res.tags.join(" ").length < 1024)
embed.addField("Tags", res.tags.join(", "), true);
send(embed);
})
.catch(() => {
send("Sorry, that word was not found.");
});
} }
const res = await urban(args.join(" ")).catch((e: Error) => { })
return channel.send("Sorry, that word was not found.");
});
const embed = new MessageEmbed()
.setColor(0x1d2439)
.setTitle(res.word)
.setURL(res.urbanURL)
.setDescription(`**Definition:**\n*${res.definition}*\n\n**Example:**\n*${res.example}*`)
.addField("Author", res.author, true)
.addField("Rating", `**\`Upvotes: ${res.thumbsUp} | Downvotes: ${res.thumbsDown}\`**`);
if (res.tags.length > 0 && res.tags.join(" ").length < 1024) {
embed.addField("Tags", res.tags.join(", "), true);
}
channel.send(embed);
}
}); });

View File

@ -0,0 +1,34 @@
import {NamedCommand, RestCommand} from "../../core";
const vaporwave = (() => {
const map = new Map<string, string>();
const vaporwave =
"_ ";
const normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\"#$%&'()*+,-./0123456789:;<=>?@[\\]^_`{|}~ ";
if (vaporwave.length !== normal.length) console.error("Vaporwave text failed to load properly!");
for (let i = 0; i < vaporwave.length; i++) map.set(normal[i], vaporwave[i]);
return map;
})();
function getVaporwaveText(text: string): string {
let output = "";
for (const c of text) {
const transformed = vaporwave.get(c);
if (transformed) output += transformed;
}
return output;
}
export default new NamedCommand({
description: "Transforms your text into .",
run: "You need to enter some text!",
any: new RestCommand({
async run({send, combined}) {
const text = getVaporwaveText(combined);
if (text !== "") send(text);
else send("Make sure to enter at least one valid character.");
}
})
});

View File

@ -1,36 +1,38 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import {MessageEmbed} from "discord.js"; import {MessageEmbed} from "discord.js";
// Anycasting Alert import {find} from "weather-js";
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}) { run: "You need to provide a city.",
if (args.length == 0) return channel.send("You need to provide a city."); any: new RestCommand({
return weather.find( async run({send, combined}) {
{ find(
search: args.join(" "), {
degreeType: "C" search: combined,
}, degreeType: "C"
function (err: any, result: any) { },
if (err) channel.send(err); function (error, result) {
var current = result[0].current; if (error) return send(error.toString());
var location = result[0].location; if (result.length === 0) return send("No city found by that name.");
const embed = new MessageEmbed() var current = result[0].current;
.setDescription(`**${current.skytext}**`) var location = result[0].location;
.setAuthor(`Weather for ${current.observationpoint}`) const embed = new MessageEmbed()
.setThumbnail(current.imageUrl) .setDescription(`**${current.skytext}**`)
.setColor(0x00ae86) .setAuthor(`Weather for ${current.observationpoint}`)
.addField("Timezone", `UTC${location.timezone}`, true) .setThumbnail(current.imageUrl)
.addField("Degree Type", "C", true) .setColor(0x00ae86)
.addField("Temperature", `${current.temperature} Degrees`, true) .addField("Timezone", `UTC${location.timezone}`, true)
.addField("Feels like", `${current.feelslike} Degrees`, true) .addField("Degree Type", "C", true)
.addField("Winds", current.winddisplay, true) .addField("Temperature", `${current.temperature} Degrees`, true)
.addField("Humidity", `${current.humidity}%`, true); .addField("Feels like", `${current.feelslike} Degrees`, true)
channel.send({ .addField("Winds", current.winddisplay, true)
embed .addField("Humidity", `${current.humidity}%`, true);
}); return send({
} embed
); });
} }
);
}
})
}); });

View File

@ -1,5 +1,5 @@
import {User} from "discord.js"; import {User} from "discord.js";
import {Command, NamedCommand, getMemberByUsername, CHANNEL_TYPE} from "../../core"; import {Command, NamedCommand, getMemberByName, CHANNEL_TYPE, RestCommand} 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} = {
@ -43,46 +43,41 @@ const registry: {[id: string]: string} = {
export default new NamedCommand({ export default new NamedCommand({
description: "Tells you who you or the specified user is.", description: "Tells you who you or the specified user is.",
aliases: ["whoami"], aliases: ["whoami"],
async run({message, channel, guild, author, member, client, args}) { async run({send, author}) {
const id = author.id; const id = author.id;
if (id in registry) { if (id in registry) {
channel.send(registry[id]); send(registry[id]);
} else { } else {
channel.send("You haven't been added to the registry yet!"); send("You haven't been added to the registry yet!");
} }
}, },
id: "user", id: "user",
user: new Command({ user: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, args}) {
const user: User = args[0]; const user: User = args[0];
const id = user.id; const id = user.id;
if (id in registry) { if (id in registry) {
channel.send(`\`${user.username}\` - ${registry[id]}`); send(`\`${user.username}\` - ${registry[id]}`);
} else { } else {
channel.send(`\`${user.tag}\` hasn't been added to the registry yet!`); send(`\`${user.tag}\` hasn't been added to the registry yet!`);
} }
} }
}), }),
any: new Command({ any: new RestCommand({
channelType: CHANNEL_TYPE.GUILD, channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, client, args}) { async run({send, guild, combined}) {
const query = args.join(" ") as string; const member = await getMemberByName(guild!, combined);
const member = await getMemberByUsername(guild!, query);
if (member && member.id in registry) { if (typeof member !== "string") {
const id = member.id; if (member.id in registry) {
send(`\`${member.nickname ?? member.user.username}\` - ${registry[member.id]}`);
if (id in registry) {
channel.send(`\`${member.nickname ?? member.user.username}\` - ${registry[member.id]}`);
} else { } else {
channel.send( send(`\`${member.nickname ?? member.user.username}\` hasn't been added to the registry yet!`);
`\`${member.nickname ?? 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}\`!`); send(member);
} }
} }
}) })

View File

@ -1,7 +1,15 @@
import {Command, NamedCommand, botHasPermission, getPermissionLevel, getPermissionName, CHANNEL_TYPE} from "../../core"; import {
Command,
NamedCommand,
botHasPermission,
getPermissionLevel,
getPermissionName,
CHANNEL_TYPE,
RestCommand
} from "../../core";
import {clean} from "../../lib"; import {clean} from "../../lib";
import {Config, Storage} from "../../structures"; import {Config, Storage} from "../../structures";
import {Permissions, TextChannel} from "discord.js"; import {Permissions, TextChannel, User} from "discord.js";
import {logs} from "../../modules/globals"; import {logs} from "../../modules/globals";
function getLogBuffer(type: string) { function getLogBuffer(type: string) {
@ -21,9 +29,9 @@ const statuses = ["online", "idle", "dnd", "invisible"];
export default new NamedCommand({ 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({send, message, channel, guild, author, member, client, args}) {
const permLevel = getPermissionLevel(author, member); const permLevel = getPermissionLevel(author, member);
return channel.send(`${author}, your permission level is \`${getPermissionName(permLevel)}\` (${permLevel}).`); return send(`${author}, your permission level is \`${getPermissionName(permLevel)}\` (${permLevel}).`);
}, },
subcommands: { subcommands: {
set: new NamedCommand({ set: new NamedCommand({
@ -34,20 +42,30 @@ export default new NamedCommand({
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>) (<@bot>)",
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
Storage.getGuild(guild!.id).prefix = null; Storage.getGuild(guild!.id).prefix = null;
Storage.save(); Storage.save();
channel.send( 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}\`.`
); );
}, },
any: new Command({ any: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
Storage.getGuild(guild!.id).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]}\`.`); send(`The custom prefix for this guild is now \`${args[0]}\`.`);
} },
user: new Command({
description: "Specifies the bot in case of conflicting prefixes.",
async run({send, message, channel, guild, author, member, client, args}) {
if ((args[1] as User).id === client.user!.id) {
Storage.getGuild(guild!.id).prefix = args[0];
Storage.save();
send(`The custom prefix for this guild is now \`${args[0]}\`.`);
}
}
})
}) })
}), }),
welcome: new NamedCommand({ welcome: new NamedCommand({
@ -59,25 +77,25 @@ export default new NamedCommand({
description: description:
"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({send, message, channel, guild, author, member, client, args}) {
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`."); send("Set this server's welcome type to `none`.");
}, },
// 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({send, message, channel, guild, author, member, client, args}) {
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`."); send("Set this server's welcome type to `text`.");
} }
}), }),
graphical: new NamedCommand({ graphical: new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
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`."); send("Set this server's welcome type to `graphical`.");
} }
}) })
} }
@ -85,18 +103,18 @@ export default new NamedCommand({
channel: new NamedCommand({ channel: 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({send, message, channel, guild, author, member, client, args}) {
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.`); send(`Successfully set ${channel} as the welcome channel for this server.`);
}, },
id: "channel", id: "channel",
channel: new Command({ channel: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const result = args[0] as TextChannel; const result = args[0] as TextChannel;
Storage.getGuild(guild!.id).welcomeChannel = result.id; Storage.getGuild(guild!.id).welcomeChannel = result.id;
Storage.save(); Storage.save();
channel.send(`Successfully set this server's welcome channel to ${result}.`); send(`Successfully set this server's welcome channel to ${result}.`);
} }
}) })
}), }),
@ -104,17 +122,16 @@ export default new NamedCommand({
description: description:
"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({send, message, channel, guild, author, member, client, args}) {
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."); send("Reset your server's welcome message to the default.");
}, },
any: new Command({ any: new RestCommand({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args, combined}) {
const newMessage = args.join(" "); Storage.getGuild(guild!.id).welcomeMessage = combined;
Storage.getGuild(guild!.id).welcomeMessage = newMessage;
Storage.save(); Storage.save();
channel.send(`Set your server's welcome message to \`${newMessage}\`.`); send(`Set your server's welcome message to \`${combined}\`.`);
} }
}) })
}) })
@ -123,26 +140,26 @@ export default new NamedCommand({
stream: new NamedCommand({ stream: new NamedCommand({
description: "Set a channel to send stream notifications. Type `#` to reference the channel.", description: "Set a channel to send stream notifications. Type `#` to reference the channel.",
usage: "(<channel mention>)", usage: "(<channel mention>)",
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const targetGuild = Storage.getGuild(guild!.id); const targetGuild = Storage.getGuild(guild!.id);
if (targetGuild.streamingChannel) { if (targetGuild.streamingChannel) {
targetGuild.streamingChannel = null; targetGuild.streamingChannel = null;
channel.send("Removed your server's stream notifications channel."); send("Removed your server's stream notifications channel.");
} else { } else {
targetGuild.streamingChannel = channel.id; targetGuild.streamingChannel = channel.id;
channel.send(`Set your server's stream notifications channel to ${channel}.`); send(`Set your server's stream notifications channel to ${channel}.`);
} }
Storage.save(); Storage.save();
}, },
id: "channel", id: "channel",
channel: new Command({ channel: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const result = args[0] as TextChannel; const result = args[0] as TextChannel;
Storage.getGuild(guild!.id).streamingChannel = result.id; Storage.getGuild(guild!.id).streamingChannel = result.id;
Storage.save(); Storage.save();
channel.send(`Successfully set this server's stream notifications channel to ${result}.`); send(`Successfully set this server's stream notifications channel to ${result}.`);
} }
}) })
}) })
@ -151,17 +168,17 @@ export default new NamedCommand({
diag: new NamedCommand({ diag: new NamedCommand({
description: 'Requests a debug log with the "info" verbosity level.', description: 'Requests a debug log with the "info" verbosity level.',
permission: PERMISSIONS.BOT_SUPPORT, permission: PERMISSIONS.BOT_SUPPORT,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
channel.send(getLogBuffer("info")); send(getLogBuffer("info"));
}, },
any: new Command({ any: new Command({
description: `Select a verbosity to listen to. Available levels: \`[${Object.keys(logs).join(", ")}]\``, description: `Select a verbosity to listen to. Available levels: \`[${Object.keys(logs).join(", ")}]\``,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const type = args[0]; const type = args[0];
if (type in logs) channel.send(getLogBuffer(type)); if (type in logs) send(getLogBuffer(type));
else else
channel.send( send(
`Couldn't find a verbosity level named \`${type}\`! The available types are \`[${Object.keys( `Couldn't find a verbosity level named \`${type}\`! The available types are \`[${Object.keys(
logs logs
).join(", ")}]\`.` ).join(", ")}]\`.`
@ -172,17 +189,17 @@ export default new NamedCommand({
status: new NamedCommand({ status: new NamedCommand({
description: "Changes the bot's status.", description: "Changes the bot's status.",
permission: PERMISSIONS.BOT_SUPPORT, permission: PERMISSIONS.BOT_SUPPORT,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
channel.send("Setting status to `online`..."); send("Setting status to `online`...");
}, },
any: new Command({ any: new Command({
description: `Select a status to set to. Available statuses: \`[${statuses.join(", ")}]\`.`, description: `Select a status to set to. Available statuses: \`[${statuses.join(", ")}]\`.`,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
if (!statuses.includes(args[0])) { if (!statuses.includes(args[0])) {
return channel.send("That status doesn't exist!"); return send("That status doesn't exist!");
} else { } else {
client.user?.setStatus(args[0]); client.user?.setStatus(args[0]);
return channel.send(`Setting status to \`${args[0]}\`...`); return send(`Setting status to \`${args[0]}\`...`);
} }
} }
}) })
@ -191,7 +208,7 @@ export default 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, channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({send, 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)) { if (botHasPermission(guild, Permissions.FLAGS.MANAGE_MESSAGES)) {
message.delete(); message.delete();
@ -200,16 +217,14 @@ export default new NamedCommand({
}); });
const travMessages = msgs.filter((m) => m.author.id === client.user?.id); const travMessages = msgs.filter((m) => m.author.id === client.user?.id);
await channel.send(`Found ${travMessages.size} messages to delete.`).then((m) => await send(`Found ${travMessages.size} messages to delete.`).then((m) =>
m.delete({ m.delete({
timeout: 5000 timeout: 5000
}) })
); );
await (channel as TextChannel).bulkDelete(travMessages); await (channel as TextChannel).bulkDelete(travMessages);
} else { } else {
channel.send( 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."
);
} }
} }
}), }),
@ -220,7 +235,7 @@ export default new NamedCommand({
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({send, message, channel, guild, author, member, client, args}) {
message.delete(); message.delete();
const fetched = await channel.messages.fetch({ const fetched = await channel.messages.fetch({
limit: args[0] limit: args[0]
@ -233,60 +248,63 @@ export default new NamedCommand({
description: "Evaluate code.", description: "Evaluate code.",
usage: "<code>", usage: "<code>",
permission: PERMISSIONS.BOT_OWNER, permission: PERMISSIONS.BOT_OWNER,
// You have to bring everything into scope to use them. AFAIK, there isn't a more maintainable way to do this, but at least TS will let you know if anything gets removed. run: "You have to enter some code to execute first.",
async run({message, channel, guild, author, member, client, args}) { any: new RestCommand({
try { // You have to bring everything into scope to use them. AFAIK, there isn't a more maintainable way to do this, but at least TS will let you know if anything gets removed.
const code = args.join(" "); async run({send, message, channel, guild, author, member, client, args, combined}) {
let evaled = eval(code); try {
let evaled = eval(combined);
if (typeof evaled !== "string") evaled = require("util").inspect(evaled); if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
channel.send(clean(evaled), {code: "js", split: true}); send(clean(evaled), {code: "js", split: true});
} catch (err) { } catch (err) {
channel.send(clean(err), {code: "js", split: true}); send(clean(err), {code: "js", split: true});
}
} }
} })
}), }),
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, channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { run: "You have to specify a nickname to set for the bot",
const nickName = args.join(" "); any: new RestCommand({
await guild!.me?.setNickname(nickName); async run({send, message, channel, guild, author, member, client, args, combined}) {
if (botHasPermission(guild, Permissions.FLAGS.MANAGE_MESSAGES)) message.delete({timeout: 5000}); await guild!.me?.setNickname(combined);
channel.send(`Nickname set to \`${nickName}\``).then((m) => m.delete({timeout: 5000})); if (botHasPermission(guild, Permissions.FLAGS.MANAGE_MESSAGES)) message.delete({timeout: 5000});
} send(`Nickname set to \`${combined}\``).then((m) => m.delete({timeout: 5000}));
}
})
}), }),
guilds: new NamedCommand({ guilds: new NamedCommand({
description: "Shows a list of all guilds the bot is a member of.", description: "Shows a list of all guilds the bot is a member of.",
permission: PERMISSIONS.BOT_SUPPORT, permission: PERMISSIONS.BOT_SUPPORT,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const guildList = client.guilds.cache.array().map((e) => e.name); const guildList = client.guilds.cache.array().map((e) => e.name);
channel.send(guildList, {split: true}); send(guildList, {split: true});
} }
}), }),
activity: new NamedCommand({ activity: new NamedCommand({
description: "Set the activity of the bot.", description: "Set the activity of the bot.",
permission: PERMISSIONS.BOT_SUPPORT, permission: PERMISSIONS.BOT_SUPPORT,
usage: "<type> <string>", usage: "<type> <string>",
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
client.user?.setActivity(".help", { client.user?.setActivity(".help", {
type: "LISTENING" type: "LISTENING"
}); });
channel.send("Activity set to default."); send("Activity set to default.");
}, },
any: new Command({ any: new RestCommand({
description: `Select an activity type to set. Available levels: \`[${activities.join(", ")}]\``, description: `Select an activity type to set. Available levels: \`[${activities.join(", ")}]\``,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const type = args[0]; const type = args[0];
if (activities.includes(type)) { if (activities.includes(type)) {
client.user?.setActivity(args.slice(1).join(" "), { client.user?.setActivity(args.slice(1).join(" "), {
type: args[0].toUpperCase() type: args[0].toUpperCase()
}); });
channel.send(`Set activity to \`${args[0].toUpperCase()}\` \`${args.slice(1).join(" ")}\`.`); send(`Set activity to \`${args[0].toUpperCase()}\` \`${args.slice(1).join(" ")}\`.`);
} else } else
channel.send( send(
`Couldn't find an activity type named \`${type}\`! The available types are \`[${activities.join( `Couldn't find an activity type named \`${type}\`! The available types are \`[${activities.join(
", " ", "
)}]\`.` )}]\`.`
@ -298,17 +316,17 @@ export default 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, channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
Config.systemLogsChannel = channel.id; Config.systemLogsChannel = channel.id;
Config.save(); Config.save();
channel.send(`Successfully set ${channel} as the system logs channel.`); send(`Successfully set ${channel} as the system logs channel.`);
}, },
channel: new Command({ channel: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const targetChannel = args[0] as TextChannel; const targetChannel = args[0] as TextChannel;
Config.systemLogsChannel = targetChannel.id; Config.systemLogsChannel = targetChannel.id;
Config.save(); Config.save();
channel.send(`Successfully set ${targetChannel} as the system logs channel.`); send(`Successfully set ${targetChannel} as the system logs channel.`);
} }
}) })
}) })

View File

@ -1,78 +1,61 @@
import {Command, NamedCommand, loadableCommands, categories, getPermissionName, CHANNEL_TYPE} from "../../core"; import {
import {toTitleCase, requireAllCasesHandledFor} from "../../lib"; Command,
NamedCommand,
CHANNEL_TYPE,
getPermissionName,
getCommandList,
getCommandInfo,
paginate
} from "../../core";
import {requireAllCasesHandledFor} from "../../lib";
import {MessageEmbed} from "discord.js";
const EMBED_COLOR = "#158a28";
export default new NamedCommand({ export default new NamedCommand({
description: "Lists all commands. If a command is specified, their arguments are listed as well.", description: "Lists all commands. If a command is specified, their arguments are listed as well.",
usage: "([command, [subcommand/type], ...])", usage: "([command, [subcommand/type], ...])",
aliases: ["h"], aliases: ["h"],
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
const commands = await loadableCommands; const commands = await getCommandList();
let output = `Legend: \`<type>\`, \`[list/of/stuff]\`, \`(optional)\`, \`(<optional type>)\`, \`([optional/list/...])\``; const categoryArray = commands.keyArray();
for (const [category, headers] of categories) { paginate(send, author.id, categoryArray.length, (page, hasMultiplePages) => {
let tmp = `\n\n===[ ${toTitleCase(category)} ]===`; const category = categoryArray[page];
// Ignore empty categories, including ["test"]. const commandList = commands.get(category)!;
let hasActualCommands = false; let output = `Legend: \`<type>\`, \`[list/of/stuff]\`, \`(optional)\`, \`(<optional type>)\`, \`([optional/list/...])\`\n`;
for (const command of commandList) output += `\n \`${command.name}\`: ${command.description}`;
for (const header of headers) { return new MessageEmbed()
if (header !== "test") { .setTitle(hasMultiplePages ? `${category} (Page ${page + 1} of ${categoryArray.length})` : category)
const command = commands.get(header)!; .setDescription(output)
tmp += `\n- \`${header}\`: ${command.description}`; .setColor(EMBED_COLOR);
hasActualCommands = true; });
}
}
if (hasActualCommands) output += tmp;
}
channel.send(output, {split: true});
}, },
any: new Command({ any: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
// Setup the root command const resultingBlob = await getCommandInfo(args);
const commands = await loadableCommands; if (typeof resultingBlob === "string") return send(resultingBlob);
let header = args.shift() as string; const [result, category] = resultingBlob;
let command = commands.get(header);
if (!command || header === "test") return channel.send(`No command found by the name \`${header}\`.`);
if (!(command instanceof NamedCommand))
return channel.send(`Command is not a proper instance of NamedCommand.`);
if (command.name) header = command.name;
// Search categories
let category = "Unknown";
for (const [referenceCategory, headers] of categories) {
if (headers.includes(header)) {
category = toTitleCase(referenceCategory);
break;
}
}
// Gather info
const result = await command.resolveInfo(args);
if (result.type === "error") return channel.send(result.message);
let append = ""; let append = "";
command = result.command; const command = result.command;
const header = result.args.length > 0 ? `${result.header} ${result.args.join(" ")}` : result.header;
if (result.args.length > 0) header += " " + result.args.join(" ");
if (command.usage === "") { if (command.usage === "") {
const list: string[] = []; const list: string[] = [];
for (const [tag, subcommand] of result.keyedSubcommandInfo) { for (const [tag, subcommand] of result.keyedSubcommandInfo) {
const customUsage = subcommand.usage ? ` ${subcommand.usage}` : ""; const customUsage = subcommand.usage ? ` ${subcommand.usage}` : "";
list.push(`- \`${header} ${tag}${customUsage}\` - ${subcommand.description}`); list.push(` \`${header} ${tag}${customUsage}\` - ${subcommand.description}`);
} }
for (const [type, subcommand] of result.subcommandInfo) { for (const [type, subcommand] of result.subcommandInfo) {
const customUsage = subcommand.usage ? ` ${subcommand.usage}` : ""; const customUsage = subcommand.usage ? ` ${subcommand.usage}` : "";
list.push(`- \`${header} ${type}${customUsage}\` - ${subcommand.description}`); list.push(` \`${header} ${type}${customUsage}\` - ${subcommand.description}`);
} }
append = "Usages:" + (list.length > 0 ? `\n${list.join("\n")}` : " None."); append = list.length > 0 ? list.join("\n") : "None";
} else { } else {
append = `Usage: \`${header} ${command.usage}\``; append = `\`${header} ${command.usage}\``;
} }
let aliases = "N/A"; let aliases = "N/A";
@ -84,13 +67,42 @@ export default new NamedCommand({
aliases = formattedAliases.join(", ") || "None"; aliases = formattedAliases.join(", ") || "None";
} }
return channel.send( return send(
`Command: \`${header}\`\nAliases: ${aliases}\nCategory: \`${category}\`\nPermission Required: \`${getPermissionName( new MessageEmbed()
result.permission .setTitle(header)
)}\` (${result.permission})\nChannel Type: ${getChannelTypeName(result.channelType)}\nNSFW Only: ${ .setDescription(command.description)
result.nsfw ? "Yes" : "No" .setColor(EMBED_COLOR)
}\nDescription: ${command.description}\n${append}`, .addFields(
{split: true} {
name: "Aliases",
value: aliases,
inline: true
},
{
name: "Category",
value: category,
inline: true
},
{
name: "Permission Required",
value: `\`${getPermissionName(result.permission)}\` (Level ${result.permission})`,
inline: true
},
{
name: "Channel Type",
value: getChannelTypeName(result.channelType),
inline: true
},
{
name: "NSFW Only?",
value: result.nsfw ? "Yes" : "No",
inline: true
},
{
name: "Usages",
value: append
}
)
); );
} }
}) })

View File

@ -1,7 +1,7 @@
import {Command, NamedCommand} from "../core"; import {Command, NamedCommand, RestCommand} from "../core";
export default new NamedCommand({ export default new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild, author, member, client, args}) {
// code // code
} }
}); });

View File

@ -1,22 +1,24 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import * as math from "mathjs"; import * as math from "mathjs";
import {MessageEmbed} from "discord.js"; 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}) { run: "Please provide a calculation.",
if (!args[0]) return channel.send("Please provide a calculation."); any: new RestCommand({
let resp; async run({send, combined}) {
try { let resp;
resp = math.evaluate(args.join(" ")); try {
} catch (e) { resp = math.evaluate(combined);
return channel.send("Please provide a *valid* calculation."); } catch (e) {
return send("Please provide a *valid* calculation.");
}
const embed = new MessageEmbed()
.setColor(0xffffff)
.setTitle("Math Calculation")
.addField("Input", `\`\`\`js\n${combined}\`\`\``)
.addField("Output", `\`\`\`js\n${resp}\`\`\``);
return send(embed);
} }
const embed = new MessageEmbed() })
.setColor(0xffffff)
.setTitle("Math Calculation")
.addField("Input", `\`\`\`js\n${args.join("")}\`\`\``)
.addField("Output", `\`\`\`js\n${resp}\`\`\``);
return channel.send(embed);
}
}); });

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand} from "../../core";
export default new NamedCommand({ export default new NamedCommand({
description: "Gives you the Github link.", description: "Gives you the Github link.",

View File

@ -1,19 +1,21 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
export default new NamedCommand({ export default new NamedCommand({
description: "Renames current voice channel.", description: "Renames current voice channel.",
usage: "<name>", usage: "<name>",
async run({message, channel, guild, author, member, client, args}) { run: "Please provide a new voice channel name.",
const voiceChannel = message.member?.voice.channel; any: new RestCommand({
async run({send, message, combined}) {
const voiceChannel = message.member?.voice.channel;
if (!voiceChannel) return channel.send("You are not in a voice channel."); if (!voiceChannel) return send("You are not in a voice channel.");
if (!voiceChannel.guild.me?.hasPermission("MANAGE_CHANNELS")) if (!voiceChannel.guild.me?.hasPermission("MANAGE_CHANNELS"))
return channel.send("I am lacking the required permissions to perform this action."); return 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.");
const prevName = voiceChannel.name; const prevName = voiceChannel.name;
const newName = args.join(" "); const newName = combined;
await voiceChannel.setName(newName); await voiceChannel.setName(newName);
return await channel.send(`Changed channel name from "${prevName}" to "${newName}".`); return await send(`Changed channel name from "${prevName}" to "${newName}".`);
} }
})
}); });

View File

@ -0,0 +1,17 @@
import {NamedCommand, RestCommand} from "../../core";
import {URL} from "url";
import {getContent} from "../../lib";
export default new NamedCommand({
description: "Provides you with info from the Discord.JS docs.",
run: "You need to specify a term to query the docs with.",
any: new RestCommand({
description: "What to query the docs with.",
async run({send, args}) {
var queryString = args[0];
let url = new URL(`https://djsdocs.sorta.moe/v2/embed?src=master&q=${queryString}`);
const content = await getContent(url.toString());
return send({embed: content});
}
})
});

View File

@ -1,15 +1,16 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import {processEmoteQueryFormatted} from "./modules/emote-utils"; import {processEmoteQueryFormatted} from "./modules/emote-utils";
export default new NamedCommand({ export default new NamedCommand({
description: "Send the specified emote.", description:
run: "Please provide a command name.", "Send the specified emote list. Enter + to move an emote list to the next line, - to add a space, and _ to add a zero-width space.",
any: new Command({ run: "Please provide a list of emotes.",
any: new RestCommand({
description: "The emote(s) to send.", description: "The emote(s) to send.",
usage: "<emotes...>", usage: "<emotes...>",
async run({guild, channel, message, args}) { async run({send, args}) {
const output = processEmoteQueryFormatted(args); const output = processEmoteQueryFormatted(args);
if (output.length > 0) channel.send(output); if (output.length > 0) send(output);
} }
}) })
}); });

View File

@ -1,28 +1,28 @@
import {MessageEmbed, version as djsversion, Guild, User, GuildMember} 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, CHANNEL_TYPE} from "../../core"; import {Command, NamedCommand, getMemberByName, CHANNEL_TYPE, getGuildByName, RestCommand} 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.",
async run({message, channel, guild, author, member, client, args}) { async run({send, author, member}) {
channel.send(await getUserInfo(author, member)); 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.",
usage: "(<user>)", usage: "(<user>)",
async run({message, channel, guild, author, member, client, args}) { async run({send, author}) {
channel.send(author.displayAvatarURL({dynamic: true, size: 2048})); send(author.displayAvatarURL({dynamic: true, size: 2048}));
}, },
id: "user", 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({send, args}) {
channel.send( send(
args[0].displayAvatarURL({ args[0].displayAvatarURL({
dynamic: true, dynamic: true,
size: 2048 size: 2048
@ -30,29 +30,28 @@ export default new NamedCommand({
); );
} }
}), }),
any: new Command({ any: new RestCommand({
description: "Shows another user's avatar by searching their name", description: "Shows another user's avatar by searching their name",
channelType: CHANNEL_TYPE.GUILD, channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, client, args}) { async run({send, guild, combined}) {
const name = args.join(" "); const member = await getMemberByName(guild!, combined);
const member = await getMemberByUsername(guild!, name);
if (member) { if (typeof member !== "string") {
channel.send( 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}\`!`); send(member);
} }
} }
}) })
}), }),
bot: new NamedCommand({ bot: new NamedCommand({
description: "Displays info about the bot.", description: "Displays info about the bot.",
async run({message, channel, guild, author, member, client, args}) { async run({send, guild, client}) {
const core = os.cpus()[0]; const core = os.cpus()[0];
const embed = new MessageEmbed() const embed = new MessageEmbed()
.setColor(guild?.me?.displayHexColor || "BLUE") .setColor(guild?.me?.displayHexColor || "BLUE")
@ -88,40 +87,33 @@ export default new NamedCommand({
size: 2048 size: 2048
}); });
if (avatarURL) embed.setThumbnail(avatarURL); if (avatarURL) embed.setThumbnail(avatarURL);
channel.send(embed); send(embed);
} }
}), }),
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, channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({send, guild}) {
channel.send(await getGuildInfo(guild!, guild)); send(await getGuildInfo(guild!, guild));
}, },
any: new Command({ id: "guild",
description: "Display info about a guild by finding its name or ID.", guild: new Command({
async run({message, channel, guild, author, member, client, args}) { description: "Display info about a guild by its ID.",
// If a guild ID is provided (avoid the "number" subcommand because of inaccuracies), search for that guild async run({send, guild, args}) {
if (args.length === 1 && /^\d{17,19}$/.test(args[0])) { const targetGuild = args[0] as Guild;
const id = args[0]; send(await getGuildInfo(targetGuild, guild));
const targetGuild = client.guilds.cache.get(id); }
}),
any: new RestCommand({
description: "Display info about a guild by finding its name.",
async run({send, guild, combined}) {
const targetGuild = getGuildByName(combined);
if (targetGuild) { if (typeof targetGuild !== "string") {
channel.send(await getGuildInfo(targetGuild, guild)); send(await getGuildInfo(targetGuild, guild));
} else {
channel.send(`None of the servers I'm in matches the guild ID \`${id}\`!`);
}
} else { } else {
const query: string = args.join(" ").toLowerCase(); send(targetGuild);
const targetGuild = client.guilds.cache.find((guild) =>
guild.name.toLowerCase().includes(query)
);
if (targetGuild) {
channel.send(await getGuildInfo(targetGuild, guild));
} else {
channel.send(`None of the servers I'm in matches the query \`${query}\`!`);
}
} }
} }
}) })
@ -130,11 +122,11 @@ export default new NamedCommand({
id: "user", 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({send, guild, args}) {
const user = args[0] as User; 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 = guild?.members.resolve(args[0]); const member = guild?.members.resolve(args[0]);
channel.send(await getUserInfo(user, member)); send(await getUserInfo(user, member));
} }
}) })
}); });

View File

@ -1,9 +1,9 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand} from "../../core";
export default new NamedCommand({ export default new NamedCommand({
description: "Gives you the invite link.", description: "Gives you the invite link.",
async run({message, channel, guild, author, member, client, args}) { async run({send, client, args}) {
channel.send( send(
`https://discordapp.com/api/oauth2/authorize?client_id=${client.user!.id}&permissions=${ `https://discordapp.com/api/oauth2/authorize?client_id=${client.user!.id}&permissions=${
args[0] || 8 args[0] || 8
}&scope=bot` }&scope=bot`

View File

@ -1,5 +1,5 @@
import {GuildEmoji, MessageEmbed, TextChannel, DMChannel, NewsChannel, User} from "discord.js"; import {GuildEmoji, MessageEmbed, User} from "discord.js";
import {Command, NamedCommand, paginate} from "../../core"; import {NamedCommand, RestCommand, paginate, SendFunction} from "../../core";
import {split} from "../../lib"; import {split} from "../../lib";
import vm from "vm"; import vm from "vm";
@ -8,20 +8,20 @@ const REGEX_TIMEOUT_MS = 1000;
export default new NamedCommand({ export default new NamedCommand({
description: "Lists all emotes the bot has in it's registry,", description: "Lists all emotes the bot has in it's registry,",
usage: "<regex pattern> (-flags)", usage: "<regex pattern> (-flags)",
async run({message, channel, guild, author, member, client, args}) { async run({send, author, client}) {
displayEmoteList(client.emojis.cache.array(), channel, author); displayEmoteList(client.emojis.cache.array(), send, author);
}, },
any: new Command({ any: new RestCommand({
description: description:
"Filters emotes by via a regular expression. Flags can be added by adding a dash at the end. For example, to do a case-insensitive search, do %prefix%lsemotes somepattern -i", "Filters emotes by via a regular expression. Flags can be added by adding a dash at the end. For example, to do a case-insensitive search, do %prefix%lsemotes somepattern -i",
async run({message, channel, guild, author, member, client, args}) { async run({send, author, client, args}) {
// If a guild ID is provided, filter all emotes by that guild (but only if there aren't any arguments afterward) // If a guild ID is provided, filter all emotes by that guild (but only if there aren't any arguments afterward)
if (args.length === 1 && /^\d{17,19}$/.test(args[0])) { if (args.length === 1 && /^\d{17,}$/.test(args[0])) {
const guildID: string = args[0]; const guildID: string = args[0];
displayEmoteList( displayEmoteList(
client.emojis.cache.filter((emote) => emote.guild.id === guildID).array(), client.emojis.cache.filter((emote) => emote.guild.id === guildID).array(),
channel, send,
author author
); );
} else { } else {
@ -35,7 +35,6 @@ export default new NamedCommand({
let emoteCollection = client.emojis.cache.array(); let emoteCollection = client.emojis.cache.array();
// Creates a sandbox to stop a regular expression if it takes too much time to search. // Creates a sandbox to stop a regular expression if it takes too much time to search.
// To avoid passing in a giant data structure, I'll just pass in the structure {[id: string]: [name: string]}. // To avoid passing in a giant data structure, I'll just pass in the structure {[id: string]: [name: string]}.
//let emotes: {[id: string]: string} = {};
let emotes = new Map<string, string>(); let emotes = new Map<string, string>();
for (const emote of emoteCollection) { for (const emote of emoteCollection) {
@ -58,10 +57,10 @@ export default new NamedCommand({
script.runInContext(context, {timeout: REGEX_TIMEOUT_MS}); script.runInContext(context, {timeout: REGEX_TIMEOUT_MS});
emotes = sandbox.emotes; emotes = sandbox.emotes;
emoteCollection = emoteCollection.filter((emote) => emotes.has(emote.id)); // Only allow emotes that haven't been deleted. emoteCollection = emoteCollection.filter((emote) => emotes.has(emote.id)); // Only allow emotes that haven't been deleted.
displayEmoteList(emoteCollection, channel, author); displayEmoteList(emoteCollection, send, author);
} catch (error) { } catch (error) {
if (error.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") { if (error.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") {
channel.send( send(
`The regular expression you entered exceeded the time limit of ${REGEX_TIMEOUT_MS} milliseconds.` `The regular expression you entered exceeded the time limit of ${REGEX_TIMEOUT_MS} milliseconds.`
); );
} else { } else {
@ -69,14 +68,14 @@ export default new NamedCommand({
} }
} }
} else { } else {
channel.send("Failed to initialize sandbox."); send("Failed to initialize sandbox.");
} }
} }
} }
}) })
}); });
async function displayEmoteList(emotes: GuildEmoji[], channel: TextChannel | DMChannel | NewsChannel, author: User) { async function displayEmoteList(emotes: GuildEmoji[], send: SendFunction, author: User) {
emotes.sort((a, b) => { emotes.sort((a, b) => {
const first = a.name.toLowerCase(); const first = a.name.toLowerCase();
const second = b.name.toLowerCase(); const second = b.name.toLowerCase();
@ -91,7 +90,7 @@ async function displayEmoteList(emotes: GuildEmoji[], channel: TextChannel | DMC
// Gather the first page (if it even exists, which it might not if there no valid emotes appear) // Gather the first page (if it even exists, which it might not if there no valid emotes appear)
if (pages > 0) { if (pages > 0) {
paginate(channel, author.id, pages, (page, hasMultiplePages) => { paginate(send, author.id, pages, (page, hasMultiplePages) => {
embed.setTitle(hasMultiplePages ? `**Emotes** (Page ${page + 1} of ${pages})` : "**Emotes**"); embed.setTitle(hasMultiplePages ? `**Emotes** (Page ${page + 1} of ${pages})` : "**Emotes**");
let desc = ""; let desc = "";
@ -103,6 +102,6 @@ async function displayEmoteList(emotes: GuildEmoji[], channel: TextChannel | DMC
return embed; return embed;
}); });
} else { } else {
channel.send("No valid emotes found by that query."); send("No valid emotes found by that query.");
} }
} }

View File

@ -76,6 +76,7 @@ function processEmoteQuery(query: string[], isFormatted: boolean): string[] {
if (isFormatted) { if (isFormatted) {
if (emote == "-") return " "; if (emote == "-") return " ";
if (emote == "+") return "\n"; if (emote == "+") return "\n";
if (emote == "_") return "\u200b";
} }
// Selector number used for disambiguating multiple emotes with same name. // Selector number used for disambiguating multiple emotes with same name.

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import {Message, Channel, TextChannel} from "discord.js"; import {Message, Channel, TextChannel} from "discord.js";
import {processEmoteQueryArray} from "./modules/emote-utils"; import {processEmoteQueryArray} from "./modules/emote-utils";
@ -6,109 +6,112 @@ export default new NamedCommand({
description: description:
"Reacts to the a previous message in your place. You have to react with the same emote before the bot removes that reaction.", "Reacts to the a previous message in your place. You have to react with the same emote before the bot removes that reaction.",
usage: 'react <emotes...> (<distance / message ID / "Copy ID" / "Copy Message Link">)', usage: 'react <emotes...> (<distance / message ID / "Copy ID" / "Copy Message Link">)',
async run({message, channel, guild, author, member, client, args}) { run: "You need to enter some emotes first.",
let target: Message | undefined; any: new RestCommand({
let distance = 1; async run({send, message, channel, guild, client, args}) {
let target: Message | undefined;
let distance = 1;
if (message.reference) { if (message.reference) {
// If the command message is a reply to another message, use that as the react target. // If the command message is a reply to another message, use that as the react target.
target = await channel.messages.fetch(message.reference.messageID!); target = await channel.messages.fetch(message.reference.messageID!);
} }
// handles reacts by message id/distance // handles reacts by message id/distance
else if (args.length >= 2) { else if (args.length >= 2) {
const last = args[args.length - 1]; // Because this is optional, do not .pop() unless you're sure it's a message link indicator. const last = args[args.length - 1]; // Because this is optional, do not .pop() unless you're sure it's a message link indicator.
const URLPattern = /^(?:https:\/\/discord.com\/channels\/(\d{17,19})\/(\d{17,19})\/(\d{17,19}))$/; const URLPattern = /^(?:https:\/\/discord.com\/channels\/(\d{17,})\/(\d{17,})\/(\d{17,}))$/;
const copyIDPattern = /^(?:(\d{17,19})-(\d{17,19}))$/; const copyIDPattern = /^(?:(\d{17,})-(\d{17,}))$/;
// https://discord.com/channels/<Guild ID>/<Channel ID>/<Message ID> ("Copy Message Link" Button) // https://discord.com/channels/<Guild ID>/<Channel ID>/<Message ID> ("Copy Message Link" Button)
if (URLPattern.test(last)) { if (URLPattern.test(last)) {
const match = URLPattern.exec(last)!; const match = URLPattern.exec(last)!;
const guildID = match[1]; const guildID = match[1];
const channelID = match[2]; const channelID = match[2];
const messageID = match[3]; const messageID = match[3];
let tmpChannel: Channel | undefined = channel; let tmpChannel: Channel | undefined = channel;
if (guild?.id !== guildID) { if (guild?.id !== guildID) {
try { try {
guild = await client.guilds.fetch(guildID); guild = await client.guilds.fetch(guildID);
} catch { } catch {
return channel.send(`\`${guildID}\` is an invalid guild ID!`); return send(`\`${guildID}\` is an invalid guild ID!`);
}
} }
}
if (tmpChannel.id !== channelID) tmpChannel = guild.channels.cache.get(channelID); if (tmpChannel.id !== channelID) tmpChannel = guild.channels.cache.get(channelID);
if (!tmpChannel) return channel.send(`\`${channelID}\` is an invalid channel ID!`); if (!tmpChannel) return send(`\`${channelID}\` is an invalid channel ID!`);
if (message.id !== messageID) { if (message.id !== messageID) {
try { try {
target = await (tmpChannel as TextChannel).messages.fetch(messageID); target = await (tmpChannel as TextChannel).messages.fetch(messageID);
} catch { } catch {
return channel.send(`\`${messageID}\` is an invalid message ID!`); return send(`\`${messageID}\` is an invalid message ID!`);
}
} }
args.pop();
} }
// <Channel ID>-<Message ID> ("Copy ID" Button)
else if (copyIDPattern.test(last)) {
const match = copyIDPattern.exec(last)!;
const channelID = match[1];
const messageID = match[2];
let tmpChannel: Channel | undefined = channel;
args.pop(); if (tmpChannel.id !== channelID) tmpChannel = guild?.channels.cache.get(channelID);
} if (!tmpChannel) return send(`\`${channelID}\` is an invalid channel ID!`);
// <Channel ID>-<Message ID> ("Copy ID" Button)
else if (copyIDPattern.test(last)) {
const match = copyIDPattern.exec(last)!;
const channelID = match[1];
const messageID = match[2];
let tmpChannel: Channel | undefined = channel;
if (tmpChannel.id !== channelID) tmpChannel = guild?.channels.cache.get(channelID); if (message.id !== messageID) {
if (!tmpChannel) return channel.send(`\`${channelID}\` is an invalid channel ID!`); try {
target = await (tmpChannel as TextChannel).messages.fetch(messageID);
if (message.id !== messageID) { } catch {
try { return send(`\`${messageID}\` is an invalid message ID!`);
target = await (tmpChannel as TextChannel).messages.fetch(messageID); }
} catch {
return channel.send(`\`${messageID}\` is an invalid message ID!`);
} }
args.pop();
} }
// <Message ID>
else if (/^\d{17,}$/.test(last)) {
try {
target = await channel.messages.fetch(last);
} catch {
return send(`No valid message found by the ID \`${last}\`!`);
}
args.pop(); args.pop();
}
// <Message ID>
else if (/^\d{17,19}$/.test(last)) {
try {
target = await channel.messages.fetch(last);
} catch {
return channel.send(`No valid message found by the ID \`${last}\`!`);
} }
// The entire string has to be a number for this to match. Prevents leaCheeseAmerican1 from triggering this.
else if (/^\d+$/.test(last)) {
distance = parseInt(last);
args.pop(); if (distance >= 0 && distance <= 99) args.pop();
else return send("Your distance must be between 0 and 99!");
}
} }
// The entire string has to be a number for this to match. Prevents leaCheeseAmerican1 from triggering this.
else if (/^\d+$/.test(last)) {
distance = parseInt(last);
if (distance >= 0 && distance <= 99) args.pop(); if (!target) {
else return channel.send("Your distance must be between 0 and 99!"); // Messages are ordered from latest to earliest.
// You also have to add 1 as well because fetchMessages includes your own message.
target = (
await message.channel.messages.fetch({
limit: distance + 1
})
).last();
} }
for (const emote of processEmoteQueryArray(args)) {
// Even though the bot will always grab *some* emote, the user can choose not to keep that emote there if it isn't what they want
const reaction = await target!.react(emote);
// This part is called with a promise because you don't want to wait 5 seconds between each reaction.
setTimeout(() => {
// This reason for this null assertion is that by the time you use this command, the client is going to be loaded.
reaction.users.remove(client.user!);
}, 5000);
}
return;
} }
})
if (!target) {
// Messages are ordered from latest to earliest.
// You also have to add 1 as well because fetchMessages includes your own message.
target = (
await message.channel.messages.fetch({
limit: distance + 1
})
).last();
}
for (const emote of processEmoteQueryArray(args)) {
// Even though the bot will always grab *some* emote, the user can choose not to keep that emote there if it isn't what they want
const reaction = await target!.react(emote);
// This part is called with a promise because you don't want to wait 5 seconds between each reaction.
setTimeout(() => {
// This reason for this null assertion is that by the time you use this command, the client is going to be loaded.
reaction.users.remove(client.user!);
}, 5000);
}
return;
}
}); });

View File

@ -1,13 +1,13 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
export default new NamedCommand({ export default new NamedCommand({
description: "Repeats your message.", description: "Repeats your message.",
usage: "<message>", usage: "<message>",
run: "Please provide a message for me to say!", run: "Please provide a message for me to say!",
any: new Command({ any: new RestCommand({
description: "Message to repeat.", description: "Message to repeat.",
async run({message, channel, guild, author, member, client, args}) { async run({send, author, combined}) {
channel.send(`*${author} says:*\n${args.join(" ")}`); send(`*${author} says:*\n${combined}`);
} }
}) })
}); });

View File

@ -1,28 +1,26 @@
import {Command, NamedCommand, CHANNEL_TYPE} from "../../core"; import {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";
const lastUsedTimestamps: {[id: string]: number} = {}; const lastUsedTimestamps = new Collection<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, channelType: CHANNEL_TYPE.GUILD,
async run({message, channel, guild, author, member, client, args}) { async run({send, message, channel, guild}) {
// 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.get(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)
return channel.send( return 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}.` else lastUsedTimestamps.set(guild!.id, startTime);
);
else lastUsedTimestamps[guild!.id] = startTime;
const stats: { const stats: {
[id: string]: { [id: string]: {
@ -41,7 +39,7 @@ export default new NamedCommand({
let channelsSearched = 0; let channelsSearched = 0;
let currentChannelName = ""; let currentChannelName = "";
const totalChannels = allTextChannelsInCurrentGuild.size; const totalChannels = allTextChannelsInCurrentGuild.size;
const statusMessage = await channel.send("Gathering emotes..."); const statusMessage = await send("Gathering emotes...");
let warnings = 0; let warnings = 0;
channel.startTyping(); channel.startTyping();
@ -181,6 +179,16 @@ export default new NamedCommand({
); );
} }
return await channel.send(lines, {split: true}); return await send(lines, {split: true});
},
subcommands: {
forcereset: new NamedCommand({
description: "Forces the cooldown timer to reset.",
permission: PERMISSIONS.BOT_SUPPORT,
async run({send, guild}) {
lastUsedTimestamps.set(guild!.id, 0);
send("Reset the cooldown on `scanemotes`.");
}
})
} }
}); });

View File

@ -5,14 +5,14 @@ export default new NamedCommand({
description: "Shortens a given URL.", description: "Shortens a given URL.",
run: "Please provide a URL.", run: "Please provide a URL.",
any: new Command({ any: new Command({
async run({message, channel, guild, author, member, client, args}) { async run({send, args}) {
https.get("https://is.gd/create.php?format=simple&url=" + encodeURIComponent(args[0]), function (res) { https.get("https://is.gd/create.php?format=simple&url=" + encodeURIComponent(args[0]), function (res) {
var body = ""; var body = "";
res.on("data", function (chunk) { res.on("data", function (chunk) {
body += chunk; body += chunk;
}); });
res.on("end", function () { res.on("end", function () {
channel.send(`<${body}>`); send(`<${body}>`);
}); });
}); });
} }

View File

@ -1,25 +1,44 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import {streamList} from "../../modules/streamNotifications"; import {streamList} from "../../modules/streamNotifications";
export default new NamedCommand({ export default new NamedCommand({
description: "Sets the description of your stream. You can embed links by writing `[some name](some link)`", description: "Sets the description of your stream. You can embed links by writing `[some name](some link)`",
async run({message, channel, guild, author, member, client, args}) { async run({send, author, member}) {
const userID = author.id; const userID = author.id;
if (streamList.has(userID)) { if (streamList.has(userID)) {
const stream = streamList.get(userID)!; const stream = streamList.get(userID)!;
const description = args.join(" ") || "No description set."; stream.description = "No description set.";
stream.description = description;
stream.update(); stream.update();
channel.send(`Successfully set the stream description to:`, { send(`Successfully set the stream description to:`, {
embed: { embed: {
description, description: "No description set.",
color: member!.displayColor color: member!.displayColor
} }
}); });
} else { } else {
// Alternatively, I could make descriptions last outside of just one stream. // Alternatively, I could make descriptions last outside of just one stream.
channel.send("You can only use this command when streaming."); send("You can only use this command when streaming.");
} }
} },
any: new RestCommand({
async run({send, author, member, combined}) {
const userID = author.id;
if (streamList.has(userID)) {
const stream = streamList.get(userID)!;
stream.description = combined;
stream.update();
send(`Successfully set the stream description to:`, {
embed: {
description: stream.description,
color: member!.displayColor
}
});
} else {
// Alternatively, I could make descriptions last outside of just one stream.
send("You can only use this command when streaming.");
}
}
})
}); });

View File

@ -1,4 +1,4 @@
import {Command, NamedCommand, ask, askYesOrNo, askMultipleChoice, prompt, callMemberByUsername} from "../../core"; import {Command, NamedCommand, askForReply, confirm, askMultipleChoice, getMemberByName, RestCommand} from "../../core";
import {Storage} from "../../structures"; import {Storage} from "../../structures";
import {User} from "discord.js"; import {User} from "discord.js";
import moment from "moment"; import moment from "moment";
@ -169,186 +169,187 @@ function getTimeEmbed(user: User) {
export default new NamedCommand({ export default new NamedCommand({
description: "Show others what time it is for you.", description: "Show others what time it is for you.",
aliases: ["tz"], aliases: ["tz"],
async run({channel, author}) { async run({send, author}) {
channel.send(getTimeEmbed(author)); send(getTimeEmbed(author));
}, },
subcommands: { subcommands: {
// Welcome to callback hell. We hope you enjoy your stay here! // Welcome to callback hell. We hope you enjoy your stay here!
setup: new NamedCommand({ setup: new NamedCommand({
description: "Registers your timezone information for the bot.", description: "Registers your timezone information for the bot.",
async run({author, channel}) { async run({send, author}) {
const profile = Storage.getUser(author.id); const profile = Storage.getUser(author.id);
profile.timezone = null; profile.timezone = null;
profile.daylightSavingsRegion = null; profile.daylightSavingsRegion = null;
let hour: number;
ask( // Parse and validate reply
await channel.send( const reply = await askForReply(
await send(
"What hour (0 to 23) is it for you right now?\n*(Note: Make sure to use Discord's inline reply feature or this won't work!)*" "What hour (0 to 23) is it for you right now?\n*(Note: Make sure to use Discord's inline reply feature or this won't work!)*"
), ),
author.id, author.id,
(reply) => { 30000
hour = parseInt(reply);
if (isNaN(hour)) {
return false;
}
return hour >= 0 && hour <= 23;
},
async () => {
// You need to also take into account whether or not it's the same day in UTC or not.
// The problem this setup avoids is messing up timezones by 24 hours.
// For example, the old logic was just (hour - hourUTC). When I setup my timezone (UTC-6) at 18:00, it was UTC 00:00.
// That means that that formula was doing (18 - 0) getting me UTC+18 instead of UTC-6 because that naive formula didn't take into account a difference in days.
// (day * 24 + hour) - (day * 24 + hour)
// Since the timezones will be restricted to -12 to +14, you'll be given three options.
// The end of the month should be calculated automatically, you should have enough information at that point.
// But after mapping out the edge cases, I figured out that you can safely gather accurate information just based on whether the UTC day matches the user's day.
// 21:xx (-12, -d) -- 09:xx (+0, 0d) -- 23:xx (+14, 0d)
// 22:xx (-12, -d) -- 10:xx (+0, 0d) -- 00:xx (+14, +d)
// 23:xx (-12, -d) -- 11:xx (+0, 0d) -- 01:xx (+14, +d)
// 00:xx (-12, 0d) -- 12:xx (+0, 0d) -- 02:xx (+14, +d)
// For example, 23:xx (-12) - 01:xx (+14) shows that even the edge cases of UTC-12 and UTC+14 cannot overlap, so the dataset can be reduced to a yes or no option.
// - 23:xx same day = +0, 23:xx diff day = -1
// - 00:xx same day = +0, 00:xx diff day = +1
// - 01:xx same day = +0, 01:xx diff day = +1
// First, create a tuple list matching each possible hour-dayOffset-timezoneOffset combination. In the above example, it'd go something like this:
// [[23, -1, -12], [0, 0, -11], ..., [23, 0, 12], [0, 1, 13], [1, 1, 14]]
// Then just find the matching one by filtering through dayOffset (equals zero or not), then the hour from user input.
// Remember that you don't know where the difference in day might be at this point, so you can't do (hour - hourUTC) safely.
// In terms of the equation, you're missing a variable in (--> day <-- * 24 + hour) - (day * 24 + hour). That's what the loop is for.
// Now you might be seeing a problem with setting this up at the end/beginning of a month, but that actually isn't a problem.
// Let's say that it's 00:xx of the first UTC day of a month. hourSumUTC = 24
// UTC-12 --> hourSumLowerBound (hourSumUTC - 12) = 12
// UTC+14 --> hourSumUpperBound (hourSumUTC + 14) = 38
// Remember, the nice thing about making these bounds relative to the UTC hour sum is that there can't be any conflicts even at the edges of months.
// And remember that we aren't using this question: (day * 24 + hour) - (day * 24 + hour). We're drawing from a list which does not store its data in absolute terms.
// That means there's no 31st, 1st, 2nd, it's -1, 0, +1. I just need to make sure to calculate an offset to subtract from the hour sums.
const date = new Date(); // e.g. 2021-05-01 @ 05:00
const day = date.getUTCDate(); // e.g. 1
const hourSumUTC = day * 24 + date.getUTCHours(); // e.g. 29
const timezoneTupleList: [number, number, number][] = [];
const uniques: number[] = []; // only for temporary use
const duplicates = [];
// Setup the tuple list in a separate block.
for (let timezoneOffset = -12; timezoneOffset <= 14; timezoneOffset++) {
const hourSum = hourSumUTC + timezoneOffset; // e.g. 23, UTC-6 (17 to 43)
const hour = hourSum % 24; // e.g. 23
// This works because you get the # of days w/o hours minus UTC days without hours.
// Since it's all relative to UTC, it'll end up being -1, 0, or 1.
const dayOffset = Math.floor(hourSum / 24) - day; // e.g. -1
timezoneTupleList.push([hour, dayOffset, timezoneOffset]);
if (uniques.includes(hour)) {
duplicates.push(hour);
} else {
uniques.push(hour);
}
}
// I calculate the list beforehand and check for duplicates to reduce unnecessary asking.
if (duplicates.includes(hour)) {
const isSameDay = await askYesOrNo(
await channel.send(
`Is the current day of the month the ${moment().utc().format("Do")} for you?`
),
author.id
);
// Filter through isSameDay (aka !hasDayOffset) then hour from user-generated input.
// isSameDay is checked first to reduce the amount of conditionals per loop.
if (isSameDay) {
for (const [hourPoint, dayOffset, timezoneOffset] of timezoneTupleList) {
if (dayOffset === 0 && hour === hourPoint) {
profile.timezone = timezoneOffset;
}
}
} else {
for (const [hourPoint, dayOffset, timezoneOffset] of timezoneTupleList) {
if (dayOffset !== 0 && hour === hourPoint) {
profile.timezone = timezoneOffset;
}
}
}
} else {
// If it's a unique hour, just search through the tuple list and find the matching entry.
for (const [hourPoint, dayOffset, timezoneOffset] of timezoneTupleList) {
if (hour === hourPoint) {
profile.timezone = timezoneOffset;
}
}
}
// I should note that error handling should be added sometime because await throws an exception on Promise.reject.
const hasDST = await askYesOrNo(
await channel.send("Does your timezone change based on daylight savings?"),
author.id
);
const finalize = () => {
Storage.save();
channel.send(
"You've finished setting up your timezone! Just check to see if this looks right, and if it doesn't, run this setup again.",
getTimeEmbed(author)
);
};
if (hasDST) {
const finalizeDST = (region: DST) => {
profile.daylightSavingsRegion = region;
// If daylight savings is active, subtract the timezone offset by one to store the standard time.
if (hasDaylightSavings(region)) {
profile.timezone!--;
}
finalize();
};
askMultipleChoice(await channel.send(DST_NOTE_SETUP), author.id, [
() => finalizeDST("na"),
() => finalizeDST("eu"),
() => finalizeDST("sh")
]);
} else {
finalize();
}
},
() => "you need to enter in a valid integer between 0 to 23"
); );
if (reply === null) return send("Message timed out.");
const hour = parseInt(reply.content);
const isValidHour = !isNaN(hour) && hour >= 0 && hour <= 23;
if (!isValidHour) return reply.reply("you need to enter in a valid integer between 0 to 23");
// You need to also take into account whether or not it's the same day in UTC or not.
// The problem this setup avoids is messing up timezones by 24 hours.
// For example, the old logic was just (hour - hourUTC). When I setup my timezone (UTC-6) at 18:00, it was UTC 00:00.
// That means that that formula was doing (18 - 0) getting me UTC+18 instead of UTC-6 because that naive formula didn't take into account a difference in days.
// (day * 24 + hour) - (day * 24 + hour)
// Since the timezones will be restricted to -12 to +14, you'll be given three options.
// The end of the month should be calculated automatically, you should have enough information at that point.
// But after mapping out the edge cases, I figured out that you can safely gather accurate information just based on whether the UTC day matches the user's day.
// 21:xx (-12, -d) -- 09:xx (+0, 0d) -- 23:xx (+14, 0d)
// 22:xx (-12, -d) -- 10:xx (+0, 0d) -- 00:xx (+14, +d)
// 23:xx (-12, -d) -- 11:xx (+0, 0d) -- 01:xx (+14, +d)
// 00:xx (-12, 0d) -- 12:xx (+0, 0d) -- 02:xx (+14, +d)
// For example, 23:xx (-12) - 01:xx (+14) shows that even the edge cases of UTC-12 and UTC+14 cannot overlap, so the dataset can be reduced to a yes or no option.
// - 23:xx same day = +0, 23:xx diff day = -1
// - 00:xx same day = +0, 00:xx diff day = +1
// - 01:xx same day = +0, 01:xx diff day = +1
// First, create a tuple list matching each possible hour-dayOffset-timezoneOffset combination. In the above example, it'd go something like this:
// [[23, -1, -12], [0, 0, -11], ..., [23, 0, 12], [0, 1, 13], [1, 1, 14]]
// Then just find the matching one by filtering through dayOffset (equals zero or not), then the hour from user input.
// Remember that you don't know where the difference in day might be at this point, so you can't do (hour - hourUTC) safely.
// In terms of the equation, you're missing a variable in (--> day <-- * 24 + hour) - (day * 24 + hour). That's what the loop is for.
// Now you might be seeing a problem with setting this up at the end/beginning of a month, but that actually isn't a problem.
// Let's say that it's 00:xx of the first UTC day of a month. hourSumUTC = 24
// UTC-12 --> hourSumLowerBound (hourSumUTC - 12) = 12
// UTC+14 --> hourSumUpperBound (hourSumUTC + 14) = 38
// Remember, the nice thing about making these bounds relative to the UTC hour sum is that there can't be any conflicts even at the edges of months.
// And remember that we aren't using this question: (day * 24 + hour) - (day * 24 + hour). We're drawing from a list which does not store its data in absolute terms.
// That means there's no 31st, 1st, 2nd, it's -1, 0, +1. I just need to make sure to calculate an offset to subtract from the hour sums.
const date = new Date(); // e.g. 2021-05-01 @ 05:00
const day = date.getUTCDate(); // e.g. 1
const hourSumUTC = day * 24 + date.getUTCHours(); // e.g. 29
const timezoneTupleList: [number, number, number][] = [];
const uniques: number[] = []; // only for temporary use
const duplicates = [];
// Setup the tuple list in a separate block.
for (let timezoneOffset = -12; timezoneOffset <= 14; timezoneOffset++) {
const hourSum = hourSumUTC + timezoneOffset; // e.g. 23, UTC-6 (17 to 43)
const hour = hourSum % 24; // e.g. 23
// This works because you get the # of days w/o hours minus UTC days without hours.
// Since it's all relative to UTC, it'll end up being -1, 0, or 1.
const dayOffset = Math.floor(hourSum / 24) - day; // e.g. -1
timezoneTupleList.push([hour, dayOffset, timezoneOffset]);
if (uniques.includes(hour)) {
duplicates.push(hour);
} else {
uniques.push(hour);
}
}
// I calculate the list beforehand and check for duplicates to reduce unnecessary asking.
if (duplicates.includes(hour)) {
const isSameDay = await confirm(
await send(`Is the current day of the month the ${moment().utc().format("Do")} for you?`),
author.id
);
// Filter through isSameDay (aka !hasDayOffset) then hour from user-generated input.
// isSameDay is checked first to reduce the amount of conditionals per loop.
if (isSameDay) {
for (const [hourPoint, dayOffset, timezoneOffset] of timezoneTupleList) {
if (dayOffset === 0 && hour === hourPoint) {
profile.timezone = timezoneOffset;
}
}
} else {
for (const [hourPoint, dayOffset, timezoneOffset] of timezoneTupleList) {
if (dayOffset !== 0 && hour === hourPoint) {
profile.timezone = timezoneOffset;
}
}
}
} else {
// If it's a unique hour, just search through the tuple list and find the matching entry.
for (const [hourPoint, _dayOffset, timezoneOffset] of timezoneTupleList) {
if (hour === hourPoint) {
profile.timezone = timezoneOffset;
}
}
}
// I should note that error handling should be added sometime because await throws an exception on Promise.reject.
const hasDST = await confirm(
await send("Does your timezone change based on daylight savings?"),
author.id
);
const finalize = () => {
Storage.save();
send(
"You've finished setting up your timezone! Just check to see if this looks right, and if it doesn't, run this setup again.",
getTimeEmbed(author)
);
};
if (hasDST) {
const finalizeDST = (region: DST) => {
profile.daylightSavingsRegion = region;
// If daylight savings is active, subtract the timezone offset by one to store the standard time.
if (hasDaylightSavings(region)) {
profile.timezone!--;
}
finalize();
};
const index = await askMultipleChoice(await send(DST_NOTE_SETUP), author.id, 3);
switch (index) {
case 0:
finalizeDST("na");
break;
case 1:
finalizeDST("eu");
break;
case 2:
finalizeDST("sh");
break;
}
} else {
finalize();
}
return;
} }
}), }),
delete: new NamedCommand({ delete: new NamedCommand({
description: "Delete your timezone information.", description: "Delete your timezone information.",
async run({channel, author}) { async run({send, author}) {
prompt( const result = await confirm(
await channel.send( await send("Are you sure you want to delete your timezone information?"),
"Are you sure you want to delete your timezone information?\n*(This message will automatically be deleted after 10 seconds.)*" author.id
),
author.id,
() => {
const profile = Storage.getUser(author.id);
profile.timezone = null;
profile.daylightSavingsRegion = null;
Storage.save();
}
); );
if (result) {
const profile = Storage.getUser(author.id);
profile.timezone = null;
profile.daylightSavingsRegion = null;
Storage.save();
}
} }
}), }),
utc: new NamedCommand({ utc: new NamedCommand({
description: "Displays UTC time.", description: "Displays UTC time.",
async run({channel}) { async run({send}) {
const time = moment().utc(); const time = moment().utc();
channel.send({ send({
embed: { embed: {
color: TIME_EMBED_COLOR, color: TIME_EMBED_COLOR,
fields: [ fields: [
@ -377,16 +378,16 @@ export default new NamedCommand({
id: "user", 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({send, args}) {
channel.send(getTimeEmbed(args[0])); send(getTimeEmbed(args[0]));
} }
}), }),
any: new Command({ any: new RestCommand({
description: "See what time it is for someone else (by their username).", description: "See what time it is for someone else (by their username).",
async run({channel, args, message}) { async run({send, guild, combined}) {
callMemberByUsername(message, args.join(" "), (member) => { const member = await getMemberByName(guild!, combined);
channel.send(getTimeEmbed(member.user)); if (typeof member !== "string") send(getTimeEmbed(member.user));
}); else send(member);
} }
}) })
}); });

View File

@ -1,11 +1,11 @@
import {Command, NamedCommand} from "../../core"; import {NamedCommand, RestCommand} from "../../core";
import moment from "moment"; import moment from "moment";
import {Storage} from "../../structures"; import {Storage} from "../../structures";
import {MessageEmbed} from "discord.js"; import {MessageEmbed} from "discord.js";
export default new NamedCommand({ export default new NamedCommand({
description: "Keep and edit your personal todo list.", description: "Keep and edit your personal todo list.",
async run({message, channel, guild, author, member, client, args}) { async run({send, author}) {
const user = Storage.getUser(author.id); const user = Storage.getUser(author.id);
const embed = new MessageEmbed().setTitle(`Todo list for ${author.tag}`).setColor("BLUE"); const embed = new MessageEmbed().setTitle(`Todo list for ${author.tag}`).setColor("BLUE");
@ -17,45 +17,48 @@ export default new NamedCommand({
); );
} }
channel.send(embed); send(embed);
}, },
subcommands: { subcommands: {
add: new NamedCommand({ add: new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { run: "You need to specify a note to add.",
const user = Storage.getUser(author.id); any: new RestCommand({
const note = args.join(" "); async run({send, author, combined}) {
user.todoList[Date.now().toString()] = note; const user = Storage.getUser(author.id);
console.debug(user.todoList); user.todoList[Date.now().toString()] = combined;
Storage.save(); Storage.save();
channel.send(`Successfully added \`${note}\` to your todo list.`); send(`Successfully added \`${combined}\` to your todo list.`);
} }
})
}), }),
remove: new NamedCommand({ remove: new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { run: "You need to specify a note to remove.",
const user = Storage.getUser(author.id); any: new RestCommand({
const note = args.join(" "); async run({send, author, combined}) {
let isFound = false; const user = Storage.getUser(author.id);
let isFound = false;
for (const timestamp in user.todoList) { for (const timestamp in user.todoList) {
const selectedNote = user.todoList[timestamp]; const selectedNote = user.todoList[timestamp];
if (selectedNote === note) { if (selectedNote === combined) {
delete user.todoList[timestamp]; delete user.todoList[timestamp];
Storage.save(); Storage.save();
isFound = true; isFound = true;
channel.send(`Removed \`${note}\` from your todo list.`); send(`Removed \`${combined}\` from your todo list.`);
}
} }
}
if (!isFound) channel.send("That item couldn't be found."); if (!isFound) send("That item couldn't be found.");
} }
})
}), }),
clear: new NamedCommand({ clear: new NamedCommand({
async run({message, channel, guild, author, member, client, args}) { async run({send, author}) {
const user = Storage.getUser(author.id); const user = Storage.getUser(author.id);
user.todoList = {}; user.todoList = {};
Storage.save(); Storage.save();
channel.send("Cleared todo list."); send("Cleared todo list.");
} }
}) })
} }

View File

@ -1,38 +1,43 @@
import {Command, NamedCommand} from "../../core"; import {Command, NamedCommand, RestCommand} from "../../core";
// Anycasting Alert import translate from "translate-google";
const translate = require("translate-google");
export default new NamedCommand({ export default new NamedCommand({
description: "Translates your input.", description: "Translates your input.",
usage: "<lang ID> <input>", usage: "<lang ID> <input>",
async run({message, channel, guild, author, member, client, args}) { run: "You need to specify a language to translate to.",
const lang = args[0]; any: new Command({
const input = args.slice(1).join(" "); run: "You need to enter some text to translate.",
translate(input, { any: new RestCommand({
to: lang async run({send, args}) {
}) const lang = args[0];
.then((res: any) => { const input = args.slice(1).join(" ");
channel.send({ translate(input, {
embed: { to: lang
title: "Translation", })
fields: [ .then((res) => {
{ send({
name: "Input", embed: {
value: `\`\`\`${input}\`\`\`` title: "Translation",
}, fields: [
{ {
name: "Output", name: "Input",
value: `\`\`\`${res}\`\`\`` value: `\`\`\`${input}\`\`\``
},
{
name: "Output",
value: `\`\`\`${res}\`\`\``
}
]
} }
] });
} })
}); .catch((error) => {
}) console.error(error);
.catch((err: any) => { send(
console.error(err); `${error}\nPlease use the following list: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes`
channel.send( );
`${err}\nPlease use the following list: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes` });
); }
}); })
} })
}); });

View File

@ -8,9 +8,10 @@ import {
Guild, Guild,
User, User,
GuildMember, GuildMember,
GuildChannel GuildChannel,
Channel
} from "discord.js"; } from "discord.js";
import {SingleMessageOptions} from "./libd"; import {getChannelByID, getGuildByID, getMessageByID, getUserByID, SendFunction} from "./libd";
import {hasPermission, getPermissionLevel, getPermissionName} from "./permissions"; import {hasPermission, getPermissionLevel, getPermissionName} from "./permissions";
import {getPrefix} from "./interface"; import {getPrefix} from "./interface";
import {parseVars, requireAllCasesHandledFor} from "../lib"; import {parseVars, requireAllCasesHandledFor} from "../lib";
@ -30,18 +31,20 @@ import {parseVars, requireAllCasesHandledFor} from "../lib";
*/ */
// RegEx patterns used for identifying/extracting each type from a string argument. // RegEx patterns used for identifying/extracting each type from a string argument.
// The reason why \d{17,} is used is because the max safe number for JS numbers is 16 characters when stringified (decimal). Beyond that are IDs.
const patterns = { const patterns = {
channel: /^<#(\d{17,19})>$/, channel: /^<#(\d{17,})>$/,
role: /^<@&(\d{17,19})>$/, role: /^<@&(\d{17,})>$/,
emote: /^<a?:.*?:(\d{17,19})>$/, emote: /^<a?:.*?:(\d{17,})>$/,
messageLink: /^https?:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/channels\/(?:\d{17,19}|@me)\/(\d{17,19})\/(\d{17,19})$/, // The message type won't include <username>#<tag>. At that point, you may as well just use a search usernames function. Even then, tags would only be taken into account to differentiate different users with identical usernames.
messagePair: /^(\d{17,19})-(\d{17,19})$/, messageLink: /^https?:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/channels\/(?:\d{17,}|@me)\/(\d{17,})\/(\d{17,})$/,
user: /^<@!?(\d{17,19})>$/, messagePair: /^(\d{17,})-(\d{17,})$/,
id: /^(\d{17,19})$/ user: /^<@!?(\d{17,})>$/,
id: /^(\d{17,})$/
}; };
// Maybe add a guild redirect... somehow? // Maybe add a guild redirect... somehow?
type ID = "channel" | "role" | "emote" | "message" | "user"; type ID = "channel" | "role" | "emote" | "message" | "user" | "guild";
// Callbacks don't work with discriminated unions: // Callbacks don't work with discriminated unions:
// - https://github.com/microsoft/TypeScript/issues/41759 // - https://github.com/microsoft/TypeScript/issues/41759
@ -65,40 +68,41 @@ interface CommandMenu {
// According to the documentation, a message can be part of a guild while also not having a // According to the documentation, a message can be part of a guild while also not having a
// member object for the author. This will happen if the author of a message left the guild. // member object for the author. This will happen if the author of a message left the guild.
readonly member: GuildMember | null; readonly member: GuildMember | null;
readonly send: SendFunction;
} }
interface CommandOptionsBase { interface CommandOptionsBase {
readonly description?: string; readonly description?: string;
readonly endpoint?: boolean;
readonly usage?: string; readonly usage?: string;
readonly permission?: number; readonly permission?: number;
readonly nsfw?: boolean; readonly nsfw?: boolean;
readonly channelType?: CHANNEL_TYPE; readonly channelType?: CHANNEL_TYPE;
readonly run?: (($: CommandMenu) => Promise<any>) | string;
} }
interface CommandOptionsEndpoint {
readonly endpoint: true;
}
// Prevents subcommands from being added by compile-time.
// Also, contrary to what you might think, channel pings do still work in DM channels. // Also, contrary to what you might think, channel pings do still work in DM channels.
// Role pings, maybe not, but it's not a big deal. // Role pings, maybe not, but it's not a big deal.
interface CommandOptionsNonEndpoint { interface CommandOptions extends CommandOptionsBase {
readonly endpoint?: false; readonly run?: (($: CommandMenu) => Promise<any>) | string;
readonly subcommands?: {[key: string]: NamedCommand}; readonly subcommands?: {[key: string]: NamedCommand};
readonly channel?: Command; readonly channel?: Command;
readonly role?: Command; readonly role?: Command;
readonly emote?: Command; readonly emote?: Command;
readonly message?: Command; readonly message?: Command;
readonly user?: Command; readonly user?: Command;
readonly guild?: Command; // Only available if an ID is set to reroute to it.
readonly id?: ID; readonly id?: ID;
readonly number?: Command; readonly number?: Command;
readonly any?: Command; readonly any?: Command | RestCommand;
} }
type CommandOptions = CommandOptionsBase & (CommandOptionsEndpoint | CommandOptionsNonEndpoint); interface NamedCommandOptions extends CommandOptions {
type NamedCommandOptions = CommandOptions & {aliases?: string[]}; readonly aliases?: string[];
readonly nameOverride?: string;
}
interface RestCommandOptions extends CommandOptionsBase {
readonly run?: (($: CommandMenu & {readonly combined: string}) => Promise<any>) | string;
}
interface ExecuteCommandMetadata { interface ExecuteCommandMetadata {
readonly header: string; readonly header: string;
@ -106,17 +110,19 @@ interface ExecuteCommandMetadata {
permission: number; permission: number;
nsfw: boolean; nsfw: boolean;
channelType: CHANNEL_TYPE; channelType: CHANNEL_TYPE;
symbolicArgs: string[]; // i.e. <channel> instead of <#...>
} }
interface CommandInfo { export interface CommandInfo {
readonly type: "info"; readonly type: "info";
readonly command: Command; readonly command: BaseCommand;
readonly subcommandInfo: Collection<string, Command>; readonly subcommandInfo: Collection<string, BaseCommand>;
readonly keyedSubcommandInfo: Collection<string, NamedCommand>; readonly keyedSubcommandInfo: Collection<string, BaseCommand>;
readonly permission: number; readonly permission: number;
readonly nsfw: boolean; readonly nsfw: boolean;
readonly channelType: CHANNEL_TYPE; readonly channelType: CHANNEL_TYPE;
readonly args: string[]; readonly args: string[];
readonly header: string;
} }
interface CommandInfoError { interface CommandInfoError {
@ -131,22 +137,28 @@ interface CommandInfoMetadata {
args: string[]; args: string[];
usage: string; usage: string;
readonly originalArgs: string[]; readonly originalArgs: string[];
readonly header: string;
} }
export const defaultMetadata = { // An isolated command of just the metadata.
permission: 0, abstract class BaseCommand {
nsfw: false,
channelType: CHANNEL_TYPE.ANY
};
// Each Command instance represents a block that links other Command instances under it.
export class Command {
public readonly description: string; public readonly description: string;
public readonly endpoint: boolean;
public readonly usage: string; public readonly usage: string;
public readonly permission: number; // -1 (default) indicates to inherit, 0 is the lowest rank, 1 is second lowest rank, and so on. public readonly permission: number; // -1 (default) indicates to inherit, 0 is the lowest rank, 1 is second lowest rank, and so on.
public readonly nsfw: boolean | null; // null (default) indicates to inherit public readonly nsfw: boolean | null; // null (default) indicates to inherit
public readonly channelType: CHANNEL_TYPE | null; // null (default) indicates to inherit public readonly channelType: CHANNEL_TYPE | null; // null (default) indicates to inherit
constructor(options?: CommandOptionsBase) {
this.description = options?.description || "No description.";
this.usage = options?.usage ?? "";
this.permission = options?.permission ?? -1;
this.nsfw = options?.nsfw ?? null;
this.channelType = options?.channelType ?? null;
}
}
// Each Command instance represents a block that links other Command instances under it.
export class Command extends BaseCommand {
// The execute and subcommand properties are restricted to the class because subcommand recursion could easily break when manually handled. // The execute and subcommand properties are restricted to the class because subcommand recursion could easily break when manually handled.
// The class will handle checking for null fields. // The class will handle checking for null fields.
private run: (($: CommandMenu) => Promise<any>) | string; private run: (($: CommandMenu) => Promise<any>) | string;
@ -156,101 +168,90 @@ export class Command {
private emote: Command | null; private emote: Command | null;
private message: Command | null; private message: Command | null;
private user: Command | null; private user: Command | null;
private guild: Command | null;
private id: Command | null; private id: Command | null;
private idType: ID | null; private idType: ID | null;
private number: Command | null; private number: Command | null;
private any: Command | null; private any: Command | RestCommand | null;
constructor(options?: CommandOptions) { constructor(options?: CommandOptions) {
this.description = options?.description || "No description."; super(options);
this.endpoint = !!options?.endpoint;
this.usage = options?.usage ?? "";
this.permission = options?.permission ?? -1;
this.nsfw = options?.nsfw ?? null;
this.channelType = options?.channelType ?? null;
this.run = options?.run || "No action was set on this command!"; this.run = options?.run || "No action was set on this command!";
this.subcommands = new Collection(); // Populate this collection after setting subcommands. this.subcommands = new Collection(); // Populate this collection after setting subcommands.
this.channel = null; this.channel = options?.channel || null;
this.role = null; this.role = options?.role || null;
this.emote = null; this.emote = options?.emote || null;
this.message = null; this.message = options?.message || null;
this.user = null; this.user = options?.user || null;
this.guild = options?.guild || null;
this.id = null; this.id = null;
this.idType = null; this.idType = options?.id || null;
this.number = null; this.number = options?.number || null;
this.any = null; this.any = options?.any || null;
if (options && !options.endpoint) { if (options)
if (options?.channel) this.channel = options.channel; switch (options.id) {
if (options?.role) this.role = options.role; case "channel":
if (options?.emote) this.emote = options.emote; this.id = this.channel;
if (options?.message) this.message = options.message; break;
if (options?.user) this.user = options.user; case "role":
if (options?.number) this.number = options.number; this.id = this.role;
if (options?.any) this.any = options.any; break;
if (options?.id) this.idType = options.id; case "emote":
this.id = this.emote;
if (options?.id) { break;
switch (options.id) { case "message":
case "channel": this.id = this.message;
this.id = this.channel; break;
break; case "user":
case "role": this.id = this.user;
this.id = this.role; break;
break; case "guild":
case "emote": this.id = this.guild;
this.id = this.emote; break;
break; case undefined:
case "message": break;
this.id = this.message; default:
break; requireAllCasesHandledFor(options.id);
case "user":
this.id = this.user;
break;
default:
requireAllCasesHandledFor(options.id);
}
} }
if (options?.subcommands) { if (options?.subcommands) {
const baseSubcommands = Object.keys(options.subcommands); const baseSubcommands = Object.keys(options.subcommands);
// Loop once to set the base subcommands. // Loop once to set the base subcommands.
for (const name in options.subcommands) this.subcommands.set(name, options.subcommands[name]); for (const name in options.subcommands) this.subcommands.set(name, options.subcommands[name]);
// Then loop again to make aliases point to the base subcommands and warn if something's not right. // Then loop again to make aliases point to the base subcommands and warn if something's not right.
// This shouldn't be a problem because I'm hoping that JS stores these as references that point to the same object. // This shouldn't be a problem because I'm hoping that JS stores these as references that point to the same object.
for (const name in options.subcommands) { for (const name in options.subcommands) {
const subcmd = options.subcommands[name]; const subcmd = options.subcommands[name];
subcmd.name = name; subcmd.name = name;
const aliases = subcmd.aliases; const aliases = subcmd.aliases;
for (const alias of aliases) { for (const alias of aliases) {
if (baseSubcommands.includes(alias)) if (baseSubcommands.includes(alias))
console.warn( console.warn(
`"${alias}" in subcommand "${name}" was attempted to be declared as an alias but it already exists in the base commands! (Look at the next "Loading Command" line to see which command is affected.)` `"${alias}" in subcommand "${name}" was attempted to be declared as an alias but it already exists in the base commands! (Look at the next "Loading Command" line to see which command is affected.)`
); );
else if (this.subcommands.has(alias)) else if (this.subcommands.has(alias))
console.warn( console.warn(
`Duplicate alias "${alias}" at subcommand "${name}"! (Look at the next "Loading Command" line to see which command is affected.)` `Duplicate alias "${alias}" at subcommand "${name}"! (Look at the next "Loading Command" line to see which command is affected.)`
); );
else this.subcommands.set(alias, subcmd); else this.subcommands.set(alias, subcmd);
}
} }
} }
} }
} }
// Go through the arguments provided and find the right subcommand, then execute with the given arguments. // Go through the arguments provided and find the right subcommand, then execute with the given arguments.
// Will return null if it successfully executes, SingleMessageOptions if there's an error (to let the user know what it is). // Will return null if it successfully executes, string if there's an error (to let the user know what it is).
// //
// Calls the resulting subcommand's execute method in order to make more modular code, basically pushing the chain of execution to the subcommand. // Calls the resulting subcommand's execute method in order to make more modular code, basically pushing the chain of execution to the subcommand.
// For example, a numeric subcommand would accept args of [4] then execute on it. // For example, a numeric subcommand would accept args of [4] then execute on it.
public async execute( //
args: string[], // Because each Command instance is isolated from others, it becomes practically impossible to predict the total amount of subcommands when isolating the code to handle each individual layer of recursion.
menu: CommandMenu, // Therefore, if a Command is declared as a rest type, any typed args that come at the end must be handled manually.
metadata: ExecuteCommandMetadata public async execute(args: string[], menu: CommandMenu, metadata: ExecuteCommandMetadata): Promise<string | null> {
): Promise<SingleMessageOptions | null> {
// Update inherited properties if the current command specifies a property. // Update inherited properties if the current command specifies a property.
// In case there are no initial arguments, these should go first so that it can register. // In case there are no initial arguments, these should go first so that it can register.
if (this.permission !== -1) metadata.permission = this.permission; if (this.permission !== -1) metadata.permission = this.permission;
@ -262,69 +263,37 @@ export class Command {
// If there are no arguments left, execute the current command. Otherwise, continue on. // If there are no arguments left, execute the current command. Otherwise, continue on.
if (param === undefined) { if (param === undefined) {
// See if there is anything that'll prevent the user from executing the command. const error = canExecute(menu, metadata);
if (error) return error;
// 1. Does this command specify a required channel type? If so, does the channel type match? if (typeof this.run === "string") {
if ( // Although I *could* add an option in the launcher to attach arbitrary variables to this var string...
metadata.channelType === CHANNEL_TYPE.GUILD && // I'll just leave it like this, because instead of using var strings for user stuff, you could just make "run" a template string.
(!(menu.channel instanceof GuildChannel) || menu.guild === null || menu.member === null) await menu.send(
) { parseVars(
return {content: "This command must be executed in a server."}; this.run,
} else if ( {
metadata.channelType === CHANNEL_TYPE.DM && author: menu.author.toString(),
(menu.channel.type !== "dm" || menu.guild !== null || menu.member !== null) prefix: getPrefix(menu.guild),
) { command: `${metadata.header} ${metadata.symbolicArgs.join(", ")}`
return {content: "This command must be executed as a direct message."}; },
} "???"
)
// 2. Is this an NSFW command where the channel prevents such use? (DM channels bypass this requirement.) );
if (metadata.nsfw && menu.channel.type !== "dm" && !menu.channel.nsfw) { } else {
return {content: "This command must be executed in either an NSFW channel or as a direct message."}; // Then capture any potential errors.
} try {
// 3. Does the user have permission to execute the command?
if (!hasPermission(menu.author, menu.member, metadata.permission)) {
const userPermLevel = getPermissionLevel(menu.author, menu.member);
return {
content: `You don't have access to this command! Your permission level is \`${getPermissionName(
userPermLevel
)}\` (${userPermLevel}), but this command requires a permission level of \`${getPermissionName(
metadata.permission
)}\` (${metadata.permission}).`
};
}
// Then capture any potential errors.
try {
if (typeof this.run === "string") {
await menu.channel.send(
parseVars(
this.run,
{
author: menu.author.toString(),
prefix: getPrefix(menu.guild)
},
"???"
)
);
} else {
await this.run(menu); await this.run(menu);
} catch (error) {
const errorMessage = error.stack ?? error;
console.error(`Command Error: ${metadata.header} (${metadata.args.join(", ")})\n${errorMessage}`);
return `There was an error while trying to execute that command!\`\`\`${errorMessage}\`\`\``;
} }
return null;
} catch (error) {
const errorMessage = error.stack ?? error;
console.error(`Command Error: ${metadata.header} (${metadata.args.join(", ")})\n${errorMessage}`);
return {
content: `There was an error while trying to execute that command!\`\`\`${errorMessage}\`\`\``
};
} }
}
// If the current command is an endpoint but there are still some arguments left, don't continue. return null;
if (this.endpoint) return {content: "Too many arguments!"}; }
// Resolve the value of the current command's argument (adding it to the resolved args), // Resolve the value of the current command's argument (adding it to the resolved args),
// then pass the thread of execution to whichever subcommand is valid (if any). // then pass the thread of execution to whichever subcommand is valid (if any).
@ -332,50 +301,49 @@ export class Command {
const isMessagePair = patterns.messagePair.test(param); const isMessagePair = patterns.messagePair.test(param);
if (this.subcommands.has(param)) { if (this.subcommands.has(param)) {
metadata.symbolicArgs.push(param);
return this.subcommands.get(param)!.execute(args, menu, metadata); return this.subcommands.get(param)!.execute(args, menu, metadata);
} else if (this.channel && patterns.channel.test(param)) { } else if (this.channel && patterns.channel.test(param)) {
const id = patterns.channel.exec(param)![1]; const id = patterns.channel.exec(param)![1];
const channel = menu.client.channels.cache.get(id); const channel = await getChannelByID(id);
// Users can only enter in this format for text channels, so this restricts it to that. if (typeof channel !== "string") {
if (channel instanceof TextChannel) { if (channel instanceof TextChannel || channel instanceof DMChannel) {
menu.args.push(channel); metadata.symbolicArgs.push("<channel>");
return this.channel.execute(args, menu, metadata); menu.args.push(channel);
return this.channel.execute(args, menu, metadata);
} else {
return `\`${id}\` is not a valid text channel!`;
}
} else { } else {
return { return channel;
content: `\`${id}\` is not a valid text channel!`
};
} }
} else if (this.role && patterns.role.test(param)) { } else if (this.role && patterns.role.test(param)) {
const id = patterns.role.exec(param)![1]; const id = patterns.role.exec(param)![1];
if (!menu.guild) { if (!menu.guild) {
return { return "You can't use role parameters in DM channels!";
content: "You can't use role parameters in DM channels!"
};
} }
const role = menu.guild.roles.cache.get(id); const role = menu.guild.roles.cache.get(id);
if (role) { if (role) {
metadata.symbolicArgs.push("<role>");
menu.args.push(role); menu.args.push(role);
return this.role.execute(args, menu, metadata); return this.role.execute(args, menu, metadata);
} else { } else {
return { return `\`${id}\` is not a valid role in this server!`;
content: `\`${id}\` is not a valid role in this server!`
};
} }
} else if (this.emote && patterns.emote.test(param)) { } else if (this.emote && patterns.emote.test(param)) {
const id = patterns.emote.exec(param)![1]; const id = patterns.emote.exec(param)![1];
const emote = menu.client.emojis.cache.get(id); const emote = menu.client.emojis.cache.get(id);
if (emote) { if (emote) {
metadata.symbolicArgs.push("<emote>");
menu.args.push(emote); menu.args.push(emote);
return this.emote.execute(args, menu, metadata); return this.emote.execute(args, menu, metadata);
} else { } else {
return { return `\`${id}\` isn't a valid emote!`;
content: `\`${id}\` isn't a valid emote!`
};
} }
} else if (this.message && (isMessageLink || isMessagePair)) { } else if (this.message && (isMessageLink || isMessagePair)) {
let channelID = ""; let channelID = "";
@ -391,56 +359,50 @@ export class Command {
messageID = result[2]; messageID = result[2];
} }
const channel = menu.client.channels.cache.get(channelID); const message = await getMessageByID(channelID, messageID);
if (channel instanceof TextChannel || channel instanceof DMChannel) { if (typeof message !== "string") {
try { metadata.symbolicArgs.push("<message>");
menu.args.push(await channel.messages.fetch(messageID)); menu.args.push(message);
return this.message.execute(args, menu, metadata); return this.message.execute(args, menu, metadata);
} catch {
return {
content: `\`${messageID}\` isn't a valid message of channel ${channel}!`
};
}
} else { } else {
return { return message;
content: `\`${channelID}\` is not a valid text channel!`
};
} }
} else if (this.user && patterns.user.test(param)) { } else if (this.user && patterns.user.test(param)) {
const id = patterns.user.exec(param)![1]; const id = patterns.user.exec(param)![1];
const user = await getUserByID(id);
try { if (typeof user !== "string") {
menu.args.push(await menu.client.users.fetch(id)); metadata.symbolicArgs.push("<user>");
menu.args.push(user);
return this.user.execute(args, menu, metadata); return this.user.execute(args, menu, metadata);
} catch { } else {
return { return user;
content: `No user found by the ID \`${id}\`!`
};
} }
} else if (this.id && this.idType && patterns.id.test(param)) { } else if (this.id && this.idType && patterns.id.test(param)) {
metadata.symbolicArgs.push("<id>");
const id = patterns.id.exec(param)![1]; const id = patterns.id.exec(param)![1];
// Probably modularize the findXByY code in general in libd. // Probably modularize the findXByY code in general in libd.
// Because this part is pretty much a whole bunch of copy pastes. // Because this part is pretty much a whole bunch of copy pastes.
switch (this.idType) { switch (this.idType) {
case "channel": case "channel":
const channel = menu.client.channels.cache.get(id); const channel = await getChannelByID(id);
// Users can only enter in this format for text channels, so this restricts it to that. if (typeof channel !== "string") {
if (channel instanceof TextChannel) { if (channel instanceof TextChannel || channel instanceof DMChannel) {
menu.args.push(channel); metadata.symbolicArgs.push("<channel>");
return this.id.execute(args, menu, metadata); menu.args.push(channel);
return this.id.execute(args, menu, metadata);
} else {
return `\`${id}\` is not a valid text channel!`;
}
} else { } else {
return { return channel;
content: `\`${id}\` isn't a valid text channel!`
};
} }
case "role": case "role":
if (!menu.guild) { if (!menu.guild) {
return { return "You can't use role parameters in DM channels!";
content: "You can't use role parameters in DM channels!"
};
} }
const role = menu.guild.roles.cache.get(id); const role = menu.guild.roles.cache.get(id);
@ -449,9 +411,7 @@ export class Command {
menu.args.push(role); menu.args.push(role);
return this.id.execute(args, menu, metadata); return this.id.execute(args, menu, metadata);
} else { } else {
return { return `\`${id}\` isn't a valid role in this server!`;
content: `\`${id}\` isn't a valid role in this server!`
};
} }
case "emote": case "emote":
const emote = menu.client.emojis.cache.get(id); const emote = menu.client.emojis.cache.get(id);
@ -460,41 +420,56 @@ export class Command {
menu.args.push(emote); menu.args.push(emote);
return this.id.execute(args, menu, metadata); return this.id.execute(args, menu, metadata);
} else { } else {
return { return `\`${id}\` isn't a valid emote!`;
content: `\`${id}\` isn't a valid emote!`
};
} }
case "message": case "message":
try { const message = await getMessageByID(menu.channel, id);
menu.args.push(await menu.channel.messages.fetch(id));
if (typeof message !== "string") {
menu.args.push(message);
return this.id.execute(args, menu, metadata); return this.id.execute(args, menu, metadata);
} catch { } else {
return { return message;
content: `\`${id}\` isn't a valid message of channel ${menu.channel}!`
};
} }
case "user": case "user":
try { const user = await getUserByID(id);
menu.args.push(await menu.client.users.fetch(id));
if (typeof user !== "string") {
menu.args.push(user);
return this.id.execute(args, menu, metadata); return this.id.execute(args, menu, metadata);
} catch { } else {
return { return user;
content: `No user found by the ID \`${id}\`!` }
}; case "guild":
const guild = getGuildByID(id);
if (typeof guild !== "string") {
menu.args.push(guild);
return this.id.execute(args, menu, metadata);
} else {
return guild;
} }
default: default:
requireAllCasesHandledFor(this.idType); requireAllCasesHandledFor(this.idType);
} }
} else if (this.number && !Number.isNaN(Number(param)) && param !== "Infinity" && param !== "-Infinity") { } else if (this.number && !Number.isNaN(Number(param)) && param !== "Infinity" && param !== "-Infinity") {
metadata.symbolicArgs.push("<number>");
menu.args.push(Number(param)); menu.args.push(Number(param));
return this.number.execute(args, menu, metadata); return this.number.execute(args, menu, metadata);
} else if (this.any) { } else if (this.any instanceof Command) {
metadata.symbolicArgs.push("<any>");
menu.args.push(param); menu.args.push(param);
return this.any.execute(args, menu, metadata); return this.any.execute(args, menu, metadata);
} else if (this.any instanceof RestCommand) {
metadata.symbolicArgs.push("<...>");
args.unshift(param);
menu.args.push(...args);
return this.any.execute(args.join(" "), menu, metadata);
} else { } else {
// Continue adding on the rest of the arguments if there's no valid subcommand. metadata.symbolicArgs.push(`"${param}"`);
menu.args.push(param); return `No valid command sequence matching \`${metadata.header} ${metadata.symbolicArgs.join(
return this.execute(args, menu, metadata); " "
)}\` found.`;
} }
// Note: Do NOT add a return statement here. In case one of the other sections is missing // Note: Do NOT add a return statement here. In case one of the other sections is missing
@ -502,14 +477,19 @@ export class Command {
} }
// What this does is resolve the resulting subcommand as well as the inherited properties and the available subcommands. // What this does is resolve the resulting subcommand as well as the inherited properties and the available subcommands.
public async resolveInfo(args: string[]): Promise<CommandInfo | CommandInfoError> { public resolveInfo(args: string[], header: string): CommandInfo | CommandInfoError {
return this.resolveInfoInternal(args, {...defaultMetadata, args: [], usage: "", originalArgs: [...args]}); return this.resolveInfoInternal(args, {
permission: 0,
nsfw: false,
channelType: CHANNEL_TYPE.ANY,
header,
args: [],
usage: "",
originalArgs: [...args]
});
} }
private async resolveInfoInternal( private resolveInfoInternal(args: string[], metadata: CommandInfoMetadata): CommandInfo | CommandInfoError {
args: string[],
metadata: CommandInfoMetadata
): Promise<CommandInfo | CommandInfoError> {
// Update inherited properties if the current command specifies a property. // Update inherited properties if the current command specifies a property.
// In case there are no initial arguments, these should go first so that it can register. // In case there are no initial arguments, these should go first so that it can register.
if (this.permission !== -1) metadata.permission = this.permission; if (this.permission !== -1) metadata.permission = this.permission;
@ -522,8 +502,8 @@ export class Command {
// If there are no arguments left, return the data or an error message. // If there are no arguments left, return the data or an error message.
if (param === undefined) { if (param === undefined) {
const keyedSubcommandInfo = new Collection<string, NamedCommand>(); const keyedSubcommandInfo = new Collection<string, BaseCommand>();
const subcommandInfo = new Collection<string, Command>(); const subcommandInfo = new Collection<string, BaseCommand>();
// Get all the subcommands of the current command but without aliases. // Get all the subcommands of the current command but without aliases.
for (const [tag, command] of this.subcommands.entries()) { for (const [tag, command] of this.subcommands.entries()) {
@ -541,7 +521,12 @@ export class Command {
if (this.user) subcommandInfo.set("<user>", this.user); if (this.user) subcommandInfo.set("<user>", this.user);
if (this.id) subcommandInfo.set(`<id = <${this.idType}>>`, this.id); if (this.id) subcommandInfo.set(`<id = <${this.idType}>>`, this.id);
if (this.number) subcommandInfo.set("<number>", this.number); if (this.number) subcommandInfo.set("<number>", this.number);
if (this.any) subcommandInfo.set("<any>", this.any);
// The special case for a possible rest command.
if (this.any) {
if (this.any instanceof Command) subcommandInfo.set("<any>", this.any);
else subcommandInfo.set("<...>", this.any);
}
return { return {
type: "info", type: "info",
@ -608,12 +593,19 @@ export class Command {
return invalidSubcommandGenerator(); return invalidSubcommandGenerator();
} }
} else if (param === "<any>") { } else if (param === "<any>") {
if (this.any) { if (this.any instanceof Command) {
metadata.args.push("<any>"); metadata.args.push("<any>");
return this.any.resolveInfoInternal(args, metadata); return this.any.resolveInfoInternal(args, metadata);
} else { } else {
return invalidSubcommandGenerator(); return invalidSubcommandGenerator();
} }
} else if (param === "<...>") {
if (this.any instanceof RestCommand) {
metadata.args.push("<...>");
return this.any.resolveInfoFinale(metadata);
} else {
return invalidSubcommandGenerator();
}
} else if (this.subcommands?.has(param)) { } else if (this.subcommands?.has(param)) {
metadata.args.push(param); metadata.args.push(param);
return this.subcommands.get(param)!.resolveInfoInternal(args, metadata); return this.subcommands.get(param)!.resolveInfoInternal(args, metadata);
@ -630,7 +622,8 @@ export class NamedCommand extends Command {
constructor(options?: NamedCommandOptions) { constructor(options?: NamedCommandOptions) {
super(options); super(options);
this.aliases = options?.aliases || []; this.aliases = options?.aliases || [];
this.originalCommandName = null; // The name override exists in case a user wants to bypass filename restrictions.
this.originalCommandName = options?.nameOverride ?? null;
} }
public get name(): string { public get name(): string {
@ -643,4 +636,116 @@ export class NamedCommand extends Command {
throw new Error(`originalCommandName cannot be set twice! Attempted to set the value to "${value}".`); throw new Error(`originalCommandName cannot be set twice! Attempted to set the value to "${value}".`);
else this.originalCommandName = value; else this.originalCommandName = value;
} }
public isNameSet(): boolean {
return this.originalCommandName !== null;
}
}
// RestCommand is a declarative version of the common "any: args.join(' ')" pattern, basically the Command version of a rest parameter.
// This way, you avoid having extra subcommands when using this pattern.
// I'm probably not going to add a transformer function (a callback to automatically handle stuff like searching for usernames).
// I don't think the effort to figure this part out via generics or something is worth it.
export class RestCommand extends BaseCommand {
private run: (($: CommandMenu & {readonly combined: string}) => Promise<any>) | string;
constructor(options?: RestCommandOptions) {
super(options);
this.run = options?.run || "No action was set on this command!";
}
public async execute(
combined: string,
menu: CommandMenu,
metadata: ExecuteCommandMetadata
): Promise<string | null> {
// Update inherited properties if the current command specifies a property.
// In case there are no initial arguments, these should go first so that it can register.
if (this.permission !== -1) metadata.permission = this.permission;
if (this.nsfw !== null) metadata.nsfw = this.nsfw;
if (this.channelType !== null) metadata.channelType = this.channelType;
const error = canExecute(menu, metadata);
if (error) return error;
if (typeof this.run === "string") {
// Although I *could* add an option in the launcher to attach arbitrary variables to this var string...
// I'll just leave it like this, because instead of using var strings for user stuff, you could just make "run" a template string.
await menu.send(
parseVars(
this.run,
{
author: menu.author.toString(),
prefix: getPrefix(menu.guild),
command: `${metadata.header} ${metadata.symbolicArgs.join(", ")}`
},
"???"
)
);
} else {
// Then capture any potential errors.
try {
// Args will still be kept intact. A common pattern is popping some parameters off the end then doing some branching.
// That way, you can still declaratively mark an argument list as continuing while also handling the individual args.
await this.run({...menu, args: menu.args, combined});
} catch (error) {
const errorMessage = error.stack ?? error;
console.error(`Command Error: ${metadata.header} (${metadata.args.join(", ")})\n${errorMessage}`);
return `There was an error while trying to execute that command!\`\`\`${errorMessage}\`\`\``;
}
}
return null;
}
public resolveInfoFinale(metadata: CommandInfoMetadata): CommandInfo {
if (this.permission !== -1) metadata.permission = this.permission;
if (this.nsfw !== null) metadata.nsfw = this.nsfw;
if (this.channelType !== null) metadata.channelType = this.channelType;
if (this.usage !== "") metadata.usage = this.usage;
return {
type: "info",
command: this,
keyedSubcommandInfo: new Collection<string, BaseCommand>(),
subcommandInfo: new Collection<string, BaseCommand>(),
...metadata
};
}
}
// See if there is anything that'll prevent the user from executing the command.
// Returns null if successful, otherwise returns a message with the error.
function canExecute(menu: CommandMenu, metadata: ExecuteCommandMetadata): string | null {
// 1. Does this command specify a required channel type? If so, does the channel type match?
if (
metadata.channelType === CHANNEL_TYPE.GUILD &&
(!(menu.channel instanceof GuildChannel) || menu.guild === null || menu.member === null)
) {
return "This command must be executed in a server.";
} else if (
metadata.channelType === CHANNEL_TYPE.DM &&
(menu.channel.type !== "dm" || menu.guild !== null || menu.member !== null)
) {
return "This command must be executed as a direct message.";
}
// 2. Is this an NSFW command where the channel prevents such use? (DM channels bypass this requirement.)
if (metadata.nsfw && menu.channel.type !== "dm" && !menu.channel.nsfw) {
return "This command must be executed in either an NSFW channel or as a direct message.";
}
// 3. Does the user have permission to execute the command?
if (!hasPermission(menu.author, menu.member, metadata.permission)) {
const userPermLevel = getPermissionLevel(menu.author, menu.member);
return `You don't have access to this command! Your permission level is \`${getPermissionName(
userPermLevel
)}\` (${userPermLevel}), but this command requires a permission level of \`${getPermissionName(
metadata.permission
)}\` (${metadata.permission}).`;
}
return null;
} }

View File

@ -1,22 +1,32 @@
import {Client, Permissions, Message} from "discord.js"; import {Client, Permissions, Message, MessageReaction, User, PartialUser} from "discord.js";
import {botHasPermission} from "./libd"; import {botHasPermission} from "./libd";
// A list of message ID and callback pairs. You get the emote name and ID of the user reacting. // A list of message ID and callback pairs. You get the emote name and ID of the user reacting.
export const unreactEventListeners: Map<string, (emote: string, id: string) => void> = new Map(); // This will handle removing reactions automatically (if the bot has the right permission).
export const reactEventListeners = new Map<string, (reaction: MessageReaction, user: User | PartialUser) => void>();
export const emptyReactEventListeners = new Map<string, () => void>();
// A list of "channel-message" and callback pairs. Also, I imagine that the callback will be much more maintainable when discord.js v13 comes out with a dedicated message.referencedMessage property. // A list of "channel-message" and callback pairs. Also, I imagine that the callback will be much more maintainable when discord.js v13 comes out with a dedicated message.referencedMessage property.
// Also, I'm defining it here instead of the message event because the load order screws up if you export it from there. Yeah... I'm starting to notice just how much technical debt has been built up. The command handler needs to be modularized and refactored sooner rather than later. Define all constants in one area then grab from there.
export const replyEventListeners = new Map<string, (message: Message) => void>(); export const replyEventListeners = new Map<string, (message: Message) => void>();
export function attachEventListenersToClient(client: Client) { export function attachEventListenersToClient(client: Client) {
// Attached to the client, there can be one event listener attached to a message ID which is executed if present. client.on("messageReactionAdd", (reaction, user) => {
// The reason this is inside the call is because it's possible to switch a user's permissions halfway and suddenly throw an error.
// This will dynamically adjust for that, switching modes depending on whether it currently has the "Manage Messages" permission.
const canDeleteEmotes = botHasPermission(reaction.message.guild, Permissions.FLAGS.MANAGE_MESSAGES);
reactEventListeners.get(reaction.message.id)?.(reaction, user);
if (canDeleteEmotes && !user.partial) reaction.users.remove(user);
});
client.on("messageReactionRemove", (reaction, user) => { client.on("messageReactionRemove", (reaction, user) => {
const canDeleteEmotes = botHasPermission(reaction.message.guild, Permissions.FLAGS.MANAGE_MESSAGES); const canDeleteEmotes = botHasPermission(reaction.message.guild, Permissions.FLAGS.MANAGE_MESSAGES);
if (!canDeleteEmotes) reactEventListeners.get(reaction.message.id)?.(reaction, user);
});
if (!canDeleteEmotes) { client.on("messageReactionRemoveAll", (message) => {
const callback = unreactEventListeners.get(reaction.message.id); reactEventListeners.delete(message.id);
callback && callback(reaction.emoji.name, user.id); emptyReactEventListeners.get(message.id)?.();
} emptyReactEventListeners.delete(message.id);
}); });
client.on("message", (message) => { client.on("message", (message) => {

View File

@ -1,7 +1,5 @@
import {Client, Permissions, Message, TextChannel, DMChannel, NewsChannel} from "discord.js"; import {Client, Permissions, Message, TextChannel, DMChannel, NewsChannel} from "discord.js";
import {loadableCommands} from "./loader"; import {getPrefix, loadableCommands} from "./interface";
import {defaultMetadata} from "./command";
import {getPrefix} from "./interface";
// For custom message events that want to cancel the command handler on certain conditions. // For custom message events that want to cancel the command handler on certain conditions.
const interceptRules: ((message: Message) => boolean)[] = [(message) => message.author.bot]; const interceptRules: ((message: Message) => boolean)[] = [(message) => message.author.bot];
@ -20,6 +18,12 @@ const lastCommandInfo: {
channel: null channel: null
}; };
const defaultMetadata = {
permission: 0,
nsfw: false,
channelType: 0 // CHANNEL_TYPE.ANY, apparently isn't initialized at this point yet
};
// Note: client.user is only undefined before the bot logs in, so by this point, client.user cannot be undefined. // Note: client.user is only undefined before the bot logs in, so by this point, client.user cannot be undefined.
// Note: guild.available will never need to be checked because the message starts in either a DM channel or an already-available guild. // Note: guild.available will never need to be checked because the message starts in either a DM channel or an already-available guild.
export function attachMessageHandlerToClient(client: Client) { export function attachMessageHandlerToClient(client: Client) {
@ -32,6 +36,7 @@ export function attachMessageHandlerToClient(client: Client) {
const commands = await loadableCommands; const commands = await loadableCommands;
const {author, channel, content, guild, member} = message; const {author, channel, content, guild, member} = message;
const send = channel.send.bind(channel);
const text = content; const text = content;
const menu = { const menu = {
author, author,
@ -40,7 +45,8 @@ export function attachMessageHandlerToClient(client: Client) {
guild, guild,
member, member,
message, message,
args: [] args: [],
send
}; };
// Execute a dedicated block for messages in DM channels. // Execute a dedicated block for messages in DM channels.
@ -60,15 +66,16 @@ export function attachMessageHandlerToClient(client: Client) {
const result = await command.execute(args, menu, { const result = await command.execute(args, menu, {
header, header,
args: [...args], args: [...args],
...defaultMetadata ...defaultMetadata,
symbolicArgs: []
}); });
// If something went wrong, let the user know (like if they don't have permission to use a command). // If something went wrong, let the user know (like if they don't have permission to use a command).
if (result) { if (result) {
channel.send(result); send(result);
} }
} else { } else {
channel.send( send(
`I couldn't find the command or alias that starts with \`${header}\`. To see the list of commands, type \`help\`` `I couldn't find the command or alias that starts with \`${header}\`. To see the list of commands, type \`help\``
); );
} }
@ -79,7 +86,7 @@ export function attachMessageHandlerToClient(client: Client) {
// First, test if the message is just a ping to the bot. // First, test if the message is just a ping to the bot.
if (new RegExp(`^<@!?${client.user!.id}>$`).test(text)) { if (new RegExp(`^<@!?${client.user!.id}>$`).test(text)) {
channel.send(`${author}, my prefix on this server is \`${prefix}\`.`); send(`${author}, my prefix on this server is \`${prefix}\`.`);
} }
// Then check if it's a normal command. // Then check if it's a normal command.
else if (text.startsWith(prefix)) { else if (text.startsWith(prefix)) {
@ -97,12 +104,13 @@ export function attachMessageHandlerToClient(client: Client) {
const result = await command.execute(args, menu, { const result = await command.execute(args, menu, {
header, header,
args: [...args], args: [...args],
...defaultMetadata ...defaultMetadata,
symbolicArgs: []
}); });
// If something went wrong, let the user know (like if they don't have permission to use a command). // If something went wrong, let the user know (like if they don't have permission to use a command).
if (result) { if (result) {
channel.send(result); send(result);
} }
} }
} }

View File

@ -1,16 +1,7 @@
export {Command, NamedCommand, CHANNEL_TYPE} from "./command"; // Onion Lasers Command Handler //
export {Command, NamedCommand, RestCommand, CHANNEL_TYPE} from "./command";
export {addInterceptRule} from "./handler"; export {addInterceptRule} from "./handler";
export {launch} from "./interface"; export {launch} from "./interface";
export { export * from "./libd";
SingleMessageOptions, export {getCommandList, getCommandInfo} from "./loader";
botHasPermission,
paginate,
prompt,
ask,
askYesOrNo,
askMultipleChoice,
getMemberByUsername,
callMemberByUsername
} from "./libd";
export {loadableCommands, categories} from "./loader";
export {hasPermission, getPermissionLevel, getPermissionName} from "./permissions"; export {hasPermission, getPermissionLevel, getPermissionName} from "./permissions";

View File

@ -1,23 +1,55 @@
import {Client, User, GuildMember, Guild} from "discord.js"; import {Collection, Client, User, GuildMember, Guild} from "discord.js";
import {attachMessageHandlerToClient} from "./handler"; import {attachMessageHandlerToClient} from "./handler";
import {attachEventListenersToClient} from "./eventListeners"; import {attachEventListenersToClient} from "./eventListeners";
import {NamedCommand} from "./command";
interface LaunchSettings { import {loadCommands} from "./loader";
permissionLevels: PermissionLevel[];
getPrefix: (guild: Guild | null) => string;
}
export async function launch(client: Client, settings: LaunchSettings) {
attachMessageHandlerToClient(client);
attachEventListenersToClient(client);
permissionLevels = settings.permissionLevels;
getPrefix = settings.getPrefix;
}
interface PermissionLevel { interface PermissionLevel {
name: string; name: string;
check: (user: User, member: GuildMember | null) => boolean; check: (user: User, member: GuildMember | null) => boolean;
} }
export let permissionLevels: PermissionLevel[] = []; type PrefixResolver = (guild: Guild | null) => string;
export let getPrefix: (guild: Guild | null) => string = () => "."; type CategoryTransformer = (text: string) => string;
// One potential option is to let the user customize system messages such as "This command must be executed in a guild."
// I decided not to do that because I don't think it'll be worth the trouble.
interface LaunchSettings {
permissionLevels?: PermissionLevel[];
getPrefix?: PrefixResolver;
categoryTransformer?: CategoryTransformer;
}
// One alternative to putting everything in launch(client, ...) is to create an object then set each individual aspect, such as OnionCore.setPermissions(...).
// That way, you can split different pieces of logic into different files, then do OnionCore.launch(client).
// Additionally, each method would return the object so multiple methods could be chained, such as OnionCore.setPermissions(...).setPrefixResolver(...).launch(client).
// I decided to not do this because creating a class then having a bunch of boilerplate around it just wouldn't really be worth it.
// commandsDirectory requires an absolute path to work, so use __dirname.
export async function launch(newClient: Client, commandsDirectory: string, settings?: LaunchSettings) {
// Core Launch Parameters //
client.destroy(); // Release any resources/connections being used by the placeholder client.
client = newClient;
loadableCommands = loadCommands(commandsDirectory);
attachMessageHandlerToClient(newClient);
attachEventListenersToClient(newClient);
// Additional Configuration //
if (settings?.permissionLevels) {
if (settings.permissionLevels.length > 0) permissionLevels = settings.permissionLevels;
else console.warn("permissionLevels must have at least one element to work!");
}
if (settings?.getPrefix) getPrefix = settings.getPrefix;
if (settings?.categoryTransformer) categoryTransformer = settings.categoryTransformer;
}
// Placeholder until properly loaded by the user.
export let loadableCommands = (async () => new Collection<string, NamedCommand>())();
export let client = new Client();
export let permissionLevels: PermissionLevel[] = [
{
name: "User",
check: () => true
}
];
export let getPrefix: PrefixResolver = () => ".";
export let categoryTransformer: CategoryTransformer = (text) => text;

View File

@ -3,189 +3,161 @@ import {
Message, Message,
Guild, Guild,
GuildMember, GuildMember,
Permissions,
TextChannel, TextChannel,
DMChannel, DMChannel,
NewsChannel, NewsChannel,
MessageOptions MessageOptions,
Channel,
GuildChannel,
User,
APIMessageContentResolvable,
MessageAdditions,
SplitOptions,
APIMessage,
StringResolvable,
EmojiIdentifierResolvable,
MessageReaction,
PartialUser
} from "discord.js"; } from "discord.js";
import {unreactEventListeners, replyEventListeners} from "./eventListeners"; import {reactEventListeners, emptyReactEventListeners, replyEventListeners} from "./eventListeners";
import {client} from "./interface";
export type SingleMessageOptions = MessageOptions & {split?: false}; export type SingleMessageOptions = MessageOptions & {split?: false};
/** export type SendFunction = ((
* Tests if a bot has a certain permission in a specified guild. content: APIMessageContentResolvable | (MessageOptions & {split?: false}) | MessageAdditions
*/ ) => Promise<Message>) &
export function botHasPermission(guild: Guild | null, permission: number): boolean { ((options: MessageOptions & {split: true | SplitOptions}) => Promise<Message[]>) &
return !!guild?.me?.hasPermission(permission); ((options: MessageOptions | APIMessage) => Promise<Message | Message[]>) &
} ((content: StringResolvable, options: (MessageOptions & {split?: false}) | MessageAdditions) => Promise<Message>) &
((content: StringResolvable, options: MessageOptions & {split: true | SplitOptions}) => Promise<Message[]>) &
((content: StringResolvable, options: MessageOptions) => Promise<Message | Message[]>);
// Maybe promisify this section to reduce the potential for creating callback hell? Especially if multiple questions in a row are being asked. interface PaginateOptions {
multiPageSize?: number;
idleTimeout?: number;
}
// Pagination function that allows for customization via a callback. // Pagination function that allows for customization via a callback.
// Define your own pages outside the function because this only manages the actual turning of pages. // Define your own pages outside the function because this only manages the actual turning of pages.
/** /**
* Takes a message and some additional parameters and makes a reaction page with it. All the pagination logic is taken care of but nothing more, the page index is returned and you have to send a callback to do something with it. * Takes a message and some additional parameters and makes a reaction page with it. All the pagination logic is taken care of but nothing more, the page index is returned and you have to send a callback to do something with it.
*
* Returns the page number the user left off on in case you want to implement a return to page function.
*/ */
export async function paginate( export function paginate(
channel: TextChannel | DMChannel | NewsChannel, send: SendFunction,
senderID: string, listenTo: string | null,
total: number, totalPages: number,
callback: (page: number, hasMultiplePages: boolean) => SingleMessageOptions, onTurnPage: (page: number, hasMultiplePages: boolean) => SingleMessageOptions,
duration = 60000 options?: PaginateOptions
) { ): Promise<number> {
const hasMultiplePages = total > 1; if (totalPages < 1) throw new Error(`totalPages on paginate() must be 1 or more, ${totalPages} given.`);
const message = await channel.send(callback(0, hasMultiplePages));
if (hasMultiplePages) { return new Promise(async (resolve) => {
let page = 0; const hasMultiplePages = totalPages > 1;
const turn = (amount: number) => { const message = await send(onTurnPage(0, hasMultiplePages));
page += amount;
if (page < 0) page += total; if (hasMultiplePages) {
else if (page >= total) page -= total; const multiPageSize = options?.multiPageSize ?? 5;
const idleTimeout = options?.idleTimeout ?? 60000;
let page = 0;
message.edit(callback(page, true)); const turn = (amount: number) => {
}; page += amount;
const BACKWARDS_EMOJI = "⬅️";
const FORWARDS_EMOJI = "➡️"; if (page >= totalPages) {
const handle = (emote: string, reacterID: string) => { page %= totalPages;
if (senderID === reacterID) { } else if (page < 0) {
switch (emote) { // Assuming 3 total pages, it's a bit tricker, but if we just take the modulo of the absolute value (|page| % total), we get (1 2 0 ...), and we just need the pattern (2 1 0 ...). It needs to reverse order except for when it's 0. I want to find a better solution, but for the time being... total - (|page| % total) unless (|page| % total) = 0, then return 0.
case BACKWARDS_EMOJI: const flattened = Math.abs(page) % totalPages;
turn(-1); if (flattened !== 0) page = totalPages - flattened;
break;
case FORWARDS_EMOJI:
turn(1);
break;
} }
message.edit(onTurnPage(page, true));
};
let stack: {[emote: string]: number} = {
"⬅️": -1,
"➡️": 1
};
if (totalPages > multiPageSize) {
stack = {
"⏪": -multiPageSize,
...stack,
"⏩": multiPageSize
};
} }
};
// Listen for reactions and call the handler. const handle = (reaction: MessageReaction, user: User | PartialUser) => {
let backwardsReaction = await message.react(BACKWARDS_EMOJI); if (user.id === listenTo || (listenTo === null && user.id !== client.user!.id)) {
let forwardsReaction = await message.react(FORWARDS_EMOJI); // Turn the page
unreactEventListeners.set(message.id, handle); const emote = reaction.emoji.name;
const collector = message.createReactionCollector( if (emote in stack) turn(stack[emote]);
(reaction, user) => {
if (user.id === senderID) { // Reset the timer
// The reason this is inside the call is because it's possible to switch a user's permissions halfway and suddenly throw an error. client.clearTimeout(timeout);
// This will dynamically adjust for that, switching modes depending on whether it currently has the "Manage Messages" permission. timeout = client.setTimeout(destroy, idleTimeout);
const canDeleteEmotes = botHasPermission(message.guild, Permissions.FLAGS.MANAGE_MESSAGES);
handle(reaction.emoji.name, user.id);
if (canDeleteEmotes) reaction.users.remove(user);
collector.resetTimer();
} }
};
return false; // When time's up, remove the bot's own reactions.
}, const destroy = () => {
// Apparently, regardless of whether you put "time" or "idle", it won't matter to the collector. reactEventListeners.delete(message.id);
// In order to actually reset the timer, you have to do it manually via collector.resetTimer(). for (const emote of message.reactions.cache.values()) emote.users.remove(message.author);
{time: duration} resolve(page);
); };
// When time's up, remove the bot's own reactions. // Start the reactions and call the handler.
collector.on("end", () => { reactInOrder(message, Object.keys(stack));
unreactEventListeners.delete(message.id); reactEventListeners.set(message.id, handle);
backwardsReaction.users.remove(message.author); emptyReactEventListeners.set(message.id, destroy);
forwardsReaction.users.remove(message.author); let timeout = client.setTimeout(destroy, idleTimeout);
}); }
} });
} }
// Waits for the sender to either confirm an action or let it pass (and delete the message). export async function poll(message: Message, emotes: string[], duration = 60000): Promise<{[emote: string]: number}> {
// This should probably be renamed to "confirm" now that I think of it, "prompt" is better used elsewhere. if (emotes.length === 0) throw new Error("poll() was called without any emotes.");
// Append "\n*(This message will automatically be deleted after 10 seconds.)*" in the future?
/**
* Prompts the user about a decision before following through.
*/
export async function prompt(message: Message, senderID: string, onConfirm: () => void, duration = 10000) {
let isDeleted = false;
message.react("✅"); reactInOrder(message, emotes);
await message.awaitReactions( const reactions = await message.awaitReactions(
(reaction, user) => { (reaction: MessageReaction) => emotes.includes(reaction.emoji.name),
if (user.id === senderID) {
if (reaction.emoji.name === "✅") {
onConfirm();
isDeleted = true;
message.delete();
}
}
// CollectorFilter requires a boolean to be returned.
// My guess is that the return value of awaitReactions can be altered by making a boolean filter.
// However, because that's not my concern with this command, I don't have to worry about it.
// May as well just set it to false because I'm not concerned with collecting any reactions.
return false;
},
{time: duration} {time: duration}
); );
const reactionsByCount: {[emote: string]: number} = {};
if (!isDeleted) message.delete(); for (const emote of emotes) {
} const reaction = reactions.get(emote);
// Asks the user for some input using the inline reply feature. The message here is a message you send beforehand. if (reaction) {
// If the reply is rejected, reply with an error message (when stable support comes from discord.js). const hasBot = reaction.users.cache.has(client.user!.id); // Apparently, reaction.me doesn't work properly.
// Append "\n*(Note: Make sure to use Discord's inline reply feature or this won't work!)*" in the future? And also the "you can now reply to this message" edit.
export function ask(
message: Message,
senderID: string,
condition: (reply: string) => boolean,
onSuccess: () => void,
onReject: () => string,
timeout = 60000
) {
const referenceID = `${message.channel.id}-${message.id}`;
replyEventListeners.set(referenceID, (reply) => { if (reaction.count !== null) {
if (reply.author.id === senderID) { const difference = hasBot ? 1 : 0;
if (condition(reply.content)) { reactionsByCount[emote] = reaction.count - difference;
onSuccess();
replyEventListeners.delete(referenceID);
} else { } else {
reply.reply(onReject()); reactionsByCount[emote] = 0;
} }
} else {
reactionsByCount[emote] = 0;
} }
}); }
setTimeout(() => { return reactionsByCount;
replyEventListeners.set(referenceID, (reply) => {
reply.reply("that action timed out, try using the command again");
replyEventListeners.delete(referenceID);
});
}, timeout);
} }
export function askYesOrNo(message: Message, senderID: string, timeout = 30000): Promise<boolean> { export function confirm(message: Message, senderID: string, timeout = 30000): Promise<boolean | null> {
return new Promise(async (resolve, reject) => { return generateOneTimePrompt(
let isDeleted = false; message,
{
await message.react("✅"); "✅": true,
message.react("❌"); "❌": false
await message.awaitReactions( },
(reaction, user) => { senderID,
if (user.id === senderID) { timeout
const isCheckReacted = reaction.emoji.name === "✅"; );
if (isCheckReacted || reaction.emoji.name === "❌") {
resolve(isCheckReacted);
isDeleted = true;
message.delete();
}
}
return false;
},
{time: timeout}
);
if (!isDeleted) {
message.delete();
reject("Prompt timed out.");
}
});
} }
// This MUST be split into an array. These emojis are made up of several characters each, adding up to 29 in length. // This MUST be split into an array. These emojis are made up of several characters each, adding up to 29 in length.
@ -196,80 +168,223 @@ const multiNumbers = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6
export async function askMultipleChoice( export async function askMultipleChoice(
message: Message, message: Message,
senderID: string, senderID: string,
callbackStack: (() => void)[], choices: number,
timeout = 90000 timeout = 90000
) { ): Promise<number | null> {
if (callbackStack.length > multiNumbers.length) { if (choices > multiNumbers.length)
message.channel.send( throw new Error(
`\`ERROR: The amount of callbacks in "askMultipleChoice" must not exceed the total amount of allowed options (${multiNumbers.length})!\`` `askMultipleChoice only accepts up to ${multiNumbers.length} options, ${choices} was provided.`
); );
return; const numbers: {[emote: string]: number} = {};
} for (let i = 0; i < choices; i++) numbers[multiNumbers[i]] = i;
return generateOneTimePrompt(message, numbers, senderID, timeout);
}
let isDeleted = false; // Asks the user for some input using the inline reply feature. The message here is a message you send beforehand.
// If the reply is rejected, reply with an error message (when stable support comes from discord.js).
export function askForReply(message: Message, listenTo: string, timeout?: number): Promise<Message | null> {
return new Promise((resolve) => {
const referenceID = `${message.channel.id}-${message.id}`;
for (let i = 0; i < callbackStack.length; i++) { replyEventListeners.set(referenceID, (reply) => {
await message.react(multiNumbers[i]); if (reply.author.id === listenTo) {
} message.delete();
replyEventListeners.delete(referenceID);
await message.awaitReactions( resolve(reply);
(reaction, user) => {
if (user.id === senderID) {
const index = multiNumbers.indexOf(reaction.emoji.name);
if (index !== -1) {
callbackStack[index]();
isDeleted = true;
message.delete();
}
} }
});
return false; if (timeout) {
}, client.setTimeout(() => {
{time: timeout} if (!message.deleted) message.delete();
); replyEventListeners.delete(referenceID);
resolve(null);
if (!isDeleted) message.delete(); }, timeout);
}
});
} }
/** // Returns null if timed out, otherwise, returns the value.
* Gets a user by their username. Gets the first one then rolls with it. export function generateOneTimePrompt<T>(
*/
export async function getMemberByUsername(guild: Guild, username: string) {
return (
await guild.members.fetch({
query: username,
limit: 1
})
).first();
}
/**
* Convenience function to handle cases where someone isn't found by a username automatically.
*/
export async function callMemberByUsername(
message: Message, message: Message,
username: string, stack: {[emote: string]: T},
onSuccess: (member: GuildMember) => void listenTo: string | null = null,
) { duration = 60000
const guild = message.guild; ): Promise<T | null> {
const send = message.channel.send; return new Promise(async (resolve) => {
// First, start reacting to the message in order.
reactInOrder(message, Object.keys(stack));
if (guild) { // Then setup the reaction listener in parallel.
const member = await getMemberByUsername(guild, username); await message.awaitReactions(
(reaction: MessageReaction, user: User) => {
if (user.id === listenTo || listenTo === null) {
const emote = reaction.emoji.name;
if (member) onSuccess(member); if (emote in stack) {
else send(`Couldn't find a user by the name of \`${username}\`!`); resolve(stack[emote]);
} else send("You must execute this command in a server!"); message.delete();
}
}
// CollectorFilter requires a boolean to be returned.
// My guess is that the return value of awaitReactions can be altered by making a boolean filter.
// However, because that's not my concern with this command, I don't have to worry about it.
// May as well just set it to false because I'm not concerned with collecting any reactions.
return false;
},
{time: duration}
);
if (!message.deleted) {
message.delete();
resolve(null);
}
});
} }
// TO DO Section // // Start a parallel chain of ordered reactions, allowing a collector to end early.
// Check if the collector ended early by seeing if the message is already deleted.
// Though apparently, message.deleted doesn't seem to update fast enough, so just put a try catch block on message.react().
async function reactInOrder(message: Message, emotes: EmojiIdentifierResolvable[]): Promise<void> {
for (const emote of emotes) {
try {
await message.react(emote);
} catch {
return;
}
}
}
// getGuildByID() - checks for guild.available (boolean) /**
// getGuildByName() * Tests if a bot has a certain permission in a specified guild.
// findMemberByNickname() - gets a member by their nickname or their username */
// findUserByUsername() export function botHasPermission(guild: Guild | null, permission: number): boolean {
return !!guild?.me?.hasPermission(permission);
}
// For "get x by y" methods: // For "get x by y" methods:
// Caching: All guilds, channels, and roles are fully cached, while the caches for messages, users, and members aren't complete. // Caching: All guilds, channels, and roles are fully cached, while the caches for messages, users, and members aren't complete.
// It's more reliable to get users/members by fetching their IDs. fetch() will searching through the cache anyway. // It's more reliable to get users/members by fetching their IDs. fetch() will searching through the cache anyway.
// For guilds, do an extra check to make sure there isn't an outage (guild.available).
export function getGuildByID(id: string): Guild | string {
const guild = client.guilds.cache.get(id);
if (guild) {
if (guild.available) return guild;
else return `The guild \`${guild.name}\` (ID: \`${id}\`) is unavailable due to an outage.`;
} else {
return `No guild found by the ID of \`${id}\`!`;
}
}
export function getGuildByName(name: string): Guild | string {
const query = name.toLowerCase();
const guild = client.guilds.cache.find((guild) => guild.name.toLowerCase().includes(query));
if (guild) {
if (guild.available) return guild;
else return `The guild \`${guild.name}\` (ID: \`${guild.id}\`) is unavailable due to an outage.`;
} else {
return `No guild found by the name of \`${name}\`!`;
}
}
export async function getChannelByID(id: string): Promise<Channel | string> {
try {
return await client.channels.fetch(id);
} catch {
return `No channel found by the ID of \`${id}\`!`;
}
}
// Only go through the cached channels (non-DM channels). Plus, searching DM channels by name wouldn't really make sense, nor do they have names to search anyway.
export function getChannelByName(name: string): GuildChannel | string {
const query = name.toLowerCase();
const channel = client.channels.cache.find(
(channel) => channel instanceof GuildChannel && channel.name.toLowerCase().includes(query)
) as GuildChannel | undefined;
if (channel) return channel;
else return `No channel found by the name of \`${name}\`!`;
}
export async function getMessageByID(
channel: TextChannel | DMChannel | NewsChannel | string,
id: string
): Promise<Message | string> {
if (typeof channel === "string") {
const targetChannel = await getChannelByID(channel);
if (targetChannel instanceof TextChannel || targetChannel instanceof DMChannel) channel = targetChannel;
else if (targetChannel instanceof Channel) return `\`${id}\` isn't a valid text-based channel!`;
else return targetChannel;
}
try {
return await channel.messages.fetch(id);
} catch {
return `\`${id}\` isn't a valid message of the channel ${channel}!`;
}
}
export async function getUserByID(id: string): Promise<User | string> {
try {
return await client.users.fetch(id);
} catch {
return `No user found by the ID of \`${id}\`!`;
}
}
// Also check tags (if provided) to narrow down users.
export function getUserByName(name: string): User | string {
let query = name.toLowerCase();
const tagMatch = /^(.+?)#(\d{4})$/.exec(name);
let tag: string | null = null;
if (tagMatch) {
query = tagMatch[1].toLowerCase();
tag = tagMatch[2];
}
const user = client.users.cache.find((user) => {
const hasUsernameMatch = user.username.toLowerCase().includes(query);
if (tag) return hasUsernameMatch && user.discriminator === tag;
else return hasUsernameMatch;
});
if (user) return user;
else return `No user found by the name of \`${name}\`!`;
}
export async function getMemberByID(guild: Guild, id: string): Promise<GuildMember | string> {
try {
return await guild.members.fetch(id);
} catch {
return `No member found by the ID of \`${id}\`!`;
}
}
// First checks if a member can be found by that nickname, then check if a member can be found by that username.
export async function getMemberByName(guild: Guild, name: string): Promise<GuildMember | string> {
const member = (
await guild.members.fetch({
query: name,
limit: 1
})
).first();
// Search by username if no member is found, then resolve the user into a member if possible.
if (member) {
return member;
} else {
const user = getUserByName(name);
if (user instanceof User) {
const member = guild.members.resolve(user);
if (member) return member;
else return `The user \`${user.tag}\` isn't in this guild!`;
} else {
return `No member found by the name of \`${name}\`!`;
}
}
}

View File

@ -1,44 +1,58 @@
import {Collection} from "discord.js"; import {Collection} from "discord.js";
import glob from "glob"; import glob from "glob";
import {Command, NamedCommand} from "./command"; import path from "path";
import {NamedCommand, CommandInfo} from "./command";
import {loadableCommands, categoryTransformer} from "./interface";
// Internally, it'll keep its original capitalization. It's up to you to convert it to title case when you make a help command. // Internally, it'll keep its original capitalization. It's up to you to convert it to title case when you make a help command.
export const categories = new Collection<string, string[]>(); const categories = new Collection<string, string[]>();
/** Returns the cache of the commands if it exists and searches the directory if not. */ // This will go through all the .js files and import them. Because the import has to be .js (and cannot be .ts), there's no need for a custom filename checker in the launch settings.
export const loadableCommands = (async () => { // This will avoid the problems of being a node module by requiring absolute imports, which the user will pass in as a launch parameter.
const commands = new Collection<string, Command>(); export async function loadCommands(commandsDir: string): Promise<Collection<string, NamedCommand>> {
// Add a trailing separator so that the reduced filename list will reliably cut off the starting part.
// "C:/some/path/to/commands" --> "C:/some/path/to/commands/" (and likewise for \)
commandsDir = path.normalize(commandsDir);
if (!commandsDir.endsWith(path.sep)) commandsDir += path.sep;
const commands = new Collection<string, NamedCommand>();
// Include all .ts files recursively in "src/commands/". // Include all .ts files recursively in "src/commands/".
const files = await globP("src/commands/**/*.ts"); const files = await globP(path.join(commandsDir, "**", "*.js")); // This stage filters out source maps (.js.map).
// Extract the usable parts from "src/commands/" if: // Because glob will use / regardless of platform, the following regex pattern can rely on / being the case.
const filesClean = files.map((filename) => filename.substring(commandsDir.length));
// Extract the usable parts from commands directory if:
// - The path is 1 to 2 subdirectories (a or a/b, not a/b/c) // - The path is 1 to 2 subdirectories (a or a/b, not a/b/c)
// - Any leading directory isn't "modules" // - Any leading directory isn't "modules"
// - The filename doesn't end in .test.ts (for jest testing) // - The filename doesn't end in .test.js (for jest testing)
// - The filename cannot be the hardcoded top-level "template.ts", reserved for generating templates // - The filename cannot be the hardcoded top-level "template.js", reserved for generating templates
const pattern = /src\/commands\/(?!template\.ts)(?!modules\/)(\w+(?:\/\w+)?)(?:test\.)?\.ts/; const pattern = /^(?!template\.js)(?!modules\/)(\w+(?:\/\w+)?)(?:test\.)?\.js$/;
const lists: {[category: string]: string[]} = {}; const lists: {[category: string]: string[]} = {};
for (const path of files) { for (let i = 0; i < files.length; i++) {
const match = pattern.exec(path); const match = pattern.exec(filesClean[i]);
if (!match) continue;
const commandID = match[1]; // e.g. "utilities/info"
const slashIndex = commandID.indexOf("/");
const isMiscCommand = slashIndex !== -1;
const category = isMiscCommand ? commandID.substring(0, slashIndex) : "miscellaneous";
const commandName = isMiscCommand ? commandID.substring(slashIndex + 1) : commandID; // e.g. "info"
if (match) { // This try-catch block MUST be here or Node.js' dynamic require() will silently fail.
const commandID = match[1]; // e.g. "utilities/info" try {
const slashIndex = commandID.indexOf("/");
const isMiscCommand = slashIndex !== -1;
const category = isMiscCommand ? commandID.substring(0, slashIndex) : "miscellaneous";
const commandName = isMiscCommand ? commandID.substring(slashIndex + 1) : commandID; // e.g. "info"
// If the dynamic import works, it must be an object at the very least. Then, just test to see if it's a proper instance. // If the dynamic import works, it must be an object at the very least. Then, just test to see if it's a proper instance.
const command = (await import(`../commands/${commandID}`)).default as unknown; const command = (await import(files[i])).default as unknown;
if (command instanceof NamedCommand) { if (command instanceof NamedCommand) {
command.name = commandName; const isNameOverridden = command.isNameSet();
if (!isNameOverridden) command.name = commandName;
const header = command.name;
if (commands.has(commandName)) { if (commands.has(header)) {
console.warn( console.warn(
`Command "${commandName}" already exists! Make sure to make each command uniquely identifiable across categories!` `Command "${header}" already exists! Make sure to make each command uniquely identifiable across categories!`
); );
} else { } else {
commands.set(commandName, command); commands.set(header, command);
} }
for (const alias of command.aliases) { for (const alias of command.aliases) {
@ -52,12 +66,15 @@ export const loadableCommands = (async () => {
} }
if (!(category in lists)) lists[category] = []; if (!(category in lists)) lists[category] = [];
lists[category].push(commandName); lists[category].push(header);
console.log(`Loading Command: ${commandID}`); if (isNameOverridden) console.log(`Loaded Command: "${commandID}" as "${header}"`);
else console.log(`Loaded Command: ${commandID}`);
} else { } else {
console.warn(`Command "${commandID}" has no default export which is a NamedCommand instance!`); console.warn(`Command "${commandID}" has no default export which is a NamedCommand instance!`);
} }
} catch (error) {
console.error(error);
} }
} }
@ -66,7 +83,7 @@ export const loadableCommands = (async () => {
} }
return commands; return commands;
})(); }
function globP(path: string) { function globP(path: string) {
return new Promise<string[]>((resolve, reject) => { return new Promise<string[]>((resolve, reject) => {
@ -79,3 +96,53 @@ function globP(path: string) {
}); });
}); });
} }
/**
* Returns a list of categories and their associated commands.
*/
export async function getCommandList(): Promise<Collection<string, NamedCommand[]>> {
const list = new Collection<string, NamedCommand[]>();
const commands = await loadableCommands;
for (const [category, headers] of categories) {
const commandList: NamedCommand[] = [];
for (const header of headers.filter((header) => header !== "test")) commandList.push(commands.get(header)!);
// Ignore empty categories like "miscellaneous" (if it's empty).
if (commandList.length > 0) list.set(categoryTransformer(category), commandList);
}
return list;
}
/**
* Resolves a command based on the arguments given.
* - Returns a string if there was an error.
* - Returns a CommandInfo/category tuple if it was a success.
*/
export async function getCommandInfo(args: string[]): Promise<[CommandInfo, string] | string> {
// Use getCommandList() instead if you're just getting the list of all commands.
if (args.length === 0) return "No arguments were provided!";
// Setup the root command
const commands = await loadableCommands;
let header = args.shift()!;
const command = commands.get(header);
if (!command || header === "test") return `No command found by the name \`${header}\`.`;
if (!(command instanceof NamedCommand)) return "Command is not a proper instance of NamedCommand.";
// If it's an alias, set the header to the original command name.
if (command.name) header = command.name;
// Search categories
let category = "Unknown";
for (const [referenceCategory, headers] of categories) {
if (headers.includes(header)) {
category = categoryTransformer(referenceCategory);
break;
}
}
// Gather info
const result = command.resolveInfo(args, header);
if (result.type === "error") return result.message;
else return [result, category];
}

View File

@ -6,6 +6,7 @@ import {permissionLevels} from "./interface";
* Checks if a `Member` has a certain permission. * Checks if a `Member` has a certain permission.
*/ */
export function hasPermission(user: User, member: GuildMember | null, permission: number): boolean { export function hasPermission(user: User, member: GuildMember | null, permission: number): boolean {
if (permissionLevels.length === 0) return true;
for (let i = permissionLevels.length - 1; i >= permission; i--) for (let i = permissionLevels.length - 1; i >= permission; i--)
if (permissionLevels[i].check(user, member)) return true; if (permissionLevels[i].check(user, member)) return true;
return false; return false;
@ -20,6 +21,6 @@ export function getPermissionLevel(user: User, member: GuildMember | null): numb
} }
export function getPermissionName(level: number) { export function getPermissionName(level: number) {
if (level > permissionLevels.length || level < 0) return "N/A"; if (level > permissionLevels.length || level < 0 || permissionLevels.length === 0) return "N/A";
else return permissionLevels[level].name; else return permissionLevels[level].name;
} }

View File

@ -1,6 +1,6 @@
// Flags a user can have. // Flags a user can have.
// They're basically your profile badges. // They're basically your profile badges.
export const flags: {[index: string]: any} = { export const flags: {[index: string]: string} = {
DISCORD_EMPLOYEE: "Discord Employee", DISCORD_EMPLOYEE: "Discord Employee",
DISCORD_PARTNER: "Discord Partner", DISCORD_PARTNER: "Discord Partner",
BUGHUNTER_LEVEL_1: "Bug Hunter (Level 1)", BUGHUNTER_LEVEL_1: "Bug Hunter (Level 1)",
@ -16,13 +16,13 @@ export const flags: {[index: string]: any} = {
VERIFIED_DEVELOPER: "Verified Bot Developer" VERIFIED_DEVELOPER: "Verified Bot Developer"
}; };
export const filterLevels: {[index: string]: any} = { export const filterLevels: {[index: string]: string} = {
DISABLED: "Off", DISABLED: "Off",
MEMBERS_WITHOUT_ROLES: "No Role", MEMBERS_WITHOUT_ROLES: "No Role",
ALL_MEMBERS: "Everyone" ALL_MEMBERS: "Everyone"
}; };
export const verificationLevels: {[index: string]: any} = { export const verificationLevels: {[index: string]: string} = {
NONE: "None", NONE: "None",
LOW: "Low", LOW: "Low",
MEDIUM: "Medium", MEDIUM: "Medium",
@ -30,7 +30,7 @@ export const verificationLevels: {[index: string]: any} = {
VERY_HIGH: "┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻" VERY_HIGH: "┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻"
}; };
export const regions: {[index: string]: any} = { export const regions: {[index: string]: string} = {
brazil: "Brazil", brazil: "Brazil",
europe: "Europe", europe: "Europe",
hongkong: "Hong Kong", hongkong: "Hong Kong",

9
src/defs/translate.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
interface TranslateOptions {
from?: string;
to?: string;
}
declare module "translate-google" {
function translate(input: string, options: TranslateOptions): Promise<string>;
export = translate;
}

17
src/defs/urban.d.ts vendored Normal file
View File

@ -0,0 +1,17 @@
interface Definition {
id: number;
word: string;
thumbsUp: number;
thumbsDown: number;
author: string;
urbanURL: string;
example: string;
definition: string;
tags: string[] | null;
sounds: string[] | null;
}
declare module "relevant-urban" {
function urban(query: string): Promise<Definition>;
export = urban;
}

92
src/defs/weather.d.ts vendored Normal file
View File

@ -0,0 +1,92 @@
interface WeatherJSOptions {
search: string;
lang?: string;
degreeType?: string;
timeout?: number;
}
interface WeatherJSResult {
location: {
name: string;
lat: string;
long: string;
timezone: string;
alert: string;
degreetype: string;
imagerelativeurl: string;
};
current: {
temperature: string;
skycode: string;
skytext: string;
date: string;
observationtime: string;
observationpoint: string;
feelslike: string;
humidity: string;
winddisplay: string;
day: string;
shortday: string;
windspeed: string;
imageUrl: string;
};
forecast: [
{
low: string;
high: string;
skycodeday: string;
skytextday: string;
date: string;
day: string;
shortday: string;
precip: string;
},
{
low: string;
high: string;
skycodeday: string;
skytextday: string;
date: string;
day: string;
shortday: string;
precip: string;
},
{
low: string;
high: string;
skycodeday: string;
skytextday: string;
date: string;
day: string;
shortday: string;
precip: string;
},
{
low: string;
high: string;
skycodeday: string;
skytextday: string;
date: string;
day: string;
shortday: string;
precip: string;
},
{
low: string;
high: string;
skycodeday: string;
skytextday: string;
date: string;
day: string;
shortday: string;
precip: string;
}
];
}
declare module "weather-js" {
const find: (
options: WeatherJSOptions,
callback: (error: Error | string | null, result: WeatherJSResult[]) => any
) => void;
}

View File

@ -1,21 +1,25 @@
// Bootstrapping Section //
import "./modules/globals"; import "./modules/globals";
import {Client, Permissions} from "discord.js"; import {Client, Permissions} from "discord.js";
import {launch} from "./core"; import path from "path";
import setup from "./modules/setup";
import {Config, getPrefix} from "./structures";
// This is here in order to make it much less of a headache to access the client from other files. // This is here in order to make it much less of a headache to access the client from other files.
// This of course won't actually do anything until the setup process is complete and it logs in. // This of course won't actually do anything until the setup process is complete and it logs in.
export const client = new Client(); export const client = new Client();
import {launch} from "./core";
import setup from "./modules/setup";
import {Config, getPrefix} from "./structures";
import {toTitleCase} from "./lib";
// Send the login request to Discord's API and then load modules while waiting for it. // Send the login request to Discord's API and then load modules while waiting for it.
setup.init().then(() => { setup.init().then(() => {
client.login(Config.token).catch(setup.again); client.login(Config.token).catch(setup.again);
}); });
// Setup the command handler. // Setup the command handler.
launch(client, { launch(client, path.join(__dirname, "commands"), {
getPrefix,
categoryTransformer: toTitleCase,
permissionLevels: [ permissionLevels: [
{ {
// NONE // // NONE //
@ -57,8 +61,7 @@ launch(client, {
name: "Bot Owner", name: "Bot Owner",
check: (user) => Config.owner === user.id check: (user) => Config.owner === user.id
} }
], ]
getPrefix: getPrefix
}); });
// Initialize Modules // // Initialize Modules //

View File

@ -144,14 +144,13 @@ export abstract class GenericStructure {
constructor(tag?: string) { constructor(tag?: string) {
this.__meta__ = tag || this.__meta__; this.__meta__ = tag || this.__meta__;
Object.defineProperty(this, "__meta__", {
enumerable: false
});
} }
public save(asynchronous = true) { public save(asynchronous = true) {
const tag = this.__meta__; FileManager.write(this.__meta__, this, asynchronous);
/// @ts-ignore
delete this.__meta__;
FileManager.write(tag, this, asynchronous);
this.__meta__ = tag;
} }
} }

View File

@ -1,7 +1,7 @@
import {client} from "../index"; import {client} from "../index";
import {TextChannel, APIMessage, MessageEmbed} from "discord.js"; import {MessageEmbed} from "discord.js";
import {getPrefix} from "../structures"; import {getPrefix} from "../structures";
import {DiscordAPIError} from "discord.js"; import {getMessageByID} from "../core";
client.on("message", async (message) => { client.on("message", async (message) => {
// Only execute if the message is from a user and isn't a command. // Only execute if the message is from a user and isn't a command.
@ -10,54 +10,43 @@ client.on("message", async (message) => {
if (!messageLink) return; if (!messageLink) return;
const [guildID, channelID, messageID] = messageLink; const [guildID, channelID, messageID] = messageLink;
try { const linkMessage = await getMessageByID(channelID, messageID);
const channel = client.guilds.cache.get(guildID)?.channels.cache.get(channelID) as TextChannel;
const link_message = await channel.messages.fetch(messageID);
let rtmsg: string | APIMessage = ""; // If it's an invalid link (or the bot doesn't have access to it).
if (link_message.cleanContent) { if (typeof linkMessage === "string") {
rtmsg = new APIMessage(message.channel as TextChannel, { return message.channel.send("I don't have access to that channel!");
content: link_message.cleanContent,
disableMentions: "all",
files: link_message.attachments.array()
});
}
const embeds = [...link_message.embeds.filter((v) => v.type == "rich"), ...link_message.attachments.values()];
/// @ts-ignore
if (!link_message.cleanContent && embeds.empty) {
const Embed = new MessageEmbed().setDescription("🚫 The message is empty.");
return message.channel.send(Embed);
}
const infoEmbed = new MessageEmbed()
.setAuthor(
link_message.author.username,
link_message.author.displayAvatarURL({format: "png", dynamic: true, size: 4096})
)
.setTimestamp(link_message.createdTimestamp)
.setDescription(
`${link_message.cleanContent}\n\nSent in **${link_message.guild?.name}** | <#${link_message.channel.id}> ([link](https://discord.com/channels/${guildID}/${channelID}/${messageID}))`
);
if (link_message.attachments.size !== 0) {
const image = link_message.attachments.first();
/// @ts-ignore
infoEmbed.setImage(image.url);
}
await message.channel.send(infoEmbed);
} catch (error) {
if (error instanceof DiscordAPIError) {
message.channel.send("I don't have access to this channel, or something else went wrong.");
}
return console.error(error);
} }
const embeds = [
...linkMessage.embeds.filter((embed) => embed.type === "rich"),
...linkMessage.attachments.values()
];
if (!linkMessage.cleanContent && embeds.length === 0) {
return message.channel.send(new MessageEmbed().setDescription("🚫 The message is empty."));
}
const infoEmbed = new MessageEmbed()
.setAuthor(
linkMessage.author.username,
linkMessage.author.displayAvatarURL({format: "png", dynamic: true, size: 4096})
)
.setTimestamp(linkMessage.createdTimestamp)
.setDescription(
`${linkMessage.cleanContent}\n\nSent in **${linkMessage.guild?.name}** | <#${linkMessage.channel.id}> ([link](https://discord.com/channels/${guildID}/${channelID}/${messageID}))`
);
if (linkMessage.attachments.size !== 0) {
const image = linkMessage.attachments.first();
infoEmbed.setImage(image!.url);
}
return await message.channel.send(infoEmbed);
}); });
export function extractFirstMessageLink(message: string): [string, string, string] | null { export function extractFirstMessageLink(message: string): [string, string, string] | null {
const messageLinkMatch = message.match( const messageLinkMatch = message.match(
/([!<])?https?:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/channels\/(\d{17,19})\/(\d{17,19})\/(\d{17,19})(>)?/ /([!<])?https?:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/channels\/(\d{17,})\/(\d{17,})\/(\d{17,})(>)?/
); );
if (messageLinkMatch === null) return null; if (messageLinkMatch === null) return null;
const [, leftToken, guildID, channelID, messageID, rightToken] = messageLinkMatch; const [, leftToken, guildID, channelID, messageID, rightToken] = messageLinkMatch;

View File

@ -47,6 +47,7 @@ client.on("voiceStateUpdate", async (before, after) => {
const voiceChannel = after.channel!; const voiceChannel = after.channel!;
const textChannel = client.channels.cache.get(streamingChannel); const textChannel = client.channels.cache.get(streamingChannel);
// Although checking the bot's permission to send might seem like a good idea, having the error be thrown will cause it to show up in the last channel rather than just show up in the console.
if (textChannel instanceof TextChannel) { if (textChannel instanceof TextChannel) {
if (isStartStreamEvent) { if (isStartStreamEvent) {
streamList.set(member.id, { streamList.set(member.id, {

View File

@ -5,6 +5,7 @@ import {watch} from "fs";
import {Guild as DiscordGuild, Snowflake} from "discord.js"; import {Guild as DiscordGuild, Snowflake} from "discord.js";
// Maybe use getters and setters to auto-save on set? // Maybe use getters and setters to auto-save on set?
// And maybe use Collections/Maps instead of objects?
class ConfigStructure extends GenericStructure { class ConfigStructure extends GenericStructure {
public token: string; public token: string;
@ -91,15 +92,13 @@ class StorageStructure extends GenericStructure {
super("storage"); super("storage");
this.users = {}; this.users = {};
this.guilds = {}; this.guilds = {};
for (let id in data.users) if (/\d{17,}/g.test(id)) this.users[id] = new User(data.users[id]);
for (let id in data.users) if (/\d{17,19}/g.test(id)) this.users[id] = new User(data.users[id]); for (let id in data.guilds) if (/\d{17,}/g.test(id)) this.guilds[id] = new Guild(data.guilds[id]);
for (let id in data.guilds) if (/\d{17,19}/g.test(id)) this.guilds[id] = new Guild(data.guilds[id]);
} }
/** Gets a user's profile if they exist and generate one if not. */ /** Gets a user's profile if they exist and generate one if not. */
public getUser(id: string): User { public getUser(id: string): User {
if (!/\d{17,19}/g.test(id)) if (!/\d{17,}/g.test(id))
console.warn(`"${id}" is not a valid user ID! It will be erased when the data loads again.`); console.warn(`"${id}" is not a valid user ID! It will be erased when the data loads again.`);
if (id in this.users) return this.users[id]; if (id in this.users) return this.users[id];
@ -112,7 +111,7 @@ class StorageStructure extends GenericStructure {
/** Gets a guild's settings if they exist and generate one if not. */ /** Gets a guild's settings if they exist and generate one if not. */
public getGuild(id: string): Guild { public getGuild(id: string): Guild {
if (!/\d{17,19}/g.test(id)) if (!/\d{17,}/g.test(id))
console.warn(`"${id}" is not a valid guild ID! It will be erased when the data loads again.`); console.warn(`"${id}" is not a valid guild ID! It will be erased when the data loads again.`);
if (id in this.guilds) return this.guilds[id]; if (id in this.guilds) return this.guilds[id];