Discord.js has a presenceUpdate event with oldPresence and newPresence objects. Various posts I've seen here and elsewhere say to use these to detect when a user enters/leaves a game and what game it is, but v14 presenceUpdate objects don't make this information clear.
I've sort of gotten around this, but my solution isn't stable or reliable. The oldPresence object has a frozenPresence property which will list a game if the user was playing it in the oldPresence. The newPresence object has a map of all presences on the guild, so I can find the user the presence applies to with their userID and find the game listed in that presence.
But sometimes presenceUpdate fires when a user hasn't left or entered a game, so this results in funky behavior and sometimes crashes. Actual code below. Welcome any suggestions.
discordClient.on("presenceUpdate", (oldMember, newMember) => {
let user = oldMember.user.username;
let userID = newMember.user.id
if(oldMember.frozenPresence.game != null && newMember.frozenPresence == null) {
if(oldMember.frozenPresence.game.name != null) {
let game = oldMember.frozenPresence.game.name;
sendGroupMeMessage(user + " has stopped playing " + game, () => {});
}
}
else {
newMember.guild.presences.forEach((value, key) => {
if (key == userID) {
sendGroupMeMessage(user + " is playing " + value.game.name, () => {});
}
});
}
});