|
- /* eslint-disable import/prefer-default-export */
- /* eslint-disable @typescript-eslint/no-unsafe-call */
- /* eslint-disable @typescript-eslint/no-unsafe-assignment */
- /* eslint-disable @typescript-eslint/no-unsafe-member-access */
- /* eslint-disable @typescript-eslint/no-unsafe-return */
-
- import { readFile } from 'fs/promises';
- import { GuildEmoji, Message } from 'discord.js';
- import * as sources from '../utils/sources';
- import * as database from '../utils/database';
-
- type ImageReply = {
- tags: (string | string[])[],
- emojiName?: string[],
- content?: string,
- }
-
- export const listenForImagesAndReply = async (message: Message): Promise<void> => {
- const promises = Array
- .from(message.attachments.values())
- .filter((a) => a.url.endsWith('.jpg') || a.url.endsWith('.jpeg') || a.url.endsWith('.png'))
- .map(async (a) => sources.reverseSearch(a.url));
-
- const reverseSearchData = await Promise.all(promises);
- const imageInfoPromises = reverseSearchData.map(async (d) => {
- const [booruResult] = d.results;
- if (!booruResult) {
- return null;
- }
- return sources.fetchImage(booruResult.data.gelbooru_id.toString());
- });
- const imageInfos = await Promise.all(imageInfoPromises);
- const tags = imageInfos.filter((i) => Boolean(i)).map((info) => info.tags.split(' ')).flat();
- const repliesBuffer = await readFile('.image-replies.json');
- const repliesString = repliesBuffer.toString('utf-8');
- const replies = JSON.parse(repliesString) as ImageReply[];
- const theReply = replies.reduce<ImageReply | null>(
- (chosenReply, reply) => {
- if (chosenReply === null && reply.tags.some((t) => {
- if (Array.isArray(t)) {
- return t.every((tt) => tags.includes(tt));
- }
- return tags.includes(t);
- })) {
- return reply;
- }
- return chosenReply;
- },
- null,
- );
-
- console.log(`${message.id}: ${tags.join(' ')}`);
- if (theReply) {
- const { emojiName: emojiNames = [], content: replyContent = '' } = theReply;
- console.log([...emojiNames.map((em) => `+:${em}:`), replyContent].join(' '));
- if (emojiNames.length > 0) {
- const emojis = emojiNames
- .map((emName) => (
- message.guild?.emojis.cache.find((em) => em.name === emName)
- ))
- .filter((em) => Boolean(em)) as GuildEmoji[];
-
- await Promise.all(emojis.map((em) => message.react(em)));
- }
- if (theReply.content) {
- await message.reply(theReply.content);
- }
- }
- };
-
- export const replyRandomImage = async (message: Message, topic: string): Promise<void> => {
- const data = await sources.fetchBooru(topic);
- await message.channel.send({
- embeds: [
- {
- title: 'CuuBot',
- image: {
- url: data.post[0].file_url as string,
- },
- },
- ],
- });
- };
-
- export const queueImage = async (message: Message): Promise<void> => {
- const promises = Array
- .from(message.attachments.values())
- .map(async (attachment) => database.save(message.author.id, { url: attachment.url }));
-
- await Promise.all(promises);
- await message.react('✅');
- };
|