discord.js v12 info command always showing offline status - discord.js

So I'm trying to make a command that show info about a specific user, the command works fine but the status of the user always shows as offline
This is the main part of the info code that shows the status of the user
if (user.presence.status === 'online') status = `${client.config.emojis.ONLINE}Online` ;
if (user.presence.status === 'idle') status = `${client.config.emojis.IDLE}Idle`;
if (user.presence.status === 'dnd') status = `${client.config.emojis.DND}Dnd`;
if (user.presence.status === 'offline') status = `${client.config.emojis.OFFLINE}Offline`;
if (user.presence.clientStatus != null && user.presence.clientStatus.desktop === 'online') plateforme = '🖥️ desktop'
if (user.presence.clientStatus != null && user.presence.clientStatus.mobile === 'online') plateforme = '📱 Mobile'
let permissions_arr = userInfo.permissions.toArray().join(', ');
let permissions = permissions_arr.toString()
permissions = permissions.replace(/\_/g, ' ');
const embedMember = new MessageEmbed()
embedMember.setFooter(`ID: ${userInfo.user.id}`,``,true)
embedMember.setThumbnail(userInfo.user.displayAvatarURL({ dynamic: true }))
embedMember.setColor(`${client.config.color.EMBEDCOLOR}`)
embedMember.setTitle(`${userInfo.user.tag}`)
embedMember.addField('Joined:', `${moment.utc(userInfo.joinedAt).format('MMMM Do YYYY \n -HH:mm')}`, true)
embedMember.addField('Account created:', `${moment.utc(userInfo.user.createdAt).format('MMMM Do YYYY \n -HH:mm')}`, true)//
embedMember.addField('Status:', `${status}`, true)
embedMember.addField('Roles:', `${userInfo.roles.cache.map(r => r.toString()).join(' ')}`)
message.channel.send(embedMember);

User status is part of the user's presence. In order to access the presence of guild members, you must subscribe to the GUILD_PRESENCES intent. This is what the construction of your Client object will need to look like:
const bot_intents = ["GUILD_PRESENCES"];
const client = new Discord.Client({intents: bot_intents, ws:{intents: bot_intents}});
Because presences are a privileged intent, you will also need to go to your bot's application page in the Discord Developer Portal and enable this setting:
You can, of course, add any other intents you may need/want to the bot_intents variable. This answer assumes you are not already using the GUILD_PRESENCES intent, as you did not mention it in your question.

Related

How to remove a role in discord.py without discord.ext

