如何禁止我的机器人被阻止的不和谐成员? discord.py

时间:2021-05-13 15:19:43

标签: python discord.py

所以我有这个代码,我希望机器人首先将嵌入内容发送给要被禁止的人,然后我希望机器人禁止他/她,问题是某些用户阻止了我的机器人,因此机器人无法在 DM 中向他们发送消息,这会停止整个命令。如何使用相同的命令禁止它们?

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 个答案:

答案 0 :(得分:4)

你仍然可以禁止公会成员,只是不能直接发送消息。我认为没有解决直接消息问题的方法。由于 member.send()member.ban() 之前被调用,因此将引发异常 (Forbidden),并且不会调用 member.ban()。因此,我建议将 member.send() 移至 after member.ban() 并创建一个 try/except 来处理异常。

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