如何实现Discord机器人在踢出用户时向其发送私信(DM)
解决Discord机器人踢人时发送私信的问题
很容易就能实现这个功能!你只需要在踢用户的逻辑里加入发送私信的代码,同时一定要处理可能的发送失败情况(比如用户关闭了私信、屏蔽了机器人,或者服务器限制了DM),避免因为私信发不出去导致整个踢人命令中断。
修改后的完整代码
import datetime import discord from discord.ext import commands @bot.command(name="kick", aliases=["k"], help= "Kicks specified user from the server.") async def kick(ctx, member: discord.Member, *, reason=None): # 先尝试给用户发送踢人通知私信 try: # 用Embed发送更美观的通知 dm_embed = discord.Embed( title="你已被踢出服务器", description=f"服务器: {ctx.guild.name}\n踢出原因: {reason or '未提供理由'}", color=discord.Color.red(), timestamp=datetime.datetime.now(datetime.timezone.utc) ) dm_embed.set_footer(text=f"执行操作: {ctx.author.name}", icon_url=ctx.author.avatar_url) await member.send(embed=dm_embed) print(f"成功给 {member} 发送踢人通知私信") except discord.Forbidden: print(f"无法给 {member} 发送私信: 用户关闭了私信权限或屏蔽了机器人") except discord.HTTPException as e: print(f"发送私信时出现错误: {e}") # 执行踢人操作 await member.kick(reason=reason) await ctx.send(f'User {member} has been kicked.') # 原有的Debug日志Embed逻辑 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 an embed") await ctx.message.add_reaction('✅') print("Added a reaction to a message")
关键细节说明
- 发送时机:我把私信发送放在了踢人操作之前——即使踢人后用户立即离开服务器,Discord依然允许给曾经有过交互的用户发DM,这样能最大程度保证用户收到通知。
- 异常处理:用
try-except捕获两类常见错误:Forbidden(没有权限发私信)和HTTPException(网络或API层面的错误),确保就算私信发送失败,踢人命令依然能正常完成。 - 可选简化:如果不需要美观的Embed,也可以用纯文本发送:
await member.send(f"你已被从 {ctx.guild.name} 服务器踢出,原因: {reason or '未提供理由'}")
内容的提问来源于stack exchange,提问作者Jea