I want to remove a role from a user without using discord.ext ( because of certain resons I can't ) but I don't know how to do it ( so without commands ( by commands I mean #bot.commands....), and without ctx )
If you want this is the code where I want to put the thing that will remove the role :
if message.content.startswith('$rmv_role'):
member4 = message.content
member5 = member4.split()
member6 = member5[1]
server_id = message.guild.id
guild = client.get_guild(server_id)
role_id = 999988854696194048
role = discord.utils.get(guild.roles, id=role_id)
await message.delete()
user_id = ''.join(c for c in member6 if c.isdigit())
user = get(bot.get_all_members(), id=user_id)
*the code that remove roles*
return
discord.Member has a method called remove_roles().
So, the code is following:
await user.remove_roles(role)

Discord.js target, cache user id

I want the bot to cache the user id, this is what I got
let target = message.mentions.users.first() || ??? || message.author;
Here you go:
message.guild.members.cache.get(args[0])

Unable to Assign Role with member.roles.add (id)

I'm trying to make an assignrole command which takes userID and roleID as arguments.
content = message.content.slice(message.content.indexOf(' ')+1)
args = content.split(', ');
const userID = args[0]
const roleID = args[1]
const desiredUser = message.guild.members.cache.get(userID)
const desiredRole = message.guild.roles.cache.get(roleID)
if (desiredUser != undefined){
if (desiredRole != undefined){
usern = desiredUser.user.username
desiredUser.roles.add(roleID).catch(console.error);
message.channel.send(usern + " has been assigned the "+ desiredRole.name +" role")
console.log("added role")
} else {
message.channel.send("role with ID " + roleID + " does not exist")
}
} else {
message.channel.send("user with ID " + userID + " does not exist")
}
The function succeeds at "getting" the correct user and role, and successfully sends the "USER has been assigned the ROLENAME role" message. However, the role itself isn't actually added to the user!
My console throws a DiscordAPIError: Missing Permissions error, but I don't know how to interpret it. The error does not quit the bot, however.
How do I add the role to the user?
It is likely that you are missing the MANAGE_ROLES permission as it is, like the name would suggest, required to manage rules.
https://discord.com/developers/docs/topics/permissions
Here are other possibilities that may be causing the error:
I found these here
It is trying to execute an action on a guild member with a role higher than or equal to your bots highest role.
It is trying to modify or assign a role that is higher than or equal to its highest role.
It is trying to execute a forbidden action on the server owner.

How to make by bot to leave a server with a guild id

I want my bot to leave a discord server by using ;leave <GuildID>.
The code below does not work:
if (message.guild.id.size < 1)
return message.reply("You must supply a Guild ID");
if (!message.author.id == 740603220279164939)
return;
message.guild.leave()
.then(g => console.log(`I left ${g}`))
.catch(console.error);
You're most likely not supposed to be looking at message.guild.id, since that returns the ID of the guild you're sending the message in. If you want to get the guild ID from ;leave (guild id), you'll have to cut out the second part using something like .split().
// When split, the result is [";leave", "guild-id"]. You can access the
// guild ID with [1] (the second item in the array).
var targetGuild = message.content.split(" ")[1];
!message.author.id will convert the author ID (in this case, your bot ID) into a boolean, which results to false (since the ID is set and is not a falsy value). I'm assuming that you mean to have this run only if it the author is not the bot itself, and in that case, you're most likely aiming for this:
// You're supposed to use strings for snowflakes. Don't use numbers.
if (message.author.id == "740603220279164939") return;
And now, you just have to use the guild ID that you got from the message content and use that to leave the guild. To do that, just grab the Guild from your bot cache, and then call .leave(). All in all, your code should now look like this:
// Get the guild ID
var targetGuild = message.content.split(" ")[1];
if (!targetGuild) // targetGuild is undefined if an ID was not supplied
return message.reply("You must supply a Guild ID");
if (message.author.id == "740603220279164939") // Don't listen to self.
return;
client.guilds.cache.get(targetGuild) // Grab the guild
.leave() // Leave
.then(g => console.log(`I left ${g}`)) // Give confirmation after leaving
.catch(console.error);

How would i get live updates when a user joins and leaves a discord voice channel

Is there a way too do a callback or a background task to see when a user joins and leaves a voicechannel? Currently when I cmd the bot I only am able to see the users that are currently in the voicechannel only. Sorry if it might not make sense.
import asyncio
import config
client = discord.Client()
#client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
#Voice channel
lobby_voicechannel = client.get_channel(708339994871463986)
#Text channel
txt_channel = client.get_channel(702908501533655203)
team_one = []
team_two = []
member_id = []
lobby_queue = lobby_voicechannel.members
for x in lobby_queue:
#change mention to name or nick for variations
member_id.append(x.mention)
player_num = len(member_id)
joined_user = str(member_id)
#check how many players in total for queue
if player_num == 5:
user_convert = tuple(member_id)
embed = discord.Embed(
title="**{}/10** players joined `{}`".format(player_num, lobby_voicechannel),
description="\n".join(user_convert),
color=0x00f2ff)
await txt_channel.send(delete_after=None, embed=embed)
else:
if player_num == 0:
embed = discord.Embed(
title="**{}/10** players joined `{}`".format(player_num, lobby_voicechannel),
description=f"***```No players in {lobby_voicechannel}```***",
color=0x00f2ff
)
await txt_channel.send(delete_after=None, embed=embed)
client.run(config.Token)```
You can use the on_voice_state_update event. This event gets triggered whenever a member joins/leaves or when a members state changes in a voice channel. For more info see link.
However you still need to check whether or not the member left/joined. This can be done through the before and after VoiceState objects received from the event: on_voice_state_update(member, before, after):.
Example:
#commands.Cog.listener()
async def on_voice_state_update(member, before, after):
if before.channel == None and after.channel != None:
state = 'joined'
else if before.channel != None and after.channel == None:
state = 'left'
else:
state = 'unchanged'
# Continue with some code

Resources