Skip to content

Commit

Permalink
[ChatGPT] Adds error handling if attachment is not an image
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeyaworski committed Jun 11, 2024
1 parent ada240c commit 327fd57
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/commands/utilities/chatgpt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
getBooleanArg,
getRateLimiterFromEnv,
parseInput,
throwIfNotImageAttachment,
} from 'src/discord-utils';
import { ENV_LIMITER_SPLIT_REGEX } from 'src/constants';

Expand Down Expand Up @@ -124,6 +125,7 @@ const run: CommandOrModalRunMethod = async interaction => {
const guildId = interaction.guildId || '';

const queryImage = attachment?.url;
throwIfNotImageAttachment(attachment);

const content = await getChatGptResponse({
query,
Expand Down
7 changes: 7 additions & 0 deletions src/discord-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
Attachment,
Message,
User,
PermissionResolvable,
Expand Down Expand Up @@ -1187,3 +1188,9 @@ export function getRateLimiterFromEnv(userKey: string, guildKey: string): RateLi
} : undefined,
});
}

export function throwIfNotImageAttachment(attachment: Attachment | undefined | null): void {
if (attachment && !(attachment.contentType && /^image\//.test(attachment.contentType))) {
throw new Error('Attachment must be an image.');
}
}
4 changes: 3 additions & 1 deletion src/events/dms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import type { Message } from 'discord.js';
import type { EventTrigger } from 'src/types';

import { getChatGptResponse } from 'src/commands/utilities/chatgpt';
import { chunkReplies, getErrorMsg } from 'src/discord-utils';
import { chunkReplies, getErrorMsg, throwIfNotImageAttachment } from 'src/discord-utils';

const NewDmEvent: EventTrigger = ['messageCreate', async (message: Message): Promise<void> => {
if (!message.inGuild() && !message.author.bot) {
if (!message.content) return;
try {
const attachment = message.attachments?.at(0);
throwIfNotImageAttachment(attachment);
const response = await getChatGptResponse({
query: message.content,
queryImage: message.attachments?.at(0)?.url,
Expand Down

0 comments on commit 327fd57

Please sign in to comment.