繁体   English   中英

在 discord.py Cogs 中使用 `wait_for`

[英]Using `wait_for` in discord.py Cogs

我正在创建一些机器人会随机询问“打乱这句话”的问题,用户必须回答这个问题。 现在,当我使用client.wait_for等待用户响应时, wait_for在我尝试使用断点时完全停止代码。 为什么会这样? 我想我正在努力研究如何在齿轮中使用它。 这是我没有导入的 cog 代码:

class firework_economy(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        else:
            rand_num = randint(1, 10)
            print(rand_num)
            if rand_num == 5:
                ss = open('scrambled sentences.txt','r')
                sslist = ss.readlines()
                chosen_sentence = choice(sslist)
                await message.reply(f"Unscramble the following sentence for a chance to win a firework:\n\n`{chosen_sentence}`")
                def check(m):
                     return m.content == 'answer' and m.channel == message.channel
                msg = await commands.Bot().wait_for("message")
                await message.channel.send(f"{msg.author.mention} was first!")

   

async def setup(bot):
  await bot.add_cog(firework_economy(bot))

commands.Bot.wait_for()没有任何意义。 您应该在Bot class 的实例上调用wait_for方法。它不是 static 方法。

commands.Bot  # This is the name of a class
bot = commands.Bot(...)  # This is an instance of the commands.Bot class

要在Cog中访问它,最常见的解决方案是在创建Cog实例时将其作为参数传递给__init__()

文档中的示例也清楚地显示了这一点(使用client而不是discord.Client ): https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=wait_for#discord.ext.commands .Bot.wait_for

接下来, wait_for的 arguments 是错误的。 您不能传递多个事件类型来等待。

wait_for("event", "message", ...)  # You can't do this

“事件”对于wait_for来说甚至都不是有效的东西,所以这两种方式都行不通。 我什至不知道会触发什么“事件”。

最后,你check了 function 但你通过了check=None所以你没有使用它......

仔细查看文档页面(上面的链接)中的示例。

不过,所有这些都应该在您的控制台和您的 IDE 中给您一条错误消息 - 所以不确定您是如何到达这里的,并且您可能没有正确配置logging

你在正轨上,但有一些错误。 这是您的代码片段。

def check(m):
   return m.content == 'answer' and m.channel == message.channel
msg = await commands.Bot().wait_for("message")

您的支票 function 对于您正在做的事情大部分是正确的,您只需要用answer替换'answer' ,然后变量answer就像chosen_list : answer = 'find the answer in the txt file'

对于味精,你完全搞砸了。 commands.Bot() 是错误的,应该是 bot 或 client 所以这里是 bot. msg = await bot.wait_for('message', check=check, timeout=10)

“消息”初始化机器人正在等待消息,检查等于我们的检查 function,它将在机器人等待消息时运行,超时是机器人停止等待消息之前等待的时间长度。

这是 wait_for 上的文档参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM