How make massban in discord.py? - discord

I used this command, but the bot not ban anyone and does not write an error to the console.
#bot.command()
async def massban(ctx):
for user in ctx.guild.members:
try:
await user.ban()
except:
pass

As Fixator also mentioned, you won't be able to see the error as far as you're excepting every error and passing it.
#bot.command()
async def massban(ctx):
for user in ctx.guild.members:
try:
await user.ban()
except Exception as error:
print(error)
pass
That's how you can catch the error without interrupting the for-loop.
Please also doublecheck the permissions of your bot and the member listing.

If you sure that bot has a ban perms on server.
Check if bot has enough cache for that operation. For example, send len(guild.members) into channel before iterating over members. If it says 1-2, you, most likely, dont have enough intents.
Bot can't ban users that has roles above bot's top role:

Related

Is there a way to have multiple arguments in a command with discord py

I’m creating a discord bot using discord py and would like to have a kick command that dms the user a reason upon being kicked.
-kick #user reason
When I kick the user with a reason attached it doesn’t kick the user and I get an error in console saying can not find the user
Here is the code
#client.command(aliases=['Kick'])
#commands.has_permissions(administrator=True)
async def kick(ctx,member : discord.Member,*,reason= 'no reason'):
await ctx.send(f'{member.name} was kicked from the Server!\nand a Dm was sendet by me as a Information for him')
await asyncio.sleep(5)
await ctx.channel.purge(limit=2)
await member.send(f'**You was kicked from {ctx.guild.name}\nthe Stuff Team dont tell me the reason?**')
await member.kick(reason=reason)
print(f"{ctx.author} ----> just used {prefix}kick")
And yes I have tried Google, the discord py API guide with no luck
Can anyone help? Thanks
You can give a nice error message. It raises MemberNotFound.
Then you can make a local error handler.
#kick.error
async def kick_command_error(ctx, err):
if isinstance(err, commands.MemberNotFound):
await ctx.send('Hey! The member you gave is invalid or was not found. Please try again by `#`mentioning them or using the ID.')

Unbanning a specific user

