How to ban a discord member that has my bot blocked? discord.py

Viewed 241

So I have this code, I want the bot to first send the embed to a person which is to be banned, then I want the bot to ban him/her, the problem is that some of the users have my bot blocked, so the bot can't send messages to them in DMs which stops the entire command. How can I ban them with the same command?

import discord
from discord.ext import commands

class ban(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ban(self, ctx, member : discord.Member, *, reason = None):
        if (ctx.message.author.permissions_in(ctx.message.channel).ban_members):

            if member.top_role >= ctx.author.top_role:
                    await ctx.send("You can only ban people below you")
                    return
            
            if reason == None:
                reason = "{}: No reason provided.".format(ctx.message.author)
            
            embed=discord.Embed(title="You have been banned!", description="You have been banned from {} for {} by {}".format(ctx.guild, reason, ctx.author), color=0xff0000)
            embed.add_field(name="In order to appeal:", value="Join the server below, then DM me saying '>apelacja'", inline=False)
            embed.set_footer(text="Nims Waifu 2021")

            await member.send(embed=embed)
            await member.send("https://discord.gg/CxTQaYWqRK")
            await member.ban(reason= "{}: {}".format(ctx.author, reason))
            await ctx.send("✅ Banned {} for: {}".format(member, reason))

            

def setup(bot):
    bot.add_cog(ban(bot))
1 Answers

You can still ban the members from the guild, you just can't send direct messages. I don't think there is a workaround for the direct message issue. Since member.send() is called before member.ban(), an exception (Forbidden) will be raised, and member.ban() won't be called. So I would recommend moving member.send() to after member.ban() and create a try/except to handle the exception.

class ban(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def ban(self, ctx, member : discord.Member, *, reason = None):
        if (ctx.message.author.permissions_in(ctx.message.channel).ban_members):
            ...
            await member.ban(reason= "{}: {}".format(ctx.author, reason))
            try:
                await member.send(embed=embed)
                await member.send("https://discord.gg/CxTQaYWqRK")
            except discord.Forbidden:
                pass   # Or, send a message somewhere notifying of failure
            await ctx.send("✅ Banned {} for: {}".format(member, reason))
Related