UrBridge/Bridge/class/Message.js
2026-04-07 21:16:06 +02:00

71 lines
2.3 KiB
JavaScript

export class Message {
constructor() {
this.text;
this.channel;
this.author;
this.source_type; // irc/discord...
}
async fromDiscordFormat(discord_message, discordClient) {
this.text = await this.escapeDiscordPing(
discord_message.content,
discordClient,
);
this.text += discord_message.attachments.map((a) => a.url).join("\n");
console.log("escaped text", this.text);
this.channel = discord_message.channelId;
this.author = discord_message.author.username; // using user name here so users in irc can use that info to cross ping
this.source_type = "discord";
}
fromIRCFormat(irc_message) {
((this.text = irc_message.message),
(this.channel = irc_message.target.toLowerCase()),
(this.author = irc_message.nick),
(this.source_type = "irc"));
}
fromMatrixFormat(matrix_message, channel) {
this.text = matrix_message.event.content.body;
this.channel = matrix_message.event.room_id;
this.author = matrix_message.getSender();
this.source_type = "matrix";
}
async escapeDiscordPing(text, client) {
let res_text = text;
const regex = /<@(\d+)>/g;
const matches = [...text.matchAll(regex)];
const userReplacements = [];
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
const userId = match[1];
try {
const user = await client.users.fetch(userId);
userReplacements.push({ match, username: user.username });
} catch (error) {
console.error("Error fetching user:", error);
userReplacements.push({ match, username: null });
}
}
for (let i = 0; i < userReplacements.length; i++) {
const { match, username } = userReplacements[i];
const replacement = username ? `@${username}` : match[0];
res_text = res_text.replace(match[0], replacement);
}
return res_text;
}
copy(msg) {
this.text = msg.text;
this.channel = msg.channel;
this.author = msg.author;
this.source_type = msg.source_type;
}
}