如何用Python编写Discord bot实现按指定用户ID发送DM消息
实现Discord机器人向指定用户ID发送DM的操作步骤
首先需要先在Discord开发者后台完成机器人权限配置:
- 进入对应应用的「Bot」设置页,开启Privileged Gateway Intents分类下的
Server Members Intent和Message Content Intent权限 - 邀请机器人进入目标服务器时,要给机器人分配发送消息的基础权限
代码实现示例
首先安装依赖包:pip install discord.py
import discord from discord.ext import commands # 配置必须的Intents权限 intents = discord.Intents.default() intents.members = True intents.message_content = True # 初始化机器人,指令前缀可自定义 bot = commands.Bot(command_prefix='!', intents=intents) # 机器人启动完成后自动发送DM的实现 @bot.event async def on_ready(): print(f'已登录为 {bot.user}') # 替换为目标用户的ID,必须为整数类型不要加引号 target_user_id = 123456789012345678 # 获取用户对象 target_user = await bot.fetch_user(target_user_id) if target_user: # 发送DM消息 await target_user.send("这是机器人发送的测试DM内容") print("消息发送成功") else: print("未找到对应用户") # 可选:通过指令触发发送DM的实现,调用格式为!send_dm [用户ID] [消息内容] @bot.command() async def send_dm(ctx, user_id: int, *, content: str): target_user = await bot.fetch_user(user_id) if target_user: await target_user.send(content) await ctx.send("DM已发送") else: await ctx.send("未找到对应用户") # 替换为你自己的机器人Token bot.run("你的机器人Token")
注意事项:
- 目标用户必须和机器人在同一个服务器,否则机器人无法获取用户对象完成发送
- 如果用户设置了禁止接收服务器成员的DM,会触发
discord.Forbidden异常,可自行添加try-except捕获处理对应报错- 不要泄露机器人Token,避免机器人被恶意操控
内容的提问来源于stack exchange,提问作者rogerinhodoquero
相关产品推荐
相关产品推荐

