Discord机器人interactions.py开发/rpc命令时出现应用未响应错误
解决Discord机器人/rpc命令的"The application did not respond"错误
问题根源
- 类型不匹配:
player参数通过选项返回的是字符串类型("0"/"1"/"2"),但代码中直接与整数类型的bot做条件判断,导致所有分支都无法触发,没有执行ctx.send返回响应,Discord因此提示应用未响应。 - 索引错误:
options[player]会抛出异常——字符串不能作为列表索引,这会直接终止命令执行,同样不会返回任何响应。
修复后的代码
@slash_command(name="rpc", description="Rock Paper Scissors") @slash_option( name="player", description="Your Choice", required=True, opt_type=OptionType.STRING, choices=[ SlashCommandChoice(name="Rock", value="0"), SlashCommandChoice(name="Paper", value="1"), SlashCommandChoice(name="Scissors", value="2") ] ) async def rpc_function(ctx: SlashContext, player: str): try: # 将字符串类型的player转为整数 player = int(player) bot = random.randint(0,2) options = ["Rock", "Paper", "Scissors"] if player == bot: # TIE await ctx.send(f"We both choose **{options[bot]}**, Tied") print(f"{datetime.datetime.now().strftime('%x %X')} {ctx.author.username} Used /rpc player={options[player]} bot={options[bot]}") elif player == 0 and bot == 1: # BOT WON / ROCK - PAPER await ctx.send(f"I choose **{options[bot]}** so I WON") print(f"{datetime.datetime.now().strftime('%x %X')} {ctx.author.username} Used /rpc player={options[player]} bot={options[bot]}") elif player == 0 and bot == 2: # PLAYER WON / ROCK - SCISSORS await ctx.send(f"You won cuz I choose **{options[bot]}**") print(f"{datetime.datetime.now().strftime('%x %X')} {ctx.author.username} Used /rpc player={options[player]} bot={options[bot]}") elif player == 1 and bot == 0: # PLAYER WON / PAPER - ROCK await ctx.send(f"YOU WON, I choose **{options[bot]}**") print(f"{datetime.datetime.now().strftime('%x %X')} {ctx.author.username} Used /rpc player={options[player]} bot={options[bot]}") elif player == 1 and bot == 2: # BOT WON / PAPER - SCISSORS await ctx.send(f"HEHE I WON CUZ I CHOOSE **{options[bot]}**") print(f"{datetime.datetime.now().strftime('%x %X')} {ctx.author.username} Used /rpc player={options[player]} bot={options[bot]}") elif player == 2 and bot == 0: # BOT WON / SCISSORS - ROCK await ctx.send(f"I won, I choose {options[bot]}") print(f"{datetime.datetime.now().strftime('%x %X')} {ctx.author.username} Used /rpc player={options[player]} bot={options[bot]}") elif player == 2 and bot == 1: # PLAYER WON / SCISSORS - PAPER await ctx.send(f"You won cuz I choose {options[bot]}") print(f"{datetime.datetime.now().strftime('%x %X')} {ctx.author.username} Used /rpc player={options[player]} bot={options[bot]}") except Exception as e: # 捕获异常并返回错误信息,避免无响应 await ctx.send(f"An error occurred: {str(e)}") print(f"Error in /rpc command: {str(e)}")
关键修复点
- 新增
player = int(player),将字符串参数转为整数,解决类型不匹配问题。 - 加入
try-except块捕获异常,确保即使出现错误也会给用户返回响应,避免Discord提示应用未响应。 - 优化print语句的格式化,让日志输出更整洁。
内容的提问来源于stack exchange,提问作者Atomic8oy
相关产品推荐
相关产品推荐

