import type { MessagesServiceInterface } from "@avocadi/bot-core/entities/messages/messages.service"; import { createLogger } from "@avocadi/bot-core/lib/logger"; import { type Channel, ChannelType, type DMChannel, type Message, type MessagePayload, type PartialDMChannel, type User, } from "discord.js"; import { logChannelService } from "features/log-channel/log-channel.service"; import client from "lib/client"; export class MessagesService implements MessagesServiceInterface { private logger = createLogger("MessagesService"); async sendToUser(userInput: User, message: MessagePayload): Promise { const user = await client.users.fetch(userInput.id); if (!user) this.logger.error(`User with ID ${userInput.id} not found.`); this.logger.info(`sending message to user with ID ${userInput.id}.`); await user.send(message); } async logMessage(message: Message): Promise { let recipient: User | null = null; if ( message.channel.isDMBased() && message.channel.type !== ChannelType.GroupDM ) { const channel = message.channel as DMChannel | PartialDMChannel; recipient = channel.recipient; } let logMessage: string; if (recipient) { logMessage = `<@${message.author.id}> sent a message to <@${recipient.id}>:\n"${message.content}"`; } else { logMessage = `<@${message.author.id}> sent a message:\n"${message.content}"`; } await logChannelService.sendLogMessage(logMessage); } async sendToChannel( channel: Channel, createMessageInput: MessagePayload, ): Promise { const fetchedChannel = await client.channels.fetch(channel.id); if (fetchedChannel?.isTextBased() && fetchedChannel.isSendable()) { this.logger.info(`sending message to channel with ID ${channel.id}.`); const success = await fetchedChannel.send(createMessageInput); if (success) this.logger.info( `sending message to channel with ID ${channel.id} SUCCESS.`, ); else this.logger.error( `sending message to channel with ID ${channel.id} FAILED.`, ); } else { this.logger.error( `Channel with ID ${channel.id} not found or is not text-based.`, ); throw new Error("Channel not found or is not text-based."); } } } export const messagesService = new MessagesService();