【问题标题】:Convert message in wait_for to channel with discord.py使用 discord.py 将 wait_for 中的消息转换为频道
【发布时间】:2021-10-20 15:22:18
【问题描述】:

我有一个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

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

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

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

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

我该如何克服这个问题?

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    有人告诉我,克服它的最有效方法是创建一个循环(在外部函数内部)并在那里调用 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...
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      相关资源
      最近更新 更多