n8n-nodes-discord-dnd
Version:
n8n node to create triggers for Discord events
285 lines • 15.6 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionEventHandler = void 0;
const types_1 = require("../../Interfaces/types");
class ActionEventHandler {
constructor(client, actionInstance) {
this.client = client;
this.actionInstance = actionInstance;
}
async setupEventHandler(action) {
const data = {};
switch (action) {
case types_1.ActionEventType.SEND_TYPING:
const channelId = this.actionInstance.getNodeParameter("channelId", 0);
const channel = (await this.client.channels.fetch(channelId));
if (channel === null || channel === void 0 ? void 0 : channel.isTextBased()) {
await channel.sendTyping();
data.success = true;
data.message = "Typing indicator sent successfully.";
}
else {
throw new Error("The provided channel is not a text channel!");
}
break;
case types_1.ActionEventType.SEND_MESSAGE:
const sendAsDM = this.actionInstance.getNodeParameter("sendAsDM", 0, false);
let messageChannel;
if (sendAsDM) {
const userId = this.actionInstance.getNodeParameter("userId", 0);
try {
const user = await this.client.users.fetch(userId);
messageChannel = await user.createDM();
}
catch (error) {
throw new Error(`Failed to create DM channel: ${error.message}`);
}
}
else {
const messageChannelId = this.actionInstance.getNodeParameter("channelId", 0);
messageChannel = (await this.client.channels.fetch(messageChannelId));
if (!(messageChannel === null || messageChannel === void 0 ? void 0 : messageChannel.isTextBased())) {
throw new Error("The provided channel is not a text channel!");
}
}
let messageContent;
let embeds = [];
let files = [];
// Get message content
messageContent = this.actionInstance.getNodeParameter("messageContent", 0, "");
// Try to get embeds collection
const embedsCollection = this.actionInstance.getNodeParameter("embeds", 0, { embed: [] });
if (embedsCollection && embedsCollection.embed && embedsCollection.embed.length > 0) {
embeds = embedsCollection.embed.map((embed) => {
const inputMethod = embed.inputMethod || "fields";
// Handle JSON embeds
if (inputMethod === "json") {
try {
return JSON.parse(embed.jsonEmbed || "{}");
}
catch (error) {
throw new Error(`Invalid JSON in embed: ${error.message}`);
}
}
// Handle field-based embeds
const processedEmbed = {
type: embed.type || "rich",
title: embed.title || undefined,
description: embed.description || undefined,
url: embed.url || undefined,
color: embed.color || undefined,
timestamp: embed.timestamp ? new Date(embed.timestamp).toISOString() : undefined,
};
// Process embed fields if they exist
if (embed.fields && embed.fields.field) {
processedEmbed.fields = embed.fields.field.map((field) => ({
name: field.name || "Field",
value: field.value || "Value",
inline: field.inline || false,
}));
}
// Process thumbnail and image
if (embed.thumbnailUrl) {
processedEmbed.thumbnail = { url: embed.thumbnailUrl };
}
if (embed.imageUrl) {
processedEmbed.image = { url: embed.imageUrl };
}
// Process footer
if (embed.footerText) {
processedEmbed.footer = {
text: embed.footerText,
icon_url: embed.footerIconUrl || undefined,
};
}
// Process author
if (embed.authorName) {
processedEmbed.author = {
name: embed.authorName,
url: embed.authorUrl || undefined,
icon_url: embed.authorIconUrl || undefined,
};
}
// Process video (if applicable)
if (embed.type === "video" && embed.videoUrl) {
processedEmbed.video = { url: embed.videoUrl };
}
// Process provider (if applicable)
if (embed.providerName) {
processedEmbed.provider = {
name: embed.providerName,
url: embed.providerUrl || undefined,
};
}
return processedEmbed;
});
}
// Handle JSON payload if specified
try {
// Check if JSON payload parameter exists and has a non-empty value
const jsonPayload = this.actionInstance.getNodeParameter("jsonPayload", 0, "");
if (jsonPayload) {
const parsedPayload = JSON.parse(jsonPayload);
if (parsedPayload.content !== undefined) {
messageContent = parsedPayload.content;
}
if (parsedPayload.embeds !== undefined) {
embeds = parsedPayload.embeds;
}
// Files would need to be handled separately
}
}
catch (error) {
// If parsing fails or the parameter doesn't exist, continue with the regular fields
// No need to throw an error here as we'll use the values from the regular fields
}
// Process file uploads if any
const filesCollection = this.actionInstance.getNodeParameter("files", 0, { file: [] });
if (filesCollection.file && filesCollection.file.length > 0) {
for (const fileData of filesCollection.file) {
if (fileData.binaryProperty) {
const binaryData = this.actionInstance.helpers.getBinaryDataBuffer(0, fileData.binaryProperty);
files.push({
attachment: binaryData,
name: fileData.fileName || "file",
});
}
}
}
// Check for message to reply to
const options = this.actionInstance.getNodeParameter("options", 0, {});
const messageOptions = {
content: messageContent,
embeds: embeds,
files: files,
};
if (options.messageId) {
messageOptions.reply = { messageReference: options.messageId };
}
const message = await messageChannel.send(messageOptions);
data.success = true;
data.message = "Message sent successfully.";
data.messageId = message.id;
break;
case types_1.ActionEventType.DELETE_MESSAGE:
const deleteChannelId = this.actionInstance.getNodeParameter("channelId", 0);
const messageId = this.actionInstance.getNodeParameter("messageId", 0);
const deleteChannel = (await this.client.channels.fetch(deleteChannelId));
if (!(deleteChannel === null || deleteChannel === void 0 ? void 0 : deleteChannel.isTextBased())) {
throw new Error("The provided channel is not a text channel!");
}
try {
const messageToDelete = await deleteChannel.messages.fetch(messageId);
await messageToDelete.delete();
data.success = true;
data.message = "Message deleted successfully.";
}
catch (error) {
throw new Error(`Failed to delete message: ${error.message}`);
}
break;
case types_1.ActionEventType.EDIT_MESSAGE:
const editChannelId = this.actionInstance.getNodeParameter("channelId", 0);
const editMessageId = this.actionInstance.getNodeParameter("messageId", 0);
const newContent = this.actionInstance.getNodeParameter("newContent", 0);
const editChannel = (await this.client.channels.fetch(editChannelId));
if (!(editChannel === null || editChannel === void 0 ? void 0 : editChannel.isTextBased())) {
throw new Error("The provided channel is not a text channel!");
}
try {
const messageToEdit = await editChannel.messages.fetch(editMessageId);
const editedMessage = await messageToEdit.edit(newContent);
data.success = true;
data.message = "Message edited successfully.";
data.editedMessageId = editedMessage.id;
}
catch (error) {
throw new Error(`Failed to edit message: ${error.message}`);
}
break;
case types_1.ActionEventType.REACT_TO_MESSAGE:
const reactChannelId = this.actionInstance.getNodeParameter("channelId", 0);
const reactMessageId = this.actionInstance.getNodeParameter("messageId", 0);
const emoji = this.actionInstance.getNodeParameter("emoji", 0);
const reactChannel = (await this.client.channels.fetch(reactChannelId));
if (!(reactChannel === null || reactChannel === void 0 ? void 0 : reactChannel.isTextBased())) {
throw new Error("The provided channel is not a text channel!");
}
try {
const messageToReact = await reactChannel.messages.fetch(reactMessageId);
await messageToReact.react(emoji);
data.success = true;
data.message = "Reaction added successfully.";
}
catch (error) {
throw new Error(`Failed to add reaction: ${error.message}`);
}
break;
case types_1.ActionEventType.PIN_MESSAGE:
const pinChannelId = this.actionInstance.getNodeParameter("channelId", 0);
const pinMessageId = this.actionInstance.getNodeParameter("messageId", 0);
const pinChannel = (await this.client.channels.fetch(pinChannelId));
if (!(pinChannel === null || pinChannel === void 0 ? void 0 : pinChannel.isTextBased())) {
throw new Error("The provided channel is not a text channel!");
}
try {
const messageToPin = await pinChannel.messages.fetch(pinMessageId);
await messageToPin.pin();
data.success = true;
data.message = "Message pinned successfully.";
}
catch (error) {
throw new Error(`Failed to pin message: ${error.message}`);
}
break;
case types_1.ActionEventType.UNPIN_MESSAGE:
const unpinChannelId = this.actionInstance.getNodeParameter("channelId", 0);
const unpinMessageId = this.actionInstance.getNodeParameter("messageId", 0);
const unpinChannel = (await this.client.channels.fetch(unpinChannelId));
if (!(unpinChannel === null || unpinChannel === void 0 ? void 0 : unpinChannel.isTextBased())) {
throw new Error("The provided channel is not a text channel!");
}
try {
const messageToUnpin = await unpinChannel.messages.fetch(unpinMessageId);
await messageToUnpin.unpin();
data.success = true;
data.message = "Message unpinned successfully.";
}
catch (error) {
throw new Error(`Failed to unpin message: ${error.message}`);
}
break;
case types_1.ActionEventType.REMOVE_REACTION:
const removeReactChannelId = this.actionInstance.getNodeParameter("channelId", 0);
const removeReactMessageId = this.actionInstance.getNodeParameter("messageId", 0);
const removeEmoji = this.actionInstance.getNodeParameter("emoji", 0);
const removeReactChannel = (await this.client.channels.fetch(removeReactChannelId));
if (!(removeReactChannel === null || removeReactChannel === void 0 ? void 0 : removeReactChannel.isTextBased())) {
throw new Error("The provided channel is not a text channel!");
}
try {
const messageToRemoveReact = await removeReactChannel.messages.fetch(removeReactMessageId);
const reaction = messageToRemoveReact.reactions.cache.find((r) => r.emoji.name === removeEmoji || r.emoji.toString() === removeEmoji);
if (reaction) {
if (!this.client.user)
throw new Error("Client user is not initialized");
await reaction.users.remove(this.client.user.id);
data.success = true;
data.message = "Reaction removed successfully.";
}
else {
throw new Error("Reaction not found on the message.");
}
}
catch (error) {
throw new Error(`Failed to remove reaction: ${error.message}`);
}
break;
default:
throw new Error(`Action "${action}" is not supported.`);
}
return data;
}
}
exports.ActionEventHandler = ActionEventHandler;
//# sourceMappingURL=ActionEventHandler.js.map