diff --git a/LICENSE b/LICENSE index f288702d..94ae15a0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies @@ -7,17 +7,15 @@ Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to +our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. +software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you @@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. The precise terms and conditions for copying, distribution and modification follow. @@ -72,7 +60,7 @@ modification follow. 0. Definitions. - "This License" refers to version 3 of the GNU General Public License. + "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. @@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - 13. Use with the GNU Affero General Public License. + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single +under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General +Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published +GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's +versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. @@ -620,55 +618,3 @@ copy of the Program in return for a fee. END OF TERMS AND CONDITIONS - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/PRIVACY_POLICY.md b/PRIVACY_POLICY.md new file mode 100644 index 00000000..8e54b6e7 --- /dev/null +++ b/PRIVACY_POLICY.md @@ -0,0 +1,30 @@ +# Privacy policy + +Needle has never and will never collect any personal data. This includes message content, names, IP-adresses, time stamps, member information, etc. + + +## What we collect +We do not collect any data automatically. The only data we collect is user-provided guild configuration data for Needle. When this is provided (by invoking configuration commands), we may collect: +- Guild IDs +- Channel IDs +- Custom responses +- Which features are enabled or disabled + +## Data retention +The data is deleted from the main disk when one of the following occurs: +- Needle is removed from the guild +- A user successfully invokes the `/configure default` command +- A user indicates to us by other means that they want their data deleted + +The data may persist in full-disk copies made for backup-purposes for up to 7 days after it was originally deleted. + +## Where information is processed +Needle is hosted on a data center in Helsinki, Finland by [Hetzner Online GmbH](https://www.hetzner.com/legal/privacy-policy). The bot communicates with [Discord](https://discord.com/privacy)'s API to interact with users. + +## Changes to this privacy policy +We reserve the right to update this privacy policy at any time, with at least 24 hours prior notice in the [Discord support server](https://needle.gg/chat). Your continued use of Needle after the changes have been applied indicates that you agree with the revised privacy policy. + +## Contact +Feel free to contact us at [privacy@needle.gg](mailto:privacy@needle.gg) if you have any questions about this privacy policy. + +Last updated and effective: February 3, 2022 - see update history diff --git a/README.md b/README.md index bcb801ce..9d1563de 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@

- Needle + Needle

- Needle is a Discord bot that helps you declutter your server by creating Discord threads automatically + Needle is a Discord bot that helps you declutter your server by creating Discord threads automatically.

