Completely understood! To sum it up, the process involves:
- Checking for attachments in the file (which is already being done).
- Sending the file to another channel.
- Deleting the file from the original channel.
However, there is a limitation for files exceeding 8 MB, as bots are restricted to 8 MB uploads only (unlike Nitro users who can upload up to 100 MB). So you have two options: (A) Extract the link from the message (but won't be able to delete the message), or (B) manage messages larger than 8 MB (either ignore them or delete them without re-uploading).
Both options provided can also be applied to images and videos. If you prefer to exclude them, check if the attachment has a width (attachments[0].width == null
for instance). A width indicates an image or video, while no width means a regular file.
Choice A
Start by extracting the link from the message and then posting it in the new channel. It's a simple process.
// The incoming message is `message`.
if (message.channel.id === 'CHANNEL ID 1') {
// No need for size check as it runs 0 times without attachments.
message.attachments.each(attachment => {
client.channels.cache.get('CHANNEL ID 2').send(attachment.url);
});
}
In this scenario, refrain from deleting the message to prevent the file from being removed from Discord's servers as well.
Choice B
This transfers the attachments from the original message to the other channel.
// The incoming message is `message`.
if (message.channel.id === 'CHANNEL ID 1') {
if (message.attachments.size > 0) {
// Size check (8000000 bytes is 8 MB)
if (attachment.size > 8000000) { /* Choose an option below. */ }
client.channels.cache.get('CHANNEL ID 2')
.send({
"files": message.attachments.map(attachment => attachment.url)
});
}
}
In this case, message.attachments.map(...)
contains an array of URLs with the sent attachments. If the file exceeds 8 MB, it's your call on what action to take, but both options end with no message being sent.
Choice B.1
You can opt not to relay the message and do nothing. The original message remains, and no communication is forwarded to the other channel.
if (attachment.size > 8000000) { return; /* Terminates the function. */ }
If you plan on continuing with additional code after this, simply invert the expression (attachment.size < 8000000
) and enclose the sending statement (client.channels.cache...
) within that if statement.
Choice B.2
You can decide to delete the message without transmitting it and send a polite error message or a similar response. This is recommended for confidential files or similar situations.
if (attachment.size > 8000000) {
message.delete();
message.channel.send("Apologies, but your file exceeded the size limit!");
return;
}
You can replace the statement following message.delete
with any desired message. Note that this message also includes a return
to prevent the bot from attempting to upload the file (which would fail).