Skip to content

Commit

Permalink
whoops
Browse files Browse the repository at this point in the history
  • Loading branch information
3vorp committed Oct 8, 2023
1 parent d3c47e6 commit 3907c6a
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/helpers/getImage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { Interaction, MessageType } from "discord.js";
// remove stupid discord metadata (idk why they even added it)
export const removeMetadata = (url: string) => url.split("?")[0];

export const isImage = (url: string) => /(png|gif|jpg|jpeg|webp)$/g.test(removeMetadata(url));

// taken from loadImage();
export type ImageSource =
| string
Expand All @@ -26,12 +28,12 @@ export async function getImageFromMessage(message: Message) {
const embed = message.embeds?.[0];
if (!embed) return "";
let url = embed.thumbnail?.url || embed.image?.url;
if (url) return url;
if (url && isImage(url)) return url;

// search for image urls
url = message.content?.split(" ").find((i) => i.startsWith("http"));
// check if url points to valid image
if (url && /(png|gif|jpg|jpeg|webp)$/g.test(removeMetadata(url))) return url;
if (url && isImage(url)) return url;

// nothing found
return "";
Expand All @@ -54,7 +56,7 @@ export async function getImageFromChannel(msgOrInteraction: Message | Interactio

for (const message of messages.sort((a, b) => b.createdTimestamp - a.createdTimestamp)) {
const url = await getImageFromMessage(message);
if (url) return url;
if (url && isImage(url)) return url;
}

// no image found in last 20 messages
Expand All @@ -75,7 +77,7 @@ export default async function getImage(msgOrInteraction: Message | Interaction)
if (msgOrInteraction instanceof Message) {
author = msgOrInteraction.author.id;
url = await getImageFromMessage(msgOrInteraction);
if (url) return removeMetadata(url);
if (url && isImage(url)) return removeMetadata(url);

// if there's no attachment we check if it's a reply
if (msgOrInteraction.type === MessageType.Reply) {
Expand All @@ -84,19 +86,19 @@ export default async function getImage(msgOrInteraction: Message | Interaction)
original = await msgOrInteraction.fetchReference();
} catch {}
if (original) url = await getImageFromMessage(original);
if (url) return removeMetadata(url);
if (url && isImage(url)) return removeMetadata(url);
}
}

// if it's a slash command we check if the image property exists and use that
if (msgOrInteraction instanceof ChatInputCommandInteraction) {
url = msgOrInteraction.options.getAttachment("image", false)?.url;
if (url) return removeMetadata(url);
if (url && isImage(url)) return removeMetadata(url);
}

// no url in message found so we search the channel
url = await getImageFromChannel(msgOrInteraction);
if (url) return removeMetadata(url);
if (url && isImage(url)) return removeMetadata(url);

// no URL found at all
return "";
Expand Down

0 comments on commit 3907c6a

Please sign in to comment.