Website ✨Invite Needle 🪡Get support 💬
@@ -22,7 +22,7 @@ This step-by-step guide assumes you have [NodeJS](https://nodejs.org/en/) versio CLIENT_ID=123456... ``` 3. Run `npm install` -4. Run `npm deploy`. This will make the slash commands show up in the servers the bot are in, but **it can take up to _ONE HOUR_ before they show up**. +4. Run `npm run deploy`. This will make the slash commands show up in the servers the bot are in, but **it can take up to _ONE HOUR_ before they show up**. 5. Make sure the bot has the required permissions in Discord: - [x] View channels - [x] Send messages @@ -36,3 +36,17 @@ This step-by-step guide assumes you have [NodeJS](https://nodejs.org/en/) versio Coming soon :tm: [Join the Discord](https://needle.gg/chat) if interested! + +## License +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or (at +your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . diff --git a/package-lock.json b/package-lock.json index 7f50da2d..b64f7420 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "discord-needle", "version": "1.0.0", - "license": "GPL-3.0", + "license": "AGPL-3.0-or-later", "dependencies": { "@discordjs/builders": "^0.12.0", "@discordjs/rest": "^0.3.0", diff --git a/package.json b/package.json index 8716dde7..c45d0e80 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "git+https://github.com/MarcusOtter/discord-needle.git" }, "author": "Marcus Otterström", - "license": "GPL-3.0", + "license": "AGPL-3.0-or-later", "bugs": { "url": "https://github.com/MarcusOtter/discord-needle/issues" }, diff --git a/scripts/deploy-commands.js b/scripts/deploy-commands.js index b3360e97..2c04be73 100644 --- a/scripts/deploy-commands.js +++ b/scripts/deploy-commands.js @@ -1,5 +1,22 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + /* eslint-disable @typescript-eslint/no-var-requires */ -// IMPORTANT: You need to `tsc` before running this script. +// You need to `tsc` before running this script. require("dotenv").config(); diff --git a/src/commands/close.ts b/src/commands/close.ts index 3f5b97b2..da5f0d7d 100644 --- a/src/commands/close.ts +++ b/src/commands/close.ts @@ -1,6 +1,25 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { SlashCommandBuilder } from "@discordjs/builders"; -import { type CommandInteraction, GuildMember, MessageComponentInteraction, Permissions } from "discord.js"; -import { interactionReply, getThreadStartMessage, getMessage } from "../helpers/messageHelpers"; +import { type CommandInteraction, GuildMember, type MessageComponentInteraction, Permissions, type ThreadChannel } from "discord.js"; +import { shouldArchiveImmediately } from "../helpers/configHelpers"; +import { interactionReply, getMessage, getThreadAuthor } from "../helpers/messageHelpers"; +import { setEmojiForNewThread } from "../helpers/threadHelpers"; import type { NeedleCommand } from "../types/needleCommand"; export const command: NeedleCommand = { @@ -26,27 +45,64 @@ export const command: NeedleCommand = { return interactionReply(interaction, getMessage("ERR_ONLY_IN_THREAD")); } - if (channel.autoArchiveDuration === 60) { + // Invoking slash commands seem to unarchive the threads for now so ironically, this has no effect + // Leaving this in if Discord decides to change their API around this + if (channel.archived) { return interactionReply(interaction, getMessage("ERR_NO_EFFECT")); } - const hasChangeTitlePermissions = member.permissionsIn(channel).has(Permissions.FLAGS.MANAGE_THREADS, true); - if (hasChangeTitlePermissions) { - await channel.setAutoArchiveDuration(60); - await interactionReply(interaction, getMessage("SUCCESS_THREAD_ARCHIVE"), false); + const hasManageThreadsPermissions = member.permissionsIn(channel).has(Permissions.FLAGS.MANAGE_THREADS, true); + if (hasManageThreadsPermissions) { + await archiveThread(channel); return; } - const parentMessage = await getThreadStartMessage(channel); - if (!parentMessage) { - return interactionReply(interaction, getMessage("ERR_THREAD_MESSAGE_MISSING")); + const threadAuthor = await getThreadAuthor(channel); + if (!threadAuthor) { + return interactionReply(interaction, getMessage("ERR_AMBIGUOUS_THREAD_AUTHOR")); } - if (parentMessage.author !== interaction.user) { + if (threadAuthor !== interaction.user) { return interactionReply(interaction, getMessage("ERR_ONLY_THREAD_OWNER")); } - await channel.setAutoArchiveDuration(60); - await interactionReply(interaction, getMessage("SUCCESS_THREAD_ARCHIVE"), false); + await archiveThread(channel); + + async function archiveThread(thread: ThreadChannel): Promise { + if (shouldArchiveImmediately(thread)) { + if (interaction.isButton()) { + await interactionReply(interaction, "Success!"); + const message = getMessage("SUCCESS_THREAD_ARCHIVE_IMMEDIATE"); + if (message) { + await thread.send(message); + } + } + else if (interaction.isCommand()) { + await interactionReply(interaction, getMessage("SUCCESS_THREAD_ARCHIVE_IMMEDIATE"), false); + } + + await setEmojiForNewThread(thread, false); + await thread.setArchived(true); + return; + } + + if (thread.autoArchiveDuration === 60) { + return interactionReply(interaction, getMessage("ERR_NO_EFFECT")); + } + + await setEmojiForNewThread(thread, false); + await thread.setAutoArchiveDuration(60); + + if (interaction.isButton()) { + await interactionReply(interaction, "Success!"); + const message = getMessage("SUCCESS_THREAD_ARCHIVE_SLOW"); + if (message) { + await thread.send(message); + } + } + else if (interaction.isCommand()) { + await interactionReply(interaction, getMessage("SUCCESS_THREAD_ARCHIVE_SLOW"), false); + } + } }, }; diff --git a/src/commands/configure.ts b/src/commands/configure.ts index c6a2eb72..00230d48 100644 --- a/src/commands/configure.ts +++ b/src/commands/configure.ts @@ -1,7 +1,24 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { SlashCommandBuilder } from "@discordjs/builders"; import { ChannelType } from "discord-api-types"; -import { type CommandInteraction, GuildMember, type GuildTextBasedChannel, Permissions } from "discord.js"; -import { disableAutothreading, enableAutothreading, getConfig, resetConfigToDefault, setMessage } from "../helpers/configHelpers"; +import { type CommandInteraction, type GuildMember, type GuildTextBasedChannel, Permissions } from "discord.js"; +import { disableAutothreading, emojisEnabled, enableAutothreading, getConfig, resetConfigToDefault, setEmojisEnabled, setMessage } from "../helpers/configHelpers"; import { interactionReply, getMessage, MessageKey, isAutoThreadChannel, addMessageContext } from "../helpers/messageHelpers"; import type { NeedleCommand } from "../types/needleCommand"; import { memberIsModerator } from "../helpers/permissionHelpers"; @@ -48,7 +65,7 @@ export const command: NeedleCommand = { }) .addSubcommand(subcommand => { return subcommand - .setName("autothreading") + .setName("auto-threading") .setDescription("Enable or disable automatic creation of threads on every new message in a channel") .addChannelOption(option => { return option @@ -64,11 +81,32 @@ export const command: NeedleCommand = { .setDescription("Whether or not threads should be automatically created from new messages in the selected channel") .setRequired(true); }) + .addBooleanOption(option => { + return option + .setName("include-bots") + .setDescription("Whether or not threads should be created on messages by bots. Default: False"); + }) + .addStringOption(option => { + return option + .setName("archive-behavior") + .setDescription("What should happen when users close a thread?") + .addChoice("✅ Archive immediately (DEFAULT)", "immediately") + .addChoice("⌛ Archive after 1 hour of inactivity", "slow"); + }) .addStringOption(option => { return option .setName("custom-message") - .setDescription("The message to send when a thread is created (uses the message SUCCESS_THREAD_CREATE if left blank)") - .setRequired(false); + .setDescription("The message to send when a thread is created (\"\\n\" for new line)"); + }); + }) + .addSubcommand(subcommand => { + return subcommand + .setName("emojis") + .setDescription("Toggle thread name emojis on or off") + .addBooleanOption(option => { + return option + .setName("enabled") + .setDescription("Whether or not emojis should be enabled for titles in auto-threads"); }); }) .toJSON(); @@ -90,11 +128,15 @@ export const command: NeedleCommand = { : getMessage("ERR_NO_EFFECT"), !success); } + if (interaction.options.getSubcommand() === "emojis") { + return configureEmojis(interaction); + } + if (interaction.options.getSubcommand() === "message") { return configureMessage(interaction); } - if (interaction.options.getSubcommand() === "autothreading") { + if (interaction.options.getSubcommand() === "auto-threading") { return configureAutothreading(interaction); } @@ -102,6 +144,24 @@ export const command: NeedleCommand = { }, }; +function configureEmojis(interaction: CommandInteraction): Promise { + const enable = interaction.options.getBoolean("enabled"); + if (enable === null || interaction.guild === null) { + return interactionReply(interaction, getMessage("ERR_PARAMETER_MISSING")); + } + + if (enable === emojisEnabled(interaction.guild)) { + return interactionReply(interaction, getMessage("ERR_NO_EFFECT")); + } + + const success = setEmojisEnabled(interaction.guild, enable); + if (!success) return interactionReply(interaction, getMessage("ERR_UNKNOWN")); + + return interactionReply(interaction, enable + ? "Successfully enabled emojis." + : "Successfully disabled emojis."); +} + function configureMessage(interaction: CommandInteraction): Promise { const key = interaction.options.getString("key") as MessageKey; const value = interaction.options.getString("value"); @@ -124,6 +184,8 @@ async function configureAutothreading(interaction: CommandInteraction): Promise< const channel = interaction.options.getChannel("channel") as GuildTextBasedChannel; const enabled = interaction.options.getBoolean("enabled"); const customMessage = interaction.options.getString("custom-message") ?? ""; + const archiveImmediately = interaction.options.getString("archive-behavior") !== "slow"; + const includeBots = interaction.options.getBoolean("include-bots") ?? false; if (!interaction.guild || !interaction.guildId) { return interactionReply(interaction, getMessage("ERR_ONLY_IN_SERVER")); @@ -143,7 +205,7 @@ async function configureAutothreading(interaction: CommandInteraction): Promise< } if (enabled) { - const success = enableAutothreading(interaction.guild, channel.id, customMessage); + const success = enableAutothreading(interaction.guild, channel.id, includeBots, archiveImmediately, customMessage); return success ? interactionReply(interaction, `Updated auto-threading settings for <#${channel.id}>`, false) : interactionReply(interaction, getMessage("ERR_UNKNOWN")); diff --git a/src/commands/help.ts b/src/commands/help.ts index f6f001c3..e6295347 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -1,3 +1,20 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { SlashCommandBuilder } from "@discordjs/builders"; import { type CommandInteraction, MessageActionRow, MessageEmbed } from "discord.js"; import type { APIApplicationCommandOption } from "discord-api-types"; @@ -21,7 +38,7 @@ export const command: NeedleCommand = { getBugReportButton(), getFeatureRequestButton()); - const commandName = interaction.options.getString("command"); + const commandName = interaction.options?.getString("command"); if (commandName) { // User wrote for example "/help title" const commandsEmbed = await getCommandDetailsEmbed(commandName); await interaction.reply({ diff --git a/src/commands/title.ts b/src/commands/title.ts index 9f3c486c..f1be9f2e 100644 --- a/src/commands/title.ts +++ b/src/commands/title.ts @@ -1,6 +1,24 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { SlashCommandBuilder } from "@discordjs/builders"; import { type CommandInteraction, GuildMember, Permissions } from "discord.js"; -import { interactionReply, getThreadStartMessage, getMessage } from "../helpers/messageHelpers"; +import { interactionReply, getMessage, getThreadAuthor } from "../helpers/messageHelpers"; +import { setThreadName } from "../helpers/threadHelpers"; import type { NeedleCommand } from "../types/needleCommand"; export const command: NeedleCommand = { @@ -38,30 +56,30 @@ export const command: NeedleCommand = { } const oldThreadName = channel.name; - if (oldThreadName === newThreadName) { return interactionReply(interaction, getMessage("ERR_NO_EFFECT")); } - const hasChangeTitlePermissions = member.permissionsIn(channel).has(Permissions.FLAGS.MANAGE_THREADS, true); + const hasChangeTitlePermissions = member + .permissionsIn(channel) + .has(Permissions.FLAGS.MANAGE_THREADS, true); + if (hasChangeTitlePermissions) { - await channel.setName(newThreadName, `Changed by ${member.user.tag} (${member.id})`); - await interaction.reply(`Successfully changed title from \`${oldThreadName}\` to \`${newThreadName}\`.`); + await setThreadName(channel, newThreadName); + await interactionReply(interaction, "Success!"); return; } - const parentMessage = await getThreadStartMessage(channel); - if (!parentMessage) { - return interactionReply(interaction, getMessage("ERR_THREAD_MESSAGE_MISSING")); + const threadAuthor = await getThreadAuthor(channel); + if (!threadAuthor) { + return interactionReply(interaction, getMessage("ERR_AMBIGUOUS_THREAD_AUTHOR")); } - if (parentMessage.author !== interaction.user) { + if (threadAuthor !== interaction.user) { return interactionReply(interaction, getMessage("ERR_ONLY_THREAD_OWNER")); } - // Current rate limit is 2 renames per thread per 10 minutes (2021-09-17). - // If that rate limit is hit, it will wait here until it is able to rename the thread. - await channel.setName(newThreadName, `Changed by ${member.user.tag} (${member.id})`); - await interaction.reply(`Successfully changed title from \`${oldThreadName}\` to \`${newThreadName}\`.`); + await setThreadName(channel, newThreadName); + await interactionReply(interaction, "Success!"); }, }; diff --git a/src/config.json b/src/config.json index e41ac972..cdd66783 100644 --- a/src/config.json +++ b/src/config.json @@ -1,5 +1,6 @@ { "threadChannels": [], + "emojisEnabled": true, "messages": { "ERR_UNKNOWN": "An unexpected error occurred. Please try again later.", "ERR_ONLY_IN_SERVER": "You can only perform this action inside a server.", @@ -13,9 +14,10 @@ "ERR_PARAMETER_MISSING": "A non-optional parameter is missing from the command.", "ERR_INSUFFICIENT_PERMS": "You do not have permission to perform this action.", "ERR_CHANNEL_VISIBILITY": "The $CHANNEL channel is not visible to the bot. Change the permissions and try again.", - "ERR_THREAD_MESSAGE_MISSING": "The starting message for this thread could not be found, which prevents this action from being performed.", + "ERR_AMBIGUOUS_THREAD_AUTHOR": "Could not determine the author of this thread, because the initial message was missing.", - "SUCCESS_THREAD_CREATE": "Hello $USER!\nThis thread has been automatically created from your message in $CHANNEL $TIME_AGO.\n\n**Want to unsubscribe from this thread?**\nRight-click the thread (or use the `...` menu) and select **Leave Thread**.\n\n**Want to change the title?**\nUse the `/title` command!\n\n**Done using the thread?**\nClick the button below to archive it.", - "SUCCESS_THREAD_ARCHIVE": "**This thread will be archived soon** :card_box:\nAs requested by $USER, this thread will automatically be archived when **one hour passes without any new messages**.\n\n• The thread's content will still be searchable with Discord's search function\n• Anyone will be able to un-archive the thread at any point in the future by sending a message in the thread again" + "SUCCESS_THREAD_CREATE": "Thread automatically created by $USER in $CHANNEL.", + "SUCCESS_THREAD_ARCHIVE_IMMEDIATE": "Thread was archived by $USER. Anyone can send a message to unarchive it.", + "SUCCESS_THREAD_ARCHIVE_SLOW": "This thread will be archived automatically after 1 hour of inactivity as requested by $USER." } } diff --git a/src/handlers/commandHandler.ts b/src/handlers/commandHandler.ts index cf58c6f6..e03aaf99 100644 --- a/src/handlers/commandHandler.ts +++ b/src/handlers/commandHandler.ts @@ -1,3 +1,20 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { type CommandInteraction, type MessageComponentInteraction } from "discord.js"; import { promises } from "fs"; import { resolve as pathResolve } from "path"; diff --git a/src/handlers/interactionHandler.ts b/src/handlers/interactionHandler.ts index e567c204..1a68f4ed 100644 --- a/src/handlers/interactionHandler.ts +++ b/src/handlers/interactionHandler.ts @@ -1,3 +1,20 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import type { Interaction } from "discord.js"; import { resetMessageContext, addMessageContext } from "../helpers/messageHelpers"; import { handleButtonClickedInteraction, handleCommandInteraction } from "./commandHandler"; diff --git a/src/handlers/messageHandler.ts b/src/handlers/messageHandler.ts index a0d9bf04..79c58a79 100644 --- a/src/handlers/messageHandler.ts +++ b/src/handlers/messageHandler.ts @@ -1,30 +1,75 @@ -import { type Message, MessageActionRow, MessageButton, NewsChannel, TextChannel } from "discord.js"; -import { getConfig } from "../helpers/configHelpers"; -import { getMessage, resetMessageContext, addMessageContext, isAutoThreadChannel } from "../helpers/messageHelpers"; -import { getRequiredPermissions } from "../helpers/permissionHelpers"; +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + +import { type Message, MessageActionRow, MessageButton, NewsChannel, TextChannel, ThreadChannel } from "discord.js"; +import { emojisEnabled, getConfig, includeBotsForAutothread } from "../helpers/configHelpers"; +import { getMessage, resetMessageContext, addMessageContext, isAutoThreadChannel, getHelpButton, replaceMessageVariables, getThreadAuthor } from "../helpers/messageHelpers"; +import { getRequiredPermissions, getSafeDefaultAutoArchiveDuration } from "../helpers/permissionHelpers"; export async function handleMessageCreate(message: Message): Promise { - const clientUser = message.client.user; + // Server outage + if (!message.guild?.available) return; + + // Not logged in + if (message.client.user === null) return; + + if (message.system) return; + if (!message.channel.isText()) return; + if (!message.inGuild()) return; + if (message.author.id === message.client.user.id) return; + + const includeBots = includeBotsForAutothread(message.guild.id, message.channel.id); + if (!includeBots && message.author.bot) return; + + if (!message.author.bot && message.channel.isThread()) { + await updateTitle(message.channel, message); + return; + } + await autoCreateThread(message); + resetMessageContext(); +} + +async function updateTitle(thread: ThreadChannel, message: Message) { + if (message.author.bot) return; + + const threadAuthor = await getThreadAuthor(thread); + if (message.author == threadAuthor) return; + + await thread.setName(thread.name.replace("🆕", "")); +} + +async function autoCreateThread(message: Message) { // Server outage if (!message.guild?.available) return; // Not logged in - if (clientUser === null) return; + if (message.client.user === null) return; const authorUser = message.author; const authorMember = message.member; const guild = message.guild; const channel = message.channel; - if (message.system) return; - if (authorUser.bot) return; - if (!channel.isText()) return; if (!(channel instanceof TextChannel) && !(channel instanceof NewsChannel)) return; if (message.hasThread) return; if (!isAutoThreadChannel(channel.id, guild.id)) return; - const botMember = await guild.members.fetch(clientUser); + const botMember = await guild.members.fetch(message.client.user); const botPermissions = botMember.permissionsIn(message.channel.id); const requiredPermissions = getRequiredPermissions(); if (!botPermissions.has(requiredPermissions)) { @@ -50,22 +95,28 @@ export async function handleMessageCreate(message: Message): Promise { ? authorUser.username : authorMember.nickname; + const name = emojisEnabled(guild) + ? `🆕 ${authorName} (${creationDate})` + : `${authorName} (${creationDate})`; + const thread = await message.startThread({ - name: `${authorName} (${creationDate})`, - autoArchiveDuration: channel.defaultAutoArchiveDuration, + name, + autoArchiveDuration: getSafeDefaultAutoArchiveDuration(channel), }); const closeButton = new MessageButton() .setCustomId("close") .setLabel("Archive thread") - .setStyle("DANGER") - .setEmoji("🗃️"); + .setStyle("SUCCESS") + .setEmoji("937932140014866492"); // :archive: + + const helpButton = getHelpButton(); - const buttonRow = new MessageActionRow().addComponents(closeButton); + const buttonRow = new MessageActionRow().addComponents(closeButton, helpButton); const overrideMessageContent = getConfig(guild.id).threadChannels?.find(x => x?.channelId === channel.id)?.messageContent; const msgContent = overrideMessageContent - ? overrideMessageContent + ? replaceMessageVariables(overrideMessageContent) : getMessage("SUCCESS_THREAD_CREATE"); if (msgContent && msgContent.length > 0) { @@ -75,6 +126,5 @@ export async function handleMessageCreate(message: Message): Promise { }); } - await thread.leave(); resetMessageContext(); } diff --git a/src/helpers/configHelpers.ts b/src/helpers/configHelpers.ts index 211fb277..35e0a7ef 100644 --- a/src/helpers/configHelpers.ts +++ b/src/helpers/configHelpers.ts @@ -1,4 +1,21 @@ -import type { Client, Guild } from "discord.js"; +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + +import type { Client, Guild, ThreadChannel } from "discord.js"; import * as defaultConfig from "../config.json"; import { resolve as pathResolve } from "path"; import * as fs from "fs"; @@ -19,6 +36,8 @@ export function getConfig(guildId = ""): NeedleConfig { return Object.assign({}, defaultConfigCopy, guildConfig); } +// Can probably remove the three methods below :) + // Used by deploy-commands.js (!) export function getApiToken(): string | undefined { return process.env.DISCORD_API_TOKEN; @@ -34,6 +53,27 @@ export function getGuildId(): string | undefined { return process.env.GUILD_ID; } +export function shouldArchiveImmediately(thread: ThreadChannel) { + const config = getConfig(thread.guildId); + return config?.threadChannels?.find(x => x.channelId === thread.parentId)?.archiveImmediately ?? true; +} + +export function includeBotsForAutothread(guildId: string, channelId: string) { + const config = getConfig(guildId); + return config?.threadChannels?.find(x => x.channelId === channelId)?.includeBots ?? false; +} + +export function setEmojisEnabled(guild: Guild, enabled: boolean): boolean { + const config = getConfig(guild.id); + config.emojisEnabled = enabled; + return setConfig(guild, config); +} + +export function emojisEnabled(guild: Guild): boolean { + const config = getConfig(guild.id); + return config.emojisEnabled ?? true; +} + export function setMessage(guild: Guild, messageKey: MessageKey, value: string): boolean { const config = getConfig(guild.id); if (!config || !config.messages) { return false; } @@ -43,19 +83,20 @@ export function setMessage(guild: Guild, messageKey: MessageKey, value: string): return setConfig(guild, config); } -export function enableAutothreading(guild: Guild, channelId: string, message = ""): boolean { +export function enableAutothreading(guild: Guild, channelId: string, includeBots?: boolean, archiveImmediately?: boolean, messageContent?: string): boolean { const config = getConfig(guild.id); if (!config || !config.threadChannels) { return false; } - if (message.length > 2000) { return false; } + if ((messageContent?.length ?? 0) > 2000) { return false; } const index = config.threadChannels.findIndex(x => x?.channelId === channelId); if (index > -1) { - config.threadChannels[index].messageContent = message; + if (includeBots !== undefined) config.threadChannels[index].includeBots = includeBots; + if (archiveImmediately !== undefined) config.threadChannels[index].archiveImmediately = archiveImmediately; + if (messageContent !== undefined) config.threadChannels[index].messageContent = messageContent; } else { - config.threadChannels.push({ channelId: channelId, messageContent: message }); + config.threadChannels.push({ channelId, includeBots, archiveImmediately, messageContent }); } - return setConfig(guild, config); } diff --git a/src/helpers/fileHelpers.ts b/src/helpers/fileHelpers.ts index 0b7912f3..2a921408 100644 --- a/src/helpers/fileHelpers.ts +++ b/src/helpers/fileHelpers.ts @@ -1,3 +1,20 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { MessageAttachment } from "discord.js"; import { Readable } from "stream"; diff --git a/src/helpers/messageHelpers.ts b/src/helpers/messageHelpers.ts index c0f40195..acbdaaf5 100644 --- a/src/helpers/messageHelpers.ts +++ b/src/helpers/messageHelpers.ts @@ -1,9 +1,28 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { - BaseCommandInteraction, + type BaseCommandInteraction, type Message, MessageButton, - MessageComponentInteraction, + type MessageComponentInteraction, type TextBasedChannel, + type ThreadChannel, + type User, } from "discord.js"; import type { MessageContext } from "../types/messageContext"; @@ -27,34 +46,23 @@ export function isAutoThreadChannel(channelId: string, guildId: string): boolean return config?.threadChannels?.some(x => x?.channelId === channelId) ?? false; } -export async function getThreadStartMessage(threadChannel: TextBasedChannel | null): Promise { - if (!threadChannel?.isThread()) { return null; } - if (!threadChannel.parentId) { return null; } +export async function getThreadAuthor(channel: ThreadChannel): Promise { + const parentMessage = await getThreadStartMessage(channel); - const parentChannel = await threadChannel.guild?.channels.fetch(threadChannel.parentId); - if (!parentChannel?.isText()) { return null; } - - // The thread's channel ID is the same as the start message's ID, - // but if the start message has been deleted this will throw an exception - return parentChannel.messages - .fetch(threadChannel.id) - .catch(() => { - console.error(`Start message is missing in thread "${threadChannel.name}"`); - return null; - }); -} + if (parentMessage) return parentMessage.author; -export function getCodeFromCodeBlock(codeBlock: string): string { - const codeBlockStart = codeBlock.match(/^```(\w*)/ig); + // https://github.com/MarcusOtter/discord-needle/issues/49 + const firstMessage = await getFirstMessageInChannel(channel); + const author = firstMessage?.mentions.users.first(); - // If it has no code block - if (codeBlockStart?.length === 0) { - return codeBlock; - } + if (!author) console.log(`Could not determine author of thread "${channel.name}"`); + return author; +} - // Replace start and end tags - const codeWithoutTags = codeBlock.replaceAll(/^```(\w*)/ig, "").replaceAll(/```$/ig, ""); - return codeWithoutTags.trim(); +export async function getFirstMessageInChannel(channel: TextBasedChannel): Promise { + const amount = channel.isThread() ? 2 : 1; // threads have an empty message as the first message + const messages = await channel.messages.fetch({ after: "0", limit: amount }); + return messages.first(); } export function interactionReply( @@ -75,24 +83,29 @@ export function interactionReply( } export function getMessage(messageKey: MessageKey, replaceVariables = true): string | undefined { - const config = getConfig(context?.interaction?.guildId!); + const config = getConfig(context?.interaction?.guildId ?? undefined); if (!config.messages) { return ""; } const message = config.messages[messageKey]; if (!context || !message) { return message; } + return replaceVariables + ? replaceMessageVariables(message) + : message; +} + +export function replaceMessageVariables(message: string): string { const user = context.user ? `<@${context.user.id}>` : ""; const channel = context.channel ? `<#${context.channel.id}>` : ""; const timeAgo = context.timeAgo || (context.message ? `` : ""); - return !replaceVariables - ? message - : message - .replaceAll("$USER", user) - .replaceAll("$CHANNEL", channel) - .replaceAll("$TIME_AGO", timeAgo); + return message + .replaceAll("$USER", user) + .replaceAll("$CHANNEL", channel) + .replaceAll("$TIME_AGO", timeAgo) + .replaceAll("\\n", "\n"); } export function getDiscordInviteButton(buttonText = "Join the support server"): MessageButton { @@ -127,9 +140,24 @@ export function getFeatureRequestButton(buttonText = "Suggest an improvement"): .setEmoji("💡"); } -export function getCloseConfigChannelButton(): MessageButton { +export function getHelpButton(): MessageButton { return new MessageButton() - .setCustomId("close-config-channel") - .setLabel("Close channel") - .setStyle("DANGER"); + .setCustomId("help") + .setLabel("Commands") + .setStyle("SECONDARY") + .setEmoji("937931337942306877"); // :slash_commands: +} + +async function getThreadStartMessage(threadChannel: TextBasedChannel | null): Promise { + if (!threadChannel?.isThread()) { return null; } + if (!threadChannel.parentId) { return null; } + + const parentChannel = await threadChannel.guild?.channels.fetch(threadChannel.parentId); + if (!parentChannel?.isText()) { return null; } + + // The thread's channel ID is the same as the start message's ID, + // but if the start message has been deleted this will throw an exception + return parentChannel.messages + .fetch(threadChannel.id) + .catch(() => null); } diff --git a/src/helpers/permissionHelpers.ts b/src/helpers/permissionHelpers.ts index 695a6389..2e5d0562 100644 --- a/src/helpers/permissionHelpers.ts +++ b/src/helpers/permissionHelpers.ts @@ -1,4 +1,21 @@ -import { GuildMember, Permissions } from "discord.js"; +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + +import { type GuildMember, type NewsChannel, Permissions, type TextChannel, type ThreadAutoArchiveDuration } from "discord.js"; export function getRequiredPermissions(): bigint[] { const output = [ @@ -19,3 +36,22 @@ export function memberIsModerator(member: GuildMember): boolean { export function memberIsAdmin(member: GuildMember): boolean { return member.permissions.has(Permissions.FLAGS.ADMINISTRATOR); } + +// Fixes https://github.com/MarcusOtter/discord-needle/issues/23 +// Should not be required, but Discord for some reason allows the default duration to be higher than the allowed value +export function getSafeDefaultAutoArchiveDuration(channel: TextChannel | NewsChannel): ThreadAutoArchiveDuration { + const archiveDuration = channel.defaultAutoArchiveDuration; + if (!archiveDuration || archiveDuration === "MAX") return "MAX"; + + const highest = getHighestAllowedArchiveDuration(channel); + return archiveDuration > highest + ? highest + : archiveDuration; +} + +function getHighestAllowedArchiveDuration(channel: TextChannel | NewsChannel) { + if (channel.guild.features.includes("SEVEN_DAY_THREAD_ARCHIVE")) return 10080; + if (channel.guild.features.includes("THREE_DAY_THREAD_ARCHIVE")) return 4320; + + return 1440; // 1d +} diff --git a/src/helpers/threadHelpers.ts b/src/helpers/threadHelpers.ts new file mode 100644 index 00000000..243dff9a --- /dev/null +++ b/src/helpers/threadHelpers.ts @@ -0,0 +1,43 @@ +import type { ThreadChannel } from "discord.js"; +import { emojisEnabled } from "./configHelpers"; + +// If that rate limit is hit, it will wait here until it is able to rename the thread. +export function setThreadName(thread: ThreadChannel, name: string): Promise { + const emoji = getEmojiStatus(thread); + const newName = emoji + ? `${emoji} ${name}` + : name; + + return thread.setName(newName); +} + +// Preserves the prepended unicode emoji! +// Current rate limit is 2 renames per thread per 10 minutes (2021-09-17). +export async function setEmojiStatus(thread: ThreadChannel, unicodeEmoji: string): Promise { + if (!isOneUnicodeEmoji(unicodeEmoji)) return false; + const currentEmoji = thread.name.split(" ")[0]; + // TODO: Check if there actually is a current emoji, if not just prepend the new emoji + await thread.setName(thread.name.replace(currentEmoji, unicodeEmoji)); + return true; +} + +export function getEmojiStatus(thread: ThreadChannel): string | undefined { + const emoji = thread.name.split(" ")[0]; + return isOneUnicodeEmoji(emoji) ? emoji : undefined; +} + +export function setEmojiForNewThread(thread: ThreadChannel, shouldBeNew: boolean): Promise { + const hasNewEmoji = thread.name.includes("🆕"); + if (shouldBeNew === hasNewEmoji) return Promise.resolve(thread); + + if (shouldBeNew && !emojisEnabled(thread.guild)) return Promise.resolve(thread); + + return shouldBeNew + ? thread.setName(`🆕 ${thread.name}`) + : thread.setName(thread.name.replaceAll("🆕", "")); +} + +// Derived from https://stackoverflow.com/a/64007175/10615308 +function isOneUnicodeEmoji(text: string) { + return /^\p{Extended_Pictographic}$/u.test(text); +} diff --git a/src/index.ts b/src/index.ts index cfcf52ec..c5e180c7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,16 +1,62 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { Client, Intents } from "discord.js"; import { getOrLoadAllCommands } from "./handlers/commandHandler"; import { handleInteractionCreate } from "./handlers/interactionHandler"; import { handleMessageCreate } from "./handlers/messageHandler"; import { deleteConfigsFromUnkownServers, getApiToken, resetConfigToDefault } from "./helpers/configHelpers"; +console.log(`Needle, a Discord bot that declutters your server by creating threads +Copyright (C) 2022 Marcus Otterström + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published +by the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . +`); + (async () => { (await import("dotenv")).config(); // Initial load of all commands await getOrLoadAllCommands(false); - const CLIENT = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] }); + const CLIENT = new Client({ + intents: [ + Intents.FLAGS.GUILDS, + Intents.FLAGS.GUILD_MESSAGES, + ], + presence: { + activities: [{ + type: "LISTENING", + name: "/help", + }], + }, + }); + CLIENT.once("ready", () => { console.log("Ready!"); deleteConfigsFromUnkownServers(CLIENT); @@ -20,6 +66,6 @@ import { deleteConfigsFromUnkownServers, getApiToken, resetConfigToDefault } fro CLIENT.on("messageCreate", message => handleMessageCreate(message).catch(e => console.log(e))); CLIENT.on("guildDelete", guild => { resetConfigToDefault(guild.id); }); - CLIENT.login(getApiToken() ?? undefined); + CLIENT.login(getApiToken()); })(); diff --git a/src/types/messageContext.ts b/src/types/messageContext.ts index 384d1568..2efb1bdb 100644 --- a/src/types/messageContext.ts +++ b/src/types/messageContext.ts @@ -1,3 +1,20 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { CacheType, Interaction, Message, TextBasedChannel, User } from "discord.js"; export interface MessageContext { diff --git a/src/types/needleCommand.ts b/src/types/needleCommand.ts index 24707f6a..af1e1c1a 100644 --- a/src/types/needleCommand.ts +++ b/src/types/needleCommand.ts @@ -1,3 +1,20 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + import { SlashCommandBuilder } from "@discordjs/builders"; import type { CommandInteraction, MessageComponentInteraction } from "discord.js"; diff --git a/src/types/needleConfig.ts b/src/types/needleConfig.ts index 2213968d..1bdaea08 100644 --- a/src/types/needleConfig.ts +++ b/src/types/needleConfig.ts @@ -1,20 +1,43 @@ +// ________________________________________________________________________________________________ +// +// This file is part of Needle. +// +// Needle is free software: you can redistribute it and/or modify it under the terms of the GNU +// Affero General Public License as published by the Free Software Foundation, either version 3 of +// the License, or (at your option) any later version. +// +// Needle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero +// General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License along with Needle. +// If not, see . +// +// ________________________________________________________________________________________________ + export interface NeedleConfig { - threadChannels?: { channelId: string, messageContent: string }[]; + threadChannels?: AutothreadChannelConfig[]; + emojisEnabled?: boolean; messages?: { ERR_UNKNOWN?: string, ERR_ONLY_IN_SERVER?: string, ERR_ONLY_IN_THREAD?: string, ERR_ONLY_THREAD_OWNER?: string, ERR_NO_EFFECT?: string, - ERR_JSON_MISSING?: string, - ERR_JSON_INVALID?: string, - ERR_CONFIG_INVALID?: string; ERR_PARAMETER_MISSING?: string, ERR_INSUFFICIENT_PERMS?: string, ERR_CHANNEL_VISIBILITY?: string, - ERR_THREAD_MESSAGE_MISSING?: string, + ERR_AMBIGUOUS_THREAD_AUTHOR?: string, SUCCESS_THREAD_CREATE?: string, - SUCCESS_THREAD_ARCHIVE?: string, + SUCCESS_THREAD_ARCHIVE_IMMEDIATE?: string, + SUCCESS_THREAD_ARCHIVE_SLOW?: string, }, } + +export interface AutothreadChannelConfig { + channelId: string, + archiveImmediately?: boolean, + messageContent?: string, + includeBots?: boolean, +}