首页 > 解决方案 > 使用 discord.py 将 wait_for 中的消息转换为频道

问题描述

我有一种wait_for创建反应角色的命令方法:

msg = await self.bot.wait_for('message', check=checkChannel, timeout=60)

它利用该checkChannel功能来验证消息是“取消”(取消创建)还是公会中的频道。我的原始代码:

def checkChannel(msg):
    if ctx.message.author == msg.author and ctx.channel == msg.channel:
        if (msg.content == "Cancel"):
            return True

        nonlocal embedChannel
        message = msg.content
        if message.startswith("<#"):
            message = message[2:len(message) - 1]

        for channel in self.bot.get_guild(ctx.guild.id).channels:
            if str(channel.id) == message:
                embedChannel = channel
                return True
        return False
    else:
        return False

由于这特别混乱(并且不考虑发送频道名称),我尝试寻找一种更有效的方法并得到了这个答案

channel = await commands.TextChannelConverter().convert(ctx, args)

但是,由于这使用await并需要async语法,因此我无法在 check 函数的上下文中使用它,并且会得到:

RuntimeWarning: coroutine '<directory>.checkChannel' was never awaited

我将如何克服这一点?

标签: pythondiscorddiscord.py

解决方案


有人告诉我,克服它的最有效方法是创建一个循环(在外部函数内部)并channel = await commands.TextChannelConverter().convert(ctx, args)在那里调用,以便实际调用它。

因此,在这种情况下,它将是:

def checkChannel(msg):
    return ctx.message.author == msg.author and ctx.channel == msg.channel

channel_checker = True

while channel_checker == True:
    try:
        msg = await self.bot.wait_for('message', check=checkChannel, timeout=60)
    except asyncio.TimeoutError:
        await ctx.send(f"You took too long to respond")
        return

    if msg == "cancel":
        await ctx.send("Cancelling...")
        return
    try:
        embedChannel = await commands.TextChannelConverter().convert(ctx, msg.content)
        channel_checker = False
    except:
        await ctx.send(f"Retry typing in the channel")

#Continue creating...


推荐阅读