How to unban a discord user given their ID - python

The code I'm currently using was perfectly fine, but I really want to unban with ID because it is much easier for me.
Current command is in a Cog file:
import discord
from discord.ext import commands
class unban(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
#commands.has_permissions(administrator=True)
async def unban(self, ctx, *, member : discord.Member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
unban = discord.Embed(title='UnBan Hammer Has Spoken! :boom:', description=f'**Moderator:** {ctx.author}\n **User UnBanned:** {member}\n', color=0x10940b)
unban.set_author(name="Moderating Action", icon_url=ctx.author.avatar_url)
await ctx.send(embed=unban)
return
def setup(client):
client.add_cog(unban(client))
How can I update this code to unban using the user ID instead?

async def unban(self, ctx, id: int) :
user = await client.fetch_user(id)
await ctx.guild.unban(user)
await ctx.send(f'{user} has been unbanned')
this should work for you, you can personalize even more, but that's just the main code you need.

Try
async def unban(self, ctx, *, member : discord.User):
await ctx.guild.unban(discord.Object(id = member.id))
unban = discord.Embed(title='UnBan Hammer Has Spoken! :boom:', description=f'**Moderator:** {ctx.author}\n **User UnBanned:** {member}\n', color=0x10940b)
unban.set_author(name="Moderating Action", icon_url=ctx.author.avatar_url)
await ctx.send(embed=unban)

Related

unban based on reason discord.py

so my discord server got hacked and everyone got banned with "gotcha" reason
is there a way to make this code read this reason and unban everyone that has it?
if it's not a big problem can it send this unbanned nicks or id's in the channel?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = '!', intents=intents)
#bot.event
async def on_ready():
print('TO PRONTO FDP')
#bot.command()
async def pronto(ctx):
await ctx.send("Esperando...")
#bot.command()
async def massunban(ctx):
banlist = await ctx.guild.bans()
for users in banlist:
try:
await ctx.guild.unban(user=users.user)
await ctx.channel.send(f"UNBANNED: **{users.user}**")
except:
pass
await ctx.channel.send(f"Finalizado")
For discord.py 1.7.3 (stable)
#bot.command()
async def massunban(ctx: commands.Context):
bans = await ctx.guild.bans() # list of discord.BanEntry
for ban_entry in bans:
await ctx.guild.unban(user=ban_entry.user)
await ctx.send("Done!")
References:
discord.Guild.bans
discord.BanEntry
discord.Guild.unban
For discord.py 2.0 (latest)
#bot.command()
async def massunban(ctx: commands.Context):
# Because of a change in Discord's API,
# discord.Guild.bans() returns now a paginated iterator
# Flattening into a list
bans = [ban_entry async for ban_entry in ctx.guild.bans()] # list of discord.BanEntry
for ban_entry in bans:
await ctx.guild.unban(user=ban_entry.user)
await ctx.send("Done!")
References:
discord.Guild.bans
discord.BanEntry
discord.Guild.unban
i solved it
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = '!', intents=intents)
#bot.event
async def on_ready():
print('ready to go')
#bot.command()
async def help(ctx):
await ctx.send("!start")
#bot.command()
async def start(ctx):
reason = "Zardex V3"
reason2 = "Zardex v3"
reason3 = "zardex v3"
reason4 = None
await ctx.channel.send(f"*Loading...*")
print('Loading...')
banlist = await ctx.guild.bans()
for users in banlist:
if (reason==users.reason):
try:
await ctx.guild.unban(user=users.user)
await ctx.channel.send(f"Unbanned: **{users.user}** Reason: **{users.reason}**")
except:
pass
if (reason2==users.reason):
try:
await ctx.guild.unban(user=users.user)
await ctx.channel.send(f"Unbanned: **{users.user}** Reason: **{users.reason}**")
except:
pass
if (reason3==users.reason):
try:
await ctx.guild.unban(user=users.user)
await ctx.channel.send(f"Unbanned: **{users.user}** Reason: **{users.reason}**")
except:
pass
if (reason4==users.reason):
try:
await ctx.guild.unban(user=users.user)
await ctx.channel.send(f"Unbanned: **{users.user}** Reason: **{users.reason}**")
except:
pass
await ctx.channel.send(f"*Finished.*")
print('Finished.')

Discord.py how to make a command work for certain roles?

