You need to enable JavaScript to run this app. discord.py 如何实现脚本自动将输赢结果发送至特定用户私信
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 如何实现脚本自动将输赢结果发送至特定用户私信

原代码错误点说明
  • 在命令函数内部嵌套使用@client.event注册自定义事件完全无效:discord.py的事件装饰器仅支持全局作用域注册,函数内嵌套定义的on_win、on_lost根本不会被客户端自动触发,每次执行命令还会重复注册监听器,极易引发运行异常
  • 代码中dmessage.send.user为语法无效的错误写法:没有实例化对应的操作对象,也没有绑定触发命令的用户身份,完全无法实现发送逻辑
  • 给指定用户发私信不需要额外注册事件,直接获取触发命令的用户对象,调用其内置的异步send方法即可完成消息投递
修复后的可运行代码
from discord.ext import commands
import discord
from random import randint

# 配置Bot运行所需的权限意图
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix="-", intents=intents)

@client.event
async def on_ready():
    print(f"Bot 运行就绪,登录身份:{client.user}")

@client.command()
async def dm(ctx):
    # 获取触发当前命令的用户对象
    trigger_user = ctx.author
    rand_num = randint(1, 3)
    win_num = 1

    if rand_num == win_num:
        print(f"随机数为:{rand_num},结果:获胜")
        await trigger_user.send("You won!")
    else:
        print(f"随机数为:{rand_num},结果:失败")
        await trigger_user.send("You lost")

# 替换为自身Bot的Token后即可运行
client.run("你的Bot Token")
运行注意事项
  • 提前在Discord开发者后台为对应Bot开启Message Content Intent权限,否则会触发权限校验报错
  • 所有Discord客户端事件监听器必须定义在全局作用域,禁止在命令处理函数内部嵌套注册事件
  • 只要Bot与触发用户处于共同服务器、且Bot拥有发送私信的权限,上述代码就可以自动将输赢结果发送到对应触发用户的Discord私信

内容的提问来源于stack exchange,提问作者Adam L.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.28 10:15:02