#bot.tree.command(name="user", description="Shows some informations about the mentioned user.")
async def user(interaction: discord.Interaction, member:discord.Member=None):
if member == None:
member = interaction.user
roles = [role for role in member.roles if role.name != "#everyone"]
embed = discord.Embed(title=f"Details about the user, {member.name}",color=0xdaddd8, timestamp = datetime.datetime.utcnow())
embed.set_thumbnail(url=member.avatar) # Avatar Thumbnail
embed.add_field(name="👤 Name", value = f"{member.name}#{member.discriminator}") # Embeds
embed.add_field(name="🏷️ Nickname", value = member.display_name)
embed.add_field(name="🆔 User ID", value = member.id)
embed.add_field(name="📆 Created at", value = member.created_at.strftime("%D \n%I:%M %p"))
embed.add_field(name="👋🏻 Joined at", value = member.joined_at.strftime("%D \n%I:%M %p"))
embed.add_field(name="🟢 Status", value = member.status) #this line is'nt working as it should
embed.add_field(name="❤️🔥 Top role", value = member.top_role.mention)
bot_status = "Yes, it is" if member.bot else "No, They'snt"
embed.add_field(name="🤖 Bot?", value = bot_status)
embed.set_footer(text = interaction.user.name,icon_url = interaction.user.avatar)
await interaction.response.send_message(embed=embed)
I made a User information command and this command shows every person offline even itself how can i fix it?
This is likely due to lack of intents.
Add in your code, under the intents you define:
intents.members = True
intents.presences = True
Use member.raw_status instead of member.status. It will return a string value such as 'online', 'offline' or 'idle'.
Related
I wanted to write a mute command for a bot in the discord. The command does not work. Here's the code and the error
#bot.tree.command(name="mute", description="Мьют участника")
#app_commands.checks.has_permissions( administrator = True )
async def mute( interaction: discord.Interaction, member: discord.Member,reason: str = None ):
await interaction.response.defer( thinking = True )
await interaction.channel.purge( limit = 1 )
mute_role = discord.utils.get ( interaction.guild.roles, id = '1061014280922746887', name = 'muted' )
await member.add_roles( mute_role )
await interaction.channel.send( embed = discord.Embed(
title="Участник успешно замьючен",
description= ( f"{member.mention} **был замьючен модератором** {interaction.user.mention}! "),
color=discord.Color.from_str("#C3F")
))
error
I was trying to recreate the role of mute. Change interaction.guild.roles to interaction.message.guild.roles
ID's are ints, not strings. You're passing a string to utils.get, so nothing is found and mute_role is None, as your error message is telling you.
discord.utils.get(interaction.guild.roles,id='1061014280922746887',name='muted')
# ^^^^^^^^^^^^^^^^^^^^^ string
Pass the ID as an int instead.
Docs for Role.id: https://discordpy.readthedocs.io/en/stable/api.html#discord.Role.id
Type:
int
I'm trying to make a add role and remove role command, I've tried before and given up since I could never get my head around it. I want the command to allow someone to mention a user then mention a role and give/take that role to/from the user. The command doesn't give the role and it seems like content.replace doesnt work either. Here is my code for the give role command:
module.exports = {
name: "addrole",
description: "Give a role to a user",
aliases: ["+role", "giverole", "give-role"],
cooldown: 3,
permissions: "MANAGE_ROLES",
execute(msg, args){
const Discord = require('discord.js');
require("discord-reply")
const { colour } = require('../config.json')
const { version } = require('../config.json')
const { prefix } = require('../config.json')
let user = msg.mentions.users.first() || msg.author
//v e.g $ addrole #user test role = test role
let r1 = msg.content.replace(`${prefix} ${args[2]} ${user} `, ``)//removes everything before role name
//^ content.replace doesn't seem to work
let role = msg.guild.roles.cache.find(r => r.name === r1);
if (!r1) { //checks for anything after the user
msg.channel.send("You need to give a role name")
} else if (!role) {
msg.channel.send("That role doesn't exist")
} else return
user.roles.add(role).catch(console.error);
console.log(`Made it this far`)
}
}
In my modest experience I think your args[2] does not exist because, according to your snippet, you should've already created a messageCreate event and defined command. So try using:
let r1 = msg.content.replace(`${prefix}role ${user}`, ``)
// Or ${prefix}addrole/+role ${user}
let role = msg.guild.roles.cache.find(r => r.name === r1);
I am trying to make a jail command when the members who has this role leave the server and rejoin again the role stay with them ,i want when new members enter the server to compare their ID with the one in the database, if is it true it gives a role again. my code:
client.on("guildMemberAdd",async (member)=>{
let injail = await db.fetch(`ja_${member.guild.id}`)
let role = msg.guild.roles.cache.find(n => n.name === 'Jail');
if(member.guild.id = injail){
member.roles.remove(user.roles.cache)
member.roles.add(role)
}
});
client.on('message', msg => {
if(msg.content.startsWith(prefix + 'jail')){
if(!owners.includes(msg.author.id)) return msg.channel.send("**You Dont Have Perms 📛**")
if(!msg.channel.guild) return;
var logChannel = msg.guild.channels.cache.find(channel => channel.id === logID)//LOG
let jailRole = msg.guild.roles.cache.find(n => n.name === 'Jail');
let user = msg.mentions.members.first() //You can change this to an ID
let args = msg.content.split(" ").slice(1).join(" ")
if(!args[0]) return msg.channel.send('**:x: Please Mention A User**')
if(user.hasPermission("ADMINISTRATOR")) return msg.channel.send("**Im NOT Allowed To Do This 📛**")
let there = db.get(`jl_${msg.guild.id}_${user}`, user.id)
if (there) return msg.channel.send('**This User AlREADY In Jail ⛔**')
msg.channel.send(`**ADDED ${user} to the Jail! ✅**`)
db.set(`jl_${msg.guild.id}_${user}`, user.id)
user.roles.remove(user.roles.cache)
user.roles.add(jailRole)
let embed = new Discord.MessageEmbed()
.setTitle('Jail System')
.setAuthor(msg.author.tag,msg.author.avatarURL({dynamic:true}))
.addField("Status",`JOINED THE JAIL 🔴`)
.addField("User",`<#${user.id}> (ID: ${user.id})`)
.addField("By",`<#${msg.author.id}> (ID: ${msg.author.id})`)
.setTimestamp()
logChannel.send(embed)
}
});
Whenever people gets "jail" role, save "yes" to database.
and check condition as you did above.
here I'll give sample code:
// when people gets jail role, add following code:
db.set(`ja_${msg.guild.id}_${user}`, "yes") // or you can simply use boolean operator
// when guildMemberAdd event triggers check condition:
let condition = db.fech(`ja_${member.guild.id}_${member.user.id}`)
if(condition === "yes"){
// write code to add "jail" role to the member
}
else{
// your other code
}
Also don't forget to set "no" in the database whenever you remove jail role from member.
I have imported everything needed for the command.
So, the issue here is, in the condition for executing the command (checking if the user said yes/no or something weird which terminates the command)
#commands.command()
#commands.has_permissions(manage_channels=True)
async def nuke(self, ctx,*, channel = None, reason = None):
if reason is None:
reason = "No reason was specified!"
if channel is None:
channel = ctx.channel
p = time.strftime(f'Today at %H:%M %p')
embei = discord.Embed(color=0xa3a3ff, title = ":warning: ALERT ALERT ALERT :warning: ", description=f"{ctx.author.mention} Are you sure you want to delete {ctx.channel.mention}? y/n")
await ctx.send(embed=embei)
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
The part with the issue
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
when I execute the command, it does ask me for the confirmation as expected, however, the reply here doesn't matter as it always executes the else statement. I thought the issue was with indentation and so I tried fixing that but that too didn't work. Does anyone know about the issue here I might be facing?
Extra: Before Adding user confirmation, the code was working absolutely fine! (It created a clone of the channel, sent the embed there saying it nuked the original channel, and deleted the original channel)
For this question of mine, the string.lower() is a method which I need to call, which was mentioned to me by Lukasz. I was using the string.lower() in the wrong way.
To Fix the problem I had, I declared two lists a and b
a=["y", "yes"]
b = ["n", "no"]
and changed
if msg.content.lower in ("y", "yes"):
elif msg.content.lower in ("n", "no"):
to
if msg.content in a:
elif msg.content in b:
and the issue was fixed.
I'm someone who just got into coding recently.
I'm trying to create a Discord bot that can do custom roles that can allow a user of that custom role to edit its hex or name.
There's also the creation of a role creator that also assigns the mentioned user the role.
My problem is that I've encountered an issue with the role creation + assignment and the commands that allow the user to edit their role.
Here are the problems:
(node:6288) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined for the role creator command
When I try to use the commands that allow the user to customize their roles, the commands don't work, or to be more specific, they don't activate.
I do believe that the codes I'm using could be outdated, therefore if that is the case, please give me the exact location and the right code.
Here are some pictures of the codes. I've pasted the codes below, but I'm a bit new to this forum, so please pay attention to the separating pieces like "Role Customization Code:" to distinguish which one's which. For some reason, the module.exports aren't going in there. Please describe and let me know a solution to these problems in a specific way since I am a newbie at this topic.
Role creation command + assignment error.
Role creation command + assignment code part 1.
Role creation command + assignment code part 2.
Role customization code part 1.
Role customization code part 2.
Role customization code part 3.
Role creation + assignment code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
if (!args[0]) return message.channel.send("Please specify a user to add!");
let toAdd = message.guild.members.get(args[0]) || message.guild.members.get(message.mentions.users.first().id);
let rolejoin = args.slice(1).join(" ");
let myRole = message.guild.roles.cache.get((val) => val.name.toLowerCase() === rolejoin.toLowerCase());
if (!toAdd) return message.channel.send("User not found!");
if (!rolejoin) return message.channel.send("Please specify a role to add!");
let botRole = message.guild.members.get(bot.user.id).highestRole;
let isPosition = botRole.comparePositionTo(myRole);
if (isPosition <= 0) return message.channel.send(embedFail("This role is higher than me, I cannot add this role!"));
let res = await query(`SELECT * FROM user_roles WHERE role_id='${myRole.id}'`);
if (res[0]) {
await query(`DELETE FROM user_roles where role_id='${myRole.id}'`);
toAdd.removeRole(myRole);
message.channel.send(embedSuccess(`Removed role ${myRole.name} from ${toAdd.user.username}`));
} else if (!res[0]) {
await query(`INSERT INTO user_roles (guild_id, user_id, role_id) VALUES ('${message.guild.id}',${toAdd.id},'${myRole.id}')`);
toAdd.addRole(myRole);
message.channel.send(embedSuccess(`Adding role ${myRole.name} to ${toAdd.user.username}`));
}
};
Role Customization Code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args, db) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
let res = await query(`SELECT * FROM user_roles WHERE guild_id = '${message.guild.id}' AND user_id = '${message.author.id}'`);
if (!args[0]) {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
let assignNames = "";
let embed = new Discord.RichEmbed()
.setAuthor(`Current role assigned to ${message.author.username}`, message.guild.iconURL)
.setColor(myRole.hexColor)
.addField(`Name`, `${myRole.name}`, true)
.addField(`Colour`, `${myRole.hexColor}`, true);
message.channel.send(embed);
} else {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
if (!myRole) {
await query(`DELETE FROM user_roles where guild_id = '${message.guild.id}' AND role_id = '${res[i].role_id}' and user_id = '${res[i].user_id}'`);
return message.channel.send(embedFail("You do not have a role!"));
}
switch (args[0]) {
case "name":
let name = args.slice(1).join(" "),
oldName = myRole.name;
await myRole.setName(name);
await message.channel.send(embedSuccess(`You have changed ${oldName}'s name to ${name}!`));
break;
case "color":
case "color":
let hexCode = args[1],
oldHex = myRole.hexColor;
await myRole.setColor(hexCode);
await message.channel.send(embedSuccess(`You have changed ${myRole.name}'s color from ${oldHex} to #${hexCode}!`));
break;
}
}
};