Search code examples
pythondiscorddiscord.pybots

How can I make a Discord bot DM someone when I kick them


I'm trying to make my discord bot DM a person when I kick them. I have tried some stuff but nothing ended up working. This is the current kick code:

@bot.command(name="kick", aliases=["k"], help= "Kicks specified user from the server.")
async def kick(ctx, member: discord.Member, *, reason=None):
  await member.kick(reason=reason)
  await ctx.send(f'User {member} has been kicked.')
  embed=discord.Embed(
    title= f"{bot.user} kicked {member}",
    color=bot.embed_color,
    timestamp = datetime.datetime.now(datetime.timezone.utc)
  )
  embed.set_author(
    name = ctx.author.name,
    icon_url = ctx.author.avatar_url
  )
  embed.set_footer(
  text = bot.footer,
  icon_url = bot.footerimg
  )
  await bot.debug_channel.send(embed = embed)
  print("Sent and embed")
  await ctx.message.add_reaction('✅')
  print("Added a reaction to a message")

Does anyone know how to make the bot send a DM?


Solution

  • You have to send a message to the kicked user.

    Since you already have the member object, you can just do await member.send("What you want to send")

    Also the message should be before await member.kick(), as the bot will not be able to message people that they don't have mutual servers with.

    Another thing you should do is check if the user is kickable before sending a message to the member.

    Some cases in which you can not kick the user are:

    1. They have a higher role than the discord bot. (Can be solved by comparing the member.top_role and the bots top role)
    2. They do not have permissions to kick. (Can be solved by checking for bots guild permissions)

    Another thing is that you should also create a try except to catch any errors that can occur when trying to message the user. Some users have DM's off, so you would get an error when trying to message the member.