Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Channel Archiver #304

Merged
merged 8 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
214 changes: 214 additions & 0 deletions discord-scripts/channel-management.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import { Robot } from "hubot"
import {
Client,
TextChannel,
ChannelType,
AttachmentBuilder,
Collection,
Message,
} from "discord.js"
import { writeFile, unlink } from "fs/promises"

const defenseCategoryName = "defense"
const defenseArchiveCategoryName = "Archive: Defense"

// fetch messages in batch of 100 in-order to go past rate limit.
async function fetchAllMessages(
channel: TextChannel,
before?: string,
): Promise<Collection<string, Message<true>>> {
const limit = 100
const options = before ? { limit, before } : { limit }
const fetchedMessages = await channel.messages.fetch(options)

if (fetchedMessages.size === 0) {
return new Collection<string, Message<true>>()
}

const lastId = fetchedMessages.lastKey()
const olderMessages = await fetchAllMessages(channel, lastId)

return new Collection<string, Message<true>>().concat(
fetchedMessages,
olderMessages,
)
}

export default async function archiveChannel(
discordClient: Client,
robot: Robot,
) {
const { application } = discordClient

if (application) {
// check if archive-channel command already exists, if not create it
const existingArchiveCommand = (await application.commands.fetch()).find(
(command) => command.name === "archive-channel",
)
if (existingArchiveCommand === undefined) {
robot.logger.info("No archive-channel command found, creating it!")
await application.commands.create({
name: "archive-channel",
description:
"Archives channel to archived channels category (Defense only)",
})
robot.logger.info("archive channel command set")
}

// check if unarchive-channel command already exists, if not create it
const existingUnarchiveCommand = (await application.commands.fetch()).find(
(command) => command.name === "unarchive-channel",
)
if (existingUnarchiveCommand === undefined) {
robot.logger.info("No unarchive-channel command found, creating it!")
await application.commands.create({
name: "unarchive-channel",
description:
"unarchive channel back to defense category (Defense only)",
})
robot.logger.info("unarchive channel command set")
}

// move channel to archived-channel category and send out transcript to interaction
discordClient.on("interactionCreate", async (interaction) => {
if (
!interaction.isCommand() ||
interaction.commandName !== "archive-channel"
) {
return
}
if (!interaction.guild || !(interaction.channel instanceof TextChannel)) {
return
}

try {
const channelCategory = interaction.channel.parent

if (!channelCategory || channelCategory.name !== defenseCategoryName) {
await interaction.reply({
content: `**This command can only be run in channels under the ${defenseCategoryName} channel category**`,
ephemeral: true,
})
return
}

const allMessages = await fetchAllMessages(interaction.channel)
robot.logger.info(`Total messages fetched: ${allMessages}`)

const messagesContent = allMessages
.reverse()
.map(
(m) =>
`${m.createdAt.toLocaleString()}: ${m.author.username}: ${
m.content
}`,
)
.join("\n")

const filePath = `${interaction.channel.name}_transcript.txt`
await writeFile(filePath, messagesContent, "utf-8")

// check for or create archived category
let archivedCategory = interaction.guild.channels.cache.find(
(c) =>
c.type === ChannelType.GuildCategory &&
c.name === defenseArchiveCategoryName,
)
if (!archivedCategory) {
archivedCategory = await interaction.guild.channels.create({
name: defenseArchiveCategoryName,
type: ChannelType.GuildCategory,
})
}

// move channel and set permissions
if (archivedCategory) {
await interaction.channel.setParent(archivedCategory.id)
await interaction.channel.permissionOverwrites.edit(
interaction.guild.id,
{ SendMessages: false },
)
await interaction.reply({
content: `**Channel archived, locked and moved to ${defenseArchiveCategoryName} channel category**`,
ephemeral: true,
})

// upload chat transcript to channel and then delete it
const fileAttachment = new AttachmentBuilder(filePath)
await interaction.channel
.send({
content: "**Here is a transcript of the channel messages:**",
files: [fileAttachment],
})
.then(() => unlink(filePath))
.catch((error) =>
robot.logger.error(`Failed to delete file: ${error}`),
)

robot.logger.info(
"Channel archived and locked successfully, messages saved.",
)
}
} catch (error) {
robot.logger.error(`An error occurred: ${error}`)
}
})

// move channel back to defense category on Unarchived
discordClient.on("interactionCreate", async (interaction) => {
if (
!interaction.isCommand() ||
interaction.commandName !== "unarchive-channel"
) {
return
}
if (!interaction.guild) {
return
}
try {
if (interaction.channel instanceof TextChannel) {
zuuring marked this conversation as resolved.
Show resolved Hide resolved
const channelCategory = interaction.channel.parent

if (
!channelCategory ||
channelCategory.name !== defenseArchiveCategoryName
) {
await interaction.reply({
content: `**This command can only be run in channels under the ${defenseArchiveCategoryName} channel category.**`,
ephemeral: true,
})
return
}

const defenseCategory = interaction.guild.channels.cache.find(
(c) =>
c.type === ChannelType.GuildCategory &&
c.name.toLowerCase() === "defense",
)

if (!defenseCategory) {
await interaction.reply({
content: "No defense category found to move channel to",
ephemeral: true,
})
}

if (defenseCategory) {
await interaction.channel.setParent(defenseCategory.id)
await interaction.channel.permissionOverwrites.edit(
interaction.guild.id,
{ SendMessages: false },
)
await interaction.reply({
content:
"**Channel unarchived and move backed to defense category**",
ephemeral: true,
})
}
}
} catch (error) {
robot.logger.error(`An error occurred: ${error}`)
}
})
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"cronstrue": "^1.68.0",
"decode-html": "^2.0.0",
"discord.js": "^14.8.0",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"figma-api": "^1.11.0",
"github-api": "^3.4.0",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2363,6 +2363,11 @@ doctrine@^3.0.0:
dependencies:
esutils "^2.0.2"

dotenv@^16.4.5:
version "16.4.5"
resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.4.5.tgz#cdd3b3b604cb327e286b4762e13502f717cb099f"
integrity sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==

double-ended-queue@^2.1.0-0:
version "2.1.0-0"
resolved "https://registry.yarnpkg.com/double-ended-queue/-/double-ended-queue-2.1.0-0.tgz#103d3527fd31528f40188130c841efdd78264e5c"
Expand Down
Loading