从discord.py转换器返回默认值

2024-04-19 10:47:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个不和谐的频道转换器

class Channel(commands.Converter):
    async def convert(self, ctx, argument):

        # Do converter stuff to get a channel
        # This may fail meaning that the result is not a TextChannel 

        if not isinstance(result, discord.TextChannel):
            return ctx.channel
        else:
            return result

如您所见,如果无法获取通道,我将返回ctx.channel(调用该通道的通道)。
问题是如果我做这样的事

    @commands.command(name='invite', aliases=['inv'])
    @commands.guild_only()
    @commands.cooldown(1, 30, commands.BucketType.user)
    async def invite(self, ctx, channel: converters.Channel, member: discord.User):
        # Command stuff here

如果成员使用g/invite #channel @member运行命令,则可以正常工作,但如果成员使用g/invite @member运行命令,则当前通道将用作通道,但完全忽略该成员。有没有办法阻止这种情况发生?
(因此该频道将是当前频道,但该成员将是他们提到的成员)


Tags: selfasyncdefchannelnot成员result频道
1条回答
网友
1楼 · 发布于 2024-04-19 10:47:40

我认为最简单的方法是使用^{} converter,然后在回调函数体中将None替换为ctx.channel

from discord import TextChannel, User
from typing import Optional

@commands.command(name='invite', aliases=['inv'])
@commands.guild_only()
@commands.cooldown(1, 30, commands.BucketType.user)
async def invite(self, ctx, channel: Optional[TextChannel], member: User):
    channel = channel or ctx.channel
    # Command stuff here

相关问题 更多 >