You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人ctx.send命令失效无报错,playrps命令无法运行求助

Discord机器人playrps命令故障修复

问题根源

  1. ctx.send调用格式错误
    ctx.send()仅接受单个字符串作为消息内容参数,你传入了多个独立字符串,这会触发方法调用异常,但因缺少错误捕获逻辑,异常被静默处理。

  2. 无限循环阻塞事件循环
    while not gameOver是无停顿的死循环,直接卡住Discord机器人的事件循环,导致ctx.send无法完成发送,甚至整个机器人失去响应。

  3. 全局变量未正确声明
    函数内修改gameOver时未用global声明,导致它被当作局部变量,无法改变全局状态,循环永远不会终止。

修复后的代码

import asyncio
import discord
from discord.ext import commands

# 全局变量初始化(建议后续改用类封装,避免多用户状态冲突)
p1 = None
p2 = None
p1_ans = None
p2_ans = None
gameOver = False

@client.command()
async def playrps(ctx, p1: discord.Member, p2: discord.Member):
    global gameOver, p1_ans, p2_ans
    gameOver = False
    turn = p1
    # 用f-string拼接完整消息内容,修正ctx.send参数格式
    await ctx.send(f'Type Rock/Paper/Scissor on your turn. It is {p1.mention}\'s turn')  

    # 定义消息检查器,确保只接收当前玩家的有效输入
    def check(msg):
        return msg.author == turn and msg.channel == ctx.channel and msg.content.lower() in ['rock', 'paper', 'scissor']

    while not gameOver:
        try:
            # 等待玩家输入,超时时间设为60秒
            msg = await client.wait_for('message', check=check, timeout=60.0)
            # 记录选择并切换回合
            if turn == p1:
                p1_ans = msg.content.lower()
                turn = p2
                await ctx.send(f'It is {p2.mention}\'s turn')
            else:
                p2_ans = msg.content.lower()
                gameOver = True
                # 此处可添加胜负判断逻辑
                await ctx.send(f'Game over! P1 chose {p1_ans}, P2 chose {p2_ans}')
        except asyncio.TimeoutError:
            gameOver = True
            await ctx.send('Game timed out - no input received!')

额外建议

  • 移除或正确实现clear()函数,若该函数未定义会引发未捕获异常。
  • 全局变量会导致多用户同时玩游戏时状态冲突,建议用类封装每局游戏的玩家、选择等独立状态。
  • 添加命令错误处理,快速定位问题:
    @playrps.error
    async def playrps_error(ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.send('请指定两名玩家,格式:!playrps @玩家1 @玩家2')
        elif isinstance(error, commands.BadArgument):
            await ctx.send('请正确提及两位有效玩家')
    

内容的提问来源于stack exchange,提问作者samuel yoong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:20:32