unban based on reason discord.py - python

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.')

Related

Why the Cog is not loading?

I created a discord bot with cog and extensions, but the commands aren't being imported
Main file:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), intents=intents)
bot.remove_command('help')
#bot.event
async def on_ready():
print(f'Bot ready as {bot.user}')
bot.load_extension('.ext.moderation')
bot.run(***)
"Moderation.py" extension:
import discord
import datetime
from discord.ext import commands
from ..functions import Time
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
#commands.has_permissions(ban_members = True)
async def ban(self, ctx, member : discord.Member = None, *, reason = None):
if member == None:
await ctx.send('Você deve especificar um membro para ser banido!', delete_after = 10)
else:
await member.ban(reason = reason)
#commands.command()
#commands.has_permissions(kick_members = True)
async def kick(self, ctx, member : discord.Member = None, *, reason = None):
if member == None:
await ctx.send('Você deve especificar um membro para ser expulso!', delete_after = 10)
else:
await member.kick(reason = reason)
#commands.command()
#commands.has_permissions(administrator = True)
async def unban(self, ctx, *, member = None):
if member == None:
await ctx.send('Você deve especificar um membro para ser desbanido!', delete_after = 10)
else:
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)
await ctx.send(f'Unbanned {user.mention}')
return
else:
await ctx.send('O membro não está banido!')
#commands.command(aliases=['purge','clean','limpar'])
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount: int = 10):
try:
int(amount)
except:
await ctx.send('Insira um número válido.', delete_after=5)
else:
await ctx.channel.purge(limit=amount)
await ctx.send(f'Apagou {amount} mensagens.', delete_after=5)
#commands.command(aliases=['mute'])
#commands.has_role('Mod' or 'Admin')
async def timeout(self, ctx, member : discord.Member, duration = '30m', *, reason = None):
lenght = Time.input_convert(duration)
if lenght == -1:
await ctx.send('Duração inválida! Digite a duração no formato (s/m/d/h).')
else:
lenght = datetime.timedelta(seconds = lenght)
await member.timeout(until = lenght, reason = reason)
def setup(bot):
bot.add_cog(Moderation(bot))
But whenever I try to use a command, this appears in the console instead: discord.ext.commands.errors.CommandNotFound: Command "ban" is not found
Where is the error?
I tried to change some parts of the code, using just Cogs or just extensions, but it isn't working anyway.
If you're using the latest version of discord.py, loading Cogs is Asynchronous now!
Do this for your main file:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
class BotClient(commands.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or('!'), intents=intents, help_command=None)
async def setup_hook(self):
await self.load_extension('ext.moderation')
# Load cogs here
async def on_ready(self):
print(f'Bot ready as {self.user}')
bot = BotClient()
bot.run(***)
Then change the setup function on the cog with this:
async def setup(bot):
await bot.add_cog(Moderation(bot))'
More on this change:
https://discordpy.readthedocs.io/en/latest/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
Migrating to v2.0: https://discordpy.readthedocs.io/en/latest/migrating.html#

Auto role in discord.py

I checked all codes what I can find but they don't work with my bot.What am I doing wrong?
They’re not much different and they all work, but not in my code. No mistakes in the cmd.
my friend can’t do it either. Bot has administrator privileges (I checked)
role = "NEWS"
#bot.event
async def on_member_join(member):
rank = discord.utils.get(member.guild.roles, name=role)
await member.add_roles(rank)
print(f"{member} was given the {rank} role.")
Second
#bot.event
async def on_member_join( member ):
role = discord.utils.get( member.guild.roles, id = 889869064997068810)
await member.add_roles( role )
Third
#bot.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name='Unverified')
await member.add_roles(role)
All code without this auto role
import random
import json
import discord
import datetime
from lol import an
from zdar import answer_hello
from zdar import hello_words
from zdar import maternie
from zdar import answer_maternie
from discord.ext import commands
from config0 import settings
bot = commands.Bot(command_prefix= settings['prefix'])
bot.remove_command('help')
#bot.command()
async def clear(ctx, amount = 100):
await ctx.channel.purge( limit = amount )
#bot.command()
async def hello(ctx):
await ctx.send(f',{ctx.message.author.mention}!')
#bot.command()
async def cat(ctx):
await ctx.send(random.choice(an))
#bot.command()
async def time (ctx):
emb = discord.Embed(title = 'Титульник', colour = discord.Color.green(), url = 'https://www.timeserver.ru/cities/by/minsk')
emb.set_author(name = bot.user.name, icon_url = bot.user.avatar_url)
emb.set_footer ( text = ctx.author.name, icon_url= ctx.author.avatar_url)
emb.set_image( url= 'https://i.pinimg.com/originals/3f/82/40/3f8240fa1d16d0de6d4e7510b43b37ba.gif')
emb.set_thumbnail( url= 'https://static.wikia.nocookie.net/anime-characters-fight/images/9/90/Eugo_La_Raviaz_mg_main.png/revision/latest/scale-to-width-down/700?cb=20201114130423&path-prefix=ru')
now_date = datetime.datetime.now()
emb.add_field( name = 'Time', value='Time:{}'.format( now_date))
await ctx.send(embed = emb)
bot.run(settings['token'])
You have to specify the member intent to receive on_member_join events. You can do this while creating your bot object by adding an intent option:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=settings['prefix'], intents=intents)
Note
If your bot is verified you require the SERVER MEMBERS INTENT which you can request on the bot page of your application.

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

How to unban a discord user given their ID

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)

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