如果 DM 被禁用,Discord.py 禁止用户不工作

时间:2021-01-25 01:45:24

标签: discord discord.py

我有我的不和谐机器人的代码,它可以禁止人们并首先将禁止的原因发送给他们。

cooldown = []

@bot.command(pass_context = True)
@commands.has_role('Senior Moderator')
async def ban(ctx, member: discord.Member = None, *, reason = None):
    author = str(ctx.author)
    if author in cooldown:
        await ctx.send('Calm down! You\'ve already banned someone less than two hours ago.')
        return

    try:
        if reason == None:
            reason = 'breaking the rules.'
        await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')
        await member.ban(reason = f"Banned by {ctx.message.author} for "+reason)
        await ctx.send(f'{member.mention} has been banned.')
        cooldown.append(author)
        await asyncio.sleep(2 * 60 * 60)    #The argument is in seconds. 2hr = 7200s
        cooldown.remove(author)
    except:
        await ctx.send('Error. Please check you are typing the command correctly. `!ban @username (reason)`.')

但是,如果我尝试禁止的用户已禁用 DM,则机器人无法发送禁止原因消息,因此不会进行下一步,即禁止他们,并返回错误消息,这是错误。请检查您输入的命令是否正确。 !ban @username(原因)

请你重写代码,让它在禁止某人之前尝试 DM 某人的推理,但如果他们禁用了 DM,它仍然会禁止他们。谢谢!

2 个答案:

答案 0 :(得分:1)

通过简单地将禁令先执行(因为它是优先事项),然后它会尝试 dm 用户。

我还重新调整了部分代码。它现在会尝试发送 dm,如果没有,它仍然会被禁止,但会向频道发送一条消息,提醒消息未发送给被禁止的用户。

@bot.command(pass_context = True)
@commands.has_role('Senior Moderator')
async def ban(ctx, member: discord.Member = None, *, reason = None):
    author = ctx.author
    
    if author in cooldown:
        await ctx.send('Calm down! You\'ve already banned someone less than two hours ago.')
        return
    
    if member == None:
        await ctx.send('Please mention a member to ban!')
        return
    if reason == None:
        reason = 'breaking the rules.'
        
    await member.ban(reason = f"Banned by {ctx.message.author} for " + reason)
    
    try:
        await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')

    except:
        await ctx.send(f'A reason could not be sent to {ctx.message.author} as they had their dms off.')

    await ctx.send(f'{member.mention} has been banned.')
    cooldown.append(author)
    await asyncio.sleep(2 * 60 * 60)
    cooldown.remove(author)

答案 1 :(得分:1)

当我第一次发出机器人禁止命令时,我也注意到了同样的事情,我做了以下操作来修复我的禁止命令。首先我尝试了一个场景,机器人可以 dm 用户,如果可以,那么它会 dm 用户然后禁止用户(注意:在 DM 用户之前不要禁止用户,因为机器人只能在用户和机器人共享一个公共服务器)。但是,然后我做了一个例外,如果机器人无法 dm 用户,它将在执行命令的频道中发送一条消息“无法 dm 用户”然后禁止用户

try:
      await member.send(embed=embo)
      await ctx.guild.ban(member, reason=reason)
except Exception:
      await ctx.send("Couldn't send dm to the user")
      await ctx.guild.ban(member, reason=reason)

编辑: 您还可以选择以下内容:

try:
      await member.send(embed=embo)
      await ctx.guild.ban(member, reason=reason)
except discord.HTTPException:
      await ctx.send("Couldn't send dm to the user")
      await ctx.guild.ban(member, reason=reason)

在我指定之前,我遇到了以下错误。enter image description here

我修复了它,然后添加了例外情况。

enter image description here