Important note: I'm not using the rewrite.
I've been trying to unban specific users on a message in discord.py with a command.
Example:
On the command "!unban," the bot unbans a user who was not mentioned in the command.
I've tried something like
#client.event
async def on_message(message):
if message.content == x:
await message.guild.unban('[User ID], *, reason=none')
which results in
await self._state.http.unban(user.id, self.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'
If anybody could help me out, I'd appreciate it. I'm pretty lost.
The proper usage of that command is guild.unban(user, reason=None). The asterisk is not required in a call to the function, and =None indicates that reason is optional. If you do not have a reason:
In your case:
await message.guild.unban(userID)
Should do the job, so long as your user ID is in the format of a snowflake object (e.g. a User object for that user!)

issues with dicord bot

#was making a sort of capcha system works on my main account with admin but after going on my alt #account and test getting this error even after giving ult admin
#bot.command(pass_context=True, name="cat")
#commands.has_permissions(manage_messages=True)
async def cat(ctx):
member = ctx.message.author
role = discord.utils.get(member.guild.roles, name="user")
await member.add_roles(role)
await ctx.channel.purge(limit=1)
Error:
#raise MissingPermissions(missing)
#discord.ext.commands.errors.MissingPermissions: You are missing Manage Messages permission(s) to #run this command.
I dont see why you would need help, the error is just telling you that the account does not have a role with that perm.

How to get permissions in discord js when we do direct message

I am trying to get a list of the permission that the user has in Discord. If it sends the message in the channel, it’s fine as we can use message.member.hasPermission, etc.
But what if the message is DM? I want my users to send a DM to the bot and the bot be able to check and see if the user has certain permissions.
I cannot find anything anywhere. I keep getting redirected to message.member, or message.guild which both are null when it’s in DM.
In DM no one has permissions. All you have is the permission to see messages and send messages which aren’t shown visually, or to bots. To make sure that it isn’t DM, just return if the channel type is dm, or guild is null.
if(!message.guild) return;
//before checking "perms"
If you want the permissions for a certain guild if the message is from DM, use this code
if(message.channel.type === 'dm') {
let guild = await client.guilds.fetch('THE ID OF THE GUILD YOU WANT TO SEE THE USER’S PERMS IN')
let member = await guild.members.fetch(message.author.id);
//you can now access member.permissions
}
Keep in mind await must be in an async callback.
You did not provide any code so I cannot give any more code than this.
You can fetch the member with the guild's context.
Fetching is recommended, as Guild#member() relies on cache and is also deprecated.
Member#hasPermission() will be deprecated as well, using MemberRoleManager#has() is recommended
The following example uses async/await, ensure you're inside an async function
// Inside async function
const guild = await client.guilds.fetch('guild-id');
const member = await guild.members.fetch(message.author.id);
const hasThisPermission = member.roles.cache.has('permission');

#commands.has_permissions(administrator=True) not working properly?

I am trying to make a simple moderator bot.
the code looks something like this.
import discord
from discord.ext import commands
from random import choice
import os
client = commands.Bot(command_prefix=commands.when_mentioned_or("%"), description='A simple Moderator bot')
def colour():
l = [ 1752220, 3066993, 3447003, 10181046, 15844367, 15105570, 15158332, 3426654, 16580705 ]
return choice(l)
#client.event
async def on_ready():
change_status.start()
print("The Bot is online!")
#client.command()
#commands.has_permissions(administrator=True)
async def kick(ctx, user : discord.Member = None, *,reason = "No reason provided"):
await user.kick(reason = reason)
await ctx.send("Kicked the user.")
#client.command()
#commands.has_permissions(administrator=True)
async def ban(ctx, user : discord.Member = None, *,reason = "No reason provided"):
await user.ban(reason = reason)
await ctx.send("Banned the user")
#client.command()
#commands.has_permissions(administrator=True)
async def warn(ctx, user : discord.Member = None, *,reason = "No reason provided"):
await user.send(f"You have been **Warned** by **{ctx.author.name}** in the **{ctx.guild.name}** for the reason: **{reason}** ")
await ctx.send("Warned the user")
client.run(os.environ['token'])
In this only warn command is working successfully rest all the commands throws an error which looks like this.
Ignoring exception in command kick:
Traceback (most recent call last):
File "main.py", line 140, in kick
await user.kick(reason = reason)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/member.py", line 524, in kick
await self.guild.kick(self, reason=reason)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/guild.py", line 1886, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/http.py", line 241, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
It is throwing a missing permission but I am the owner of the server and even added the bot as an admistrator.
Even tried by making an administrator role and giving all the permissions to it but still no luck.
This error is coming again and again.
Even if anyone know how to check between multiple roles like if anyone has administrator or kick member permission then do this, please let me know how to do that.
Thanks in advance for the help.
If any more information needed, do let me know.
The error you are getting on the last line from your console; discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions Is because the bot is missing permissions to perform these actions against the given permissions the bot currently has.
This could occur from the following;
Sufficient Bot permissions haven't been enabled from the invite link
The member has a higher or equal role than the bot
The #everyone role has no permissions
Moreover, these issues aren't at fault with the code you have written and is something that can be fixed in your server with the role hierarchy or bot invite link permissions.
I would also recommend comparing roles to make sure users can't attempt moderation on a higher level member in the first place, this could also help to mitigate the problem
With this, you can use >= and the top_role attribute which would compare the roles that the user compared to the member you are attempting to take moderation on, if your permissions are lower than the member you are attempting to moderate, it will prevent the rest of the code running. Here is a simple way of doing this,
if member.top_role >= ctx.author.top_role:
await ctx.send(f"You can only moderate members below your role")
return

Resources