【问题标题】:Retrieving TextChannel Object in command在命令中检索 TextChannel 对象
【发布时间】:2021-07-06 12:20:59
【问题描述】:

我在命令中检索通道对象时有点停滞不前。而不是使用async def command(ctx, channel:discord.TextChannel)或类似的,我想从用户的wait_for消息内容的产品中获取频道对象,我不会在这里包含。

例如,如果用户说general、id 757115231377031169,或者只是提到频道#general,则无论输出是否有效,机器人都可以检索 TextChannel 对象。

简而言之:我如何在代码本身中获得TextChannel Object


以下是我尝试过的几件事

我曾尝试在转换器的帮助下通过调用另一个命令来检索通道对象。这通常会引发错误'str' object has no attribute 'mention'(这是我最近的选择,我有比这更好的想法)

@client.command()
async def chan_convert(ctx, channel:discord.TextChannel):
    return channel

@client.command()
async def test(ctx, channel):
    try:
        ch = await ctx.invoke(client.get_command("chan_convert"), channel=channel)
        await ctx.send(ch.mention)
    except Exception as e:
        await ctx.send(str(e))

我解决问题的另一种方法是使用我尝试创建的自定义函数,但这只能工作到某个点,例如如果您输入了频道 ID,它会引发错误 AttributeError: 'NoneType' object has no attribute 'mention'

def custom_chan(guild:discord.Guild, channel):
    if channel.isnumeric(): # if it's all numbers, it could be an id
        try:
            channel = guild.get_channel(channel)
            return [True, channel]
        except:
            return [False, "ID was not valid"]
    else:
        if channel.startswith("<#") and channel.endswith(">"): # <#123123123123123123> format of channel mention
            channel = channel.replace("<#", "")
            channel = channel.replace(">", "")
            try:
                channel = guild.get_channel(channel)
                return [True, channel]
            except:
                return [False, "ID was not valid"]
        else: # otherwise, it's just a name, check if it exists
            try:
                channel = discord.utils.get(guild.channels, name=channel)
                return [True, channel]
            except:
                return [False, "No channel with that name was found"]

def channel_check(channel):
    return type(channel)

chan = custom_chan(ctx.guild, "757115231377031169") # an id I put in here originally
await ctx.send(chan[1].mention)
await ctx.send(channel_check(chan))

提前谢谢你。

【问题讨论】:

    标签: discord discord.py


    【解决方案1】:

    如果您使用的是discord.ext,则可以使用TextChannelConverter() 来获取TextChannel 对象,使用包含ID、提及或名称的字符串作为输入。

    按照你的第一个例子:

    from discord.ext.commands import TextChannelConverter
    
    @client.command()
    async def chan_convert(ctx, channel):
        ch = await TextChannelConverter().convert(ctx=ctx, argument=channel)
        return ch
    

    这适用于我自己的频道,使用 ID、名称或提及作为输入。但是,如果您不打算将其用作实际命令,而不是使用 ctx.invoke(),则可以删除 @client.command() 装饰器并使用 await chan_converter() 调用该函数。

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 2021-05-03
      • 2015-01-09
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2011-07-30
      相关资源
      最近更新 更多