I have this code which if someone has a role "Server Developer" it is suppose to run the command which is to give someone the role "Jail" for the determent amount n the command but it doesn't work and gives no errors.
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
import asyncio
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#commands.has_role("Server Developer")
#bot.command()
async def court(ctx, user_mentioned: discord.Member, time: int):
user_id = message.mentions[0].id
user = message.mentions[0]
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
bot.run(TOKNE_GOES_HERE)
You forgot to add #bot.command() on top of your command. Add it between #commands.has_role("Server Developer") and async def court(ctx, user_mentioned: discord.Member, time: int):
Do it like this:
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
import asyncio
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#commands.has_role("Server Developer")
#bot.command()
async def court(ctx, user_mentioned: discord.Member, time: int):
user_id = ctx.message.mentions[0].id
user = ctx.message.mentions[0]
role = discord.utils.get(ctx.message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
bot.run(TOKNE_GOES_HERE)
Using any check decorators like has_role or is_owner, doesn't make the function a command, so you would still have to add #commands.command() or #bot.command():
#bot.command()
#commands.has_role("Server Developer")
async def court(ctx, user_mentioned: discord.Member, time: int):
user_id = message.mentions[0].id
user = message.mentions[0]
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
bot.run(TOKNE_GOES_HERE)
you could try adding a check inside the command, something like this:
if not discord.utils.get(ctx.guild.roles, name="Server Developer") in ctx.user.roles:
return
else:
# do something

Discord.py | I'm trying to make my bot unban with both Member Name and Member ID

My code(Inside a Cog):
import discord
import datetime
from discord.ext import commands
class unban(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
#commands.has_permissions(ban_members = True)
async def unban(self, ctx, id: int):
user = await self.client.fetch_user(id)
await ctx.guild.unban(user)
unban= discord.Embed(title=f'A moderation action has been performed!', description='', color=0x90fd05)
#unban.add_field(name='User Affected:', value=f'`{member.name}`', inline=True)
#unban.add_field(name='User ID:', value=f'`{member.id}`', inline=True)
unban.add_field(name='Moderator Name:', value=f'`{ctx.author}`', inline=True)
unban.add_field(name='Moderator ID:', value=f'`{ctx.author.id}`', inline=True)
unban.add_field(name='Action Performed:', value='`UnBan`', inline=True)
unban.set_author(name=f'{ctx.guild}', icon_url=ctx.guild.icon_url)
#unban.set_thumbnail(url=member.avatar_url)
unban.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=unban)
def setup(client):
client.add_cog(unban(client))
I've made the command so I can unban people. But I can only unban with their ID. I want it to unban with their Name too. So how could I do that?
I've also tried replacing the:
async def unban(self, ctx, id: int):
with:
async def unban(self, ctx, member : discord.Member):
but nothing worked. and I've tried using both:
async def unban(self, ctx, member : discord.Member, id: int):
but still nothing worked...
async def unban(self, ctx, member : discord.Member):
It will not work due to a banned member can only be represented by discord.User or by an ID.
async def unban(self, ctx, user_id : int):
user = await self.client.fetch_user(user_id)
await ctx.guild.unban(user)
This will only work with ID's so discord can locate the user in their database.

discord.py entering none instead of there #username

Here is what i have right now!
#client.command()
async def punch(ctx, *, response):
response = response.replace("(", "")
response = response.replace(")", "")
member = discord.utils.get(client.get_all_members(), id=response)
embed = discord.Embed(title=f":house_with_garden: Punched: {member} :punch:", color=discord.Colour.green())
await ctx.send(embed=embed)
And this is what happens: I want it to be Sauq#(then my tag)
You can use MemberConverter
#client.command()
async def punch(ctx, member: discord.Member): # By typehinting the member arg, `MemberConverter` will automatically convert it to a `discord.Member` instance
embed = discord.Embed(title=f":house_with_garden: Punched {member} :punch:", color=discord.Colour.green()) # If you want to mention the member: `member.mention`
await ctx.send(embed=embed)

Suggestion bot discord.py

I want the bot to react to its own message with the ✅ and ❎ emojis for a suggestion command. Here is the code. How do i do it?
import discord
from discord.ext import commands
class suggestions(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command(description = 'Add a suggestion for this community!')
async def suggest(self, ctx, *,suggestion):
await ctx.channel.purge(limit = 1)
channel = discord.utils.get(ctx.guild.text_channels, name = '💡│suggestions')
suggestEmbed = discord.Embed(colour = 0xFF0000)
suggestEmbed.set_author(name=f'Suggested by {ctx.message.author}', icon_url = f'{ctx.author.avatar_url}')
suggestEmbed.add_field(name = 'New suggestion!', value = f'{suggestion}')
await channel.send(embed=suggestEmbed)
def setup(bot):
bot.add_cog(suggestions(bot))
Messageable.send returns a discord.Message object, you can then simply .add_reaction
message = await ctx.send(embed=suggestEmbed)
await message.add_reaction('✅')
await message.add_reaction('❌')
Note: You need the unicode of the emoji to react, to get it simply \:{emoji}:
Reference:
Messageable.send
Message.add_reaction
Me, I use this:
#bot.command()
async def suggestion(ctx, *, content: str):
title, description= content.split('/')
embed = discord.Embed(title=title, description=description, color=0x00ff40)
channel = bot.get_channel(insert the channel ID here)
vote = await channel.send(embed=embed)
await vote.add_reaction("✅")
await vote.add_reaction("❌")
await ctx.send("your suggestion has been send")
You can vote using the emojis, enjoy!

Categories

Resources