【问题标题】:Getting error: “Ignoring exception in command play” when running my hangman game for - Discord.py运行我的刽子手游戏时出现错误:“忽略命令播放中的异常” - Discord.py
【发布时间】:2021-04-29 20:02:11
【问题描述】:

我创建了一个 hangman 命令,但在 Discord 中调用该命令时,它给出了错误,如第二个代码所示。有没有人知道这个错误指的是什么,或者我当前的代码有什么问题?

    @bot.command()
    async def hangman(self, ctx):
        """Play hangman!"""
        game = Hangman(ctx, self.bot)
        await game.play()
Ignoring exception in command play:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 851, in invoke
    await self.prepare(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 786, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

对于hangman类的代码,这里有更多细节,因为我真的不知道问题出在哪里,因为我已经标记了self.ctx = ctx所以我真的很困惑如何解决这个问题

class Hangman():
    """Play Hangman!"""
    def __init__(self, ctx, bot):
        # setting up bot and context
        self.ctx = ctx
        self.bot = bot

        # setting up game
        self.word = RandomWords().random_word().upper()
        self.guessed = {'words':[], 'letters':[]}
        self.success = False
        self.progress = '_' * len(self.word)
        self.tries = 6

        # misc
        self.started = False
        self.gameOver = {
            True: 'Congrats! You win!',
            False: f'Sorry, you ran out of tries, **{self.word}** was the word'
        }

        global stages
        self.stages = stages

    async def play(self):
        """Use this command to play hangman"""

        # play the game

        msg = await self.ctx.send(f'Game starts now! Your word is {len(self.word)} letters long!')
        await asyncio.sleep(2)

        while self.tries > 0 and not self.success:

            await msg.edit(content='Guess a letter or word!')

            try:
                guess = await self.bot.wait_for('message', check=lambda m: m.author == self.ctx.author and m.channel == self.ctx.channel, timeout=60)

            except asyncio.TimeoutError:
                msg = await msg.edit(content='Game over, you took to long to guess')
                await asyncio.sleep(5)
                await msg.delete()
                return

            reply = guess
            guess = guess.content.upper()

            if len(guess) == 1 and guess.isalpha():
                if guess in self.guessed['letters']:
                    await msg.edit(content='You have already guessed the letter!')
                    await asyncio.sleep(1.5)

                elif not guess in self.word:
                    self.guessed['letters'].append(guess)
                    self.tries -= 1
                    await msg.edit(content='You have guessed the wrong letter')
                    await asyncio.sleep(1.5)

                else:
                    indices = [index for index, letter in enumerate(self.word) if letter == guess]
                    self.progress = list(self.progress)
                    for i in indices:
                        self.progress[i] = guess

                    self.progress = "".join(self.progress)

                    self.guessed['letters'].append(guess)
                    await msg.edit(content='You have guessed the right letter!')
                    await asyncio.sleep(1.5)

                    if self.word == self.progress: self.success = True

            elif len(guess) == len(self.word) and guess.isalpha():
                if guess == self.word:
                    self.success = True

                else:
                    self.guessed['words'].append(guess)
                    await msg.edit(content="You haven't guessed the right word")
                    await asyncio.sleep(1.5)

            else:
                await msg.edit(content='Your reply doesn\'t make sense')
                await asyncio.sleep(1.5)

            if self.started == True:
                await gameplay.edit(content=f'`{self.progress}`\n\n{self.stages[self.tries]}\n\nChances left: {self.tries}')

            else:
                gameplay = await self.ctx.send(f'`{self.progress}`\n\n{self.stages[self.tries]}\n\nChances left: {self.tries}')
                self.started = True

            await reply.delete()

        await self.ctx.send(self.gameOver[self.success])

还请记住,我对 discord.py 和 python 本身还很陌生,其中许多代码都是复制的,所以请放轻松

【问题讨论】:

  • 这个 bot.command() 是否在某个类中?看来您正在尝试以不希望的方式使用特定的 commands.ext 功能。据我所知,您应该在基本级别定义命令,并将 ctx 作为第一个参数。 (问题可能不在 Hangman 类中,您没有为 @bot.command() 提供足够的上下文

标签: python discord discord.py


【解决方案1】:

你的 hangman 协程不应该期待 self 参数,只有 ctx。您收到此错误:

discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

因为当您在 Discord 中不带参数地调用 hangman command 时,discord.py 正在调用您的 hangman 协程 时只有一个 Context 参数.由于您已将协程定义为接受两个强制参数,Context 对象将绑定到 self,但没有其他参数可以绑定到您的 ctx 参数,因此“ctx 是必需参数缺少”在您的错误消息中。

您没有向我们展示您在哪里定义了 hangman 协程,但它不应该使用 self 参数;删除它。

@bot.command()
async def hangman(ctx):
    """Play hangman!"""
    game = Hangman(ctx, self.bot)
    await game.play()

【讨论】:

    猜你喜欢
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2010-10-28
    相关资源
    最近更新 更多