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

@ -43,29 +43,36 @@ class DiscordClient extends Client {
async broadcast(message) {
const msg = await this.formatMessageForForward(message);
const mentioned_user = this.getMentionedUsers(message.text);
const mentioned_users = this.getMentionedUsers(message.text);
const userToChanMap = new Map();
mentioned_user.forEach((user) =>
userToChanMap.set(user, this.findUserChannels(user))
const mentionned_users_info = new Map();
mentioned_users.forEach((user) =>
mentionned_users_info.set(
user,
this.getUserInfoFromMention(user.replace("@", "")),
),
);
for (const chan of this.trackedChannelsIds) {
const chan_msg = new Message();
chan_msg.copy(msg);
for (let [user, user_chans] of userToChanMap) {
for (let [user, user_info] of mentionned_users_info) {
if (
user_chans.includes(chan) &&
!user_chans.includes(chan_msg.channel)
user_info.channels.includes(chan) &&
!user_info.channels.includes(chan_msg.channel)
) {
const user_id = this.getUserIdOfUserInChan(
chan,
user.replace("@", "")
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) + ">",
);
chan_msg.text = chan_msg.text.replace(user, "<@" + user_id + ">");
userToChanMap.delete(user);
mentionned_users_info.delete(user);
}
}
@ -87,7 +94,8 @@ class DiscordClient extends Client {
getUserIdOfUserInChan(chan, username) {
return this.channelsGuilds
.get(chan)
.members.cache.find((member) => member.user.username === username).id;
.members.cache.find((member) => member.user.username === username)
?.id;
}
getMentionedUsers(text) {
@ -98,21 +106,27 @@ class DiscordClient extends Client {
return matches.map((str) => str[0].trim());
}
findUserChannels(user_name) {
const channels = [];
for (const [guildId, membersMap] of this.guildsMembers) {
for (const [memberId, member] of membersMap) {
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) {
// Found the user, now find a readable channel
// 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(memberId, channel)) {
channels.push(channelId);
if (this.memberCanReadChannel(member, channel)) {
info.channels.push(channelId);
}
}
}
}
}
return channels;
return info;
}
sendTextInChannel(text, chan) {
@ -121,19 +135,16 @@ class DiscordClient extends Client {
?.send(text)
.then(() => {})
.catch((error) =>
this.log("when trying to send message in ", chan, " got ", 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;
}
memberCanReadChannel(member, channel) {
const permissions = channel.permissionsFor(member);
return permissions && permissions.has("ViewChannel");
}
@ -150,7 +161,10 @@ class DiscordClient extends Client {
channelToGuildMap.set(channel.id, channel.guild);
}
} catch (error) {
console.error(`Error fetching channel with ID ${channelId}:`, error);
console.error(
`Error fetching channel with ID ${channelId}:`,
error,
);
}
}
@ -178,13 +192,24 @@ class DiscordClient extends Client {
guildsMembersMap.set(guildId, membersMap);
} catch (error) {
console.error(`Error fetching members for guild ${guildId}:`, 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 {
@ -196,15 +221,26 @@ class DiscordClient extends Client {
}
this.channelsGuilds = await this.mapChannelIdsToGuild(
this.trackedChannelsIds
);
this.guildsMembers = await this.getGuildsMembers(
Array.from(this.channelsGuilds.values())
this.trackedChannelsIds,
);
this.refreshMembersCache();
for (const chanId of this.trackedChannelsIds) {
this.trackedChannels.set(chanId, await this.channels.fetch(chanId));
this.trackedChannels.set(
chanId,
await this.channels.fetch(chanId),
);
}
});
this.on("guildMemberAdd", (member) => {
this.refreshMembersCache();
});
this.on("guildMemberRemove", (member) => {
this.refreshMembersCache();
});
}
}

View file

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