use discord js built in cache, and update cache when user join or leave guild

This commit is contained in:
vincent 2025-03-04 21:52:50 +01:00
parent 8633a7538d
commit bea6ed2fe2
2 changed files with 217 additions and 184 deletions

View file

@ -2,210 +2,246 @@ const { Client } = require("discord.js");
const { Message } = require("../../Bridge/class/Message"); const { Message } = require("../../Bridge/class/Message");
class DiscordClient extends Client { class DiscordClient extends Client {
constructor(bridge, verbose = false, channels) { constructor(bridge, verbose = false, channels) {
super({ super({
intents: [ intents: [
"Guilds", "Guilds",
"GuildMessages", "GuildMessages",
"GuildMessageReactions", "GuildMessageReactions",
"GuildMessageTyping", "GuildMessageTyping",
"GuildMembers", "GuildMembers",
"MessageContent", "MessageContent",
], ],
}); });
this.bridge = bridge; this.bridge = bridge;
this.verbose = verbose; this.verbose = verbose;
this.trackedChannelsIds = channels; this.trackedChannelsIds = channels;
this.trackedChannels = new Map(); this.trackedChannels = new Map();
this.channelsGuilds = new Map(); this.channelsGuilds = new Map();
this.guildsMembers = new Map(); this.guildsMembers = new Map();
this.on("messageCreate", (msg) => { this.on("messageCreate", (msg) => {
this.log("message recived", msg); this.log("message recived", msg);
// catch self messages // catch self messages
if (msg.author.id == this.user.id) return; if (msg.author.id == this.user.id) return;
// only propagate messages from tracked channels // only propagate messages from tracked channels
if (!this.trackedChannelsIds.includes(msg.channelId)) return; if (!this.trackedChannelsIds.includes(msg.channelId)) return;
const internal_msg = new Message(); const internal_msg = new Message();
internal_msg internal_msg
.fromDiscordFormat(msg, this) .fromDiscordFormat(msg, this)
.then(() => this.bridge.broadcast(internal_msg)); .then(() => this.bridge.broadcast(internal_msg));
}); });
}
log(...args) {
if (this.verbose) console.log("[Discord]", ...args);
}
async broadcast(message) {
const msg = await this.formatMessageForForward(message);
const mentioned_user = this.getMentionedUsers(message.text);
const userToChanMap = new Map();
mentioned_user.forEach((user) =>
userToChanMap.set(user, this.findUserChannels(user))
);
for (const chan of this.trackedChannelsIds) {
const chan_msg = new Message();
chan_msg.copy(msg);
for (let [user, user_chans] of userToChanMap) {
if (
user_chans.includes(chan) &&
!user_chans.includes(chan_msg.channel)
) {
const user_id = this.getUserIdOfUserInChan(
chan,
user.replace("@", "")
);
chan_msg.text = chan_msg.text.replace(user, "<@" + user_id + ">");
userToChanMap.delete(user);
}
}
if (chan != msg.channel) {
// do not send in the channel the message is comming from
this.sendTextInChannel(chan_msg.text, chan);
}
} }
}
async formatMessageForForward(msg) { log(...args) {
const res_msg = { ...msg }; if (this.verbose) console.log("[Discord]", ...args);
}
res_msg.text = `[**${msg.author}**]: ${res_msg.text}`; async broadcast(message) {
const msg = await this.formatMessageForForward(message);
return res_msg; const mentioned_users = this.getMentionedUsers(message.text);
}
getUserIdOfUserInChan(chan, username) { const mentionned_users_info = new Map();
return this.channelsGuilds mentioned_users.forEach((user) =>
.get(chan) mentionned_users_info.set(
.members.cache.find((member) => member.user.username === username).id; user,
} this.getUserInfoFromMention(user.replace("@", "")),
),
);
getMentionedUsers(text) { for (const chan of this.trackedChannelsIds) {
const regex = /@\S*(?=\s|$)/g; const chan_msg = new Message();
chan_msg.copy(msg);
const matches = [...text.matchAll(regex)]; for (let [user, user_info] of mentionned_users_info) {
if (
user_info.channels.includes(chan) &&
!user_info.channels.includes(chan_msg.channel)
) {
this.log(
"replaced with",
"<@" + (user_info.id ? user_info.id : user) + ">",
);
// mentionned user is in the channel we are sending to, and not in the channel we are sending from
chan_msg.text = chan_msg.text.replace(
user,
"<@" + (user_info.id ? user_info.id : user) + ">",
);
return matches.map((str) => str[0].trim()); mentionned_users_info.delete(user);
} }
}
findUserChannels(user_name) {
const channels = []; if (chan != msg.channel) {
for (const [guildId, membersMap] of this.guildsMembers) { // do not send in the channel the message is comming from
for (const [memberId, member] of membersMap) { this.sendTextInChannel(chan_msg.text, chan);
if (member.user.username === user_name) {
// Found the user, now find a readable channel
for (const [channelId, channel] of this.trackedChannels) {
if (this.memberCanReadChannel(memberId, channel)) {
channels.push(channelId);
} }
}
} }
}
}
return channels;
}
sendTextInChannel(text, chan) {
this.channels.cache
.get(chan)
?.send(text)
.then(() => {})
.catch((error) =>
this.log("when trying to send message in ", chan, " got ", error)
);
}
memberCanReadChannel(userId, channel) {
const guildId = this.channelsGuilds.get(channel.id);
const member = this.guildsMembers.get(guildId).get(userId);
if (!member.guild) {
console.log("Member not part of a guild");
return false;
} }
const permissions = channel.permissionsFor(member); async formatMessageForForward(msg) {
return permissions && permissions.has("ViewChannel"); const res_msg = { ...msg };
}
async mapChannelIdsToGuild(channelIds) { res_msg.text = `[**${msg.author}**]: ${res_msg.text}`;
const channelToGuildMap = new Map();
for (let i = 0; i < channelIds.length; i++) { return res_msg;
const channelId = channelIds[i]; }
try {
const channel = await this.channels.fetch(channelId);
if (channel.guild) { getUserIdOfUserInChan(chan, username) {
channelToGuildMap.set(channel.id, channel.guild); return this.channelsGuilds
.get(chan)
.members.cache.find((member) => member.user.username === username)
?.id;
}
getMentionedUsers(text) {
const regex = /@\S*(?=\s|$)/g;
const matches = [...text.matchAll(regex)];
return matches.map((str) => str[0].trim());
}
getUserInfoFromMention(user_name) {
const info = {
channels: [],
id: null,
};
for (const [chan, guild] of this.channelsGuilds) {
for (const [member_id, member] of guild.members.cache) {
this.log(member);
if (member.user.username === user_name) {
// maybe also check against global name and displayname
info.id = member.user.id;
// Found the user, now find readable channels
for (const [channelId, channel] of this.trackedChannels) {
if (this.memberCanReadChannel(member, channel)) {
info.channels.push(channelId);
}
}
}
}
} }
} catch (error) { return info;
console.error(`Error fetching channel with ID ${channelId}:`, error);
}
} }
return channelToGuildMap; sendTextInChannel(text, chan) {
} this.channels.cache
.get(chan)
async getGuildMembers(guildId) { ?.send(text)
const guild = await this.guilds.fetch(guildId); .then(() => {})
const members = await guild.members.fetch(); .catch((error) =>
this.log(
const memberMap = new Map(); "when trying to send message in ",
members.forEach((member) => { chan,
memberMap.set(member.id, member); " got ",
}); error,
),
return memberMap; );
}
async getGuildsMembers(guildIds) {
const guildsMembersMap = new Map();
for (const guildId of guildIds) {
try {
const membersMap = await this.getGuildMembers(guildId);
guildsMembersMap.set(guildId, membersMap);
} catch (error) {
console.error(`Error fetching members for guild ${guildId}:`, error);
}
} }
return guildsMembersMap; memberCanReadChannel(member, channel) {
} const permissions = channel.permissionsFor(member);
return permissions && permissions.has("ViewChannel");
}
start() { async mapChannelIdsToGuild(channelIds) {
return new Promise(async (resolve, reject) => { const channelToGuildMap = new Map();
try {
await this.login(process.env.DISCORD_TOKEN);
this.log("Client connected");
resolve();
} catch (error) {
reject(error);
}
this.channelsGuilds = await this.mapChannelIdsToGuild( for (let i = 0; i < channelIds.length; i++) {
this.trackedChannelsIds const channelId = channelIds[i];
); try {
this.guildsMembers = await this.getGuildsMembers( const channel = await this.channels.fetch(channelId);
Array.from(this.channelsGuilds.values())
); if (channel.guild) {
for (const chanId of this.trackedChannelsIds) { channelToGuildMap.set(channel.id, channel.guild);
this.trackedChannels.set(chanId, await this.channels.fetch(chanId)); }
} } catch (error) {
}); console.error(
} `Error fetching channel with ID ${channelId}:`,
error,
);
}
}
return channelToGuildMap;
}
async getGuildMembers(guildId) {
const guild = await this.guilds.fetch(guildId);
const members = await guild.members.fetch();
const memberMap = new Map();
members.forEach((member) => {
memberMap.set(member.id, member);
});
return memberMap;
}
async getGuildsMembers(guildIds) {
const guildsMembersMap = new Map();
for (const guildId of guildIds) {
try {
const membersMap = await this.getGuildMembers(guildId);
guildsMembersMap.set(guildId, membersMap);
} catch (error) {
console.error(
`Error fetching members for guild ${guildId}:`,
error,
);
}
}
return guildsMembersMap;
}
async refreshMembersCache() {
for (const [channel, guild] of this.channelsGuilds) {
guild.members.fetch().then((members) => {
this.log("members cache loaded for ", guild.name);
});
}
}
start() {
return new Promise(async (resolve, reject) => {
try {
await this.login(process.env.DISCORD_TOKEN);
this.log("Client connected");
resolve();
} catch (error) {
reject(error);
}
this.channelsGuilds = await this.mapChannelIdsToGuild(
this.trackedChannelsIds,
);
this.refreshMembersCache();
for (const chanId of this.trackedChannelsIds) {
this.trackedChannels.set(
chanId,
await this.channels.fetch(chanId),
);
}
});
this.on("guildMemberAdd", (member) => {
this.refreshMembersCache();
});
this.on("guildMemberRemove", (member) => {
this.refreshMembersCache();
});
}
} }
module.exports = DiscordClient; module.exports = DiscordClient;

View file

@ -1,8 +1,5 @@
{ {
"verbose": true, "verbose": true,
"discordChannels": [ "discordChannels": ["1161739009614151751", "727212463988146206"],
"1161739009614151751", "ircChannels": ["#urlab"]
"727212463988146206"
],
"ircChannels": ["#urlab"]
} }