【问题标题】:How can I write a discord.py function that accepts integers, booleans, strings or None?如何编写一个接受整数、布尔值、字符串或无的 discord.py 函数?
【发布时间】:2018-06-17 04:36:36
【问题描述】:

我正在尝试在 discord.py 中编写一个函数,它接受整数、字符串、布尔值或 None 作为参数。

这是我目前的代码:

@commands.command()
async def post(self, ctx, type = ""):
    '''Post a random picture from the preselected gallery'''
    path = "A Folder that I want to keep hidden from the public HAHAHA ok..."
    x = 0
    if ctx.channel.is_nsfw() = True:
        await ctx.send("I'm sorry, but I can't post these kinds of pictures here!\nI can only post in safe for work areas. Server rules!")
        return
    if is_number(type):
        if type > 5:
            await ctx.send("I'm sorry, I cannot post more than 5 images.\nWe don't want me to be kicked for spamming images.")
            return
        while x < type:
            x += 1
            await ctx.send("", file=discord.File(path + "\\" + random.choice(os.listdir(path))))
    elif type == 'maxindex()':
        number_of_files = len([item for item in os.listdir(path) if os.path.isfile(os.path.join(path, item))])
        await ctx.send(f'I found: {number_of_files} total files')
    else:
        await ctx.send("", file=discord.File(path + "\\" + random.choice(os.listdir(path))))

我希望能够执行;post 1;post maxindex();post 之类的操作。带有整数或无整数的命令将发布该数量或一张图像(如果没有)。带有“MaxIndex()”字符串的命令将允许查看文件夹中有多少“可用”图像。

如果我不够清楚,请务必要求我澄清。

【问题讨论】:

  • 会使用 isinstance( ..., int)isinstance( ..., bool)is not None 简化它吗? docs.python.org/3/library/functions.html#isinstance
  • 除此之外,if ctx.channel.is_nsfw() = True: 不起作用,您需要 == 来测试是否相等。
  • 我也不会使用 type 作为变量 - 它会影响内置 type(),这在这里并不重要,但这是一个坏习惯,可能会导致混乱
  • @roganjosh 我知道 == 是必需的,但我不得不快速编辑代码并意外删除了第二个等号

标签: python python-3.x discord.py


【解决方案1】:

(呃,写我的答案太长了。)

我正在寻找一种允许整数、字符串和布尔值成为函数参数的方法。

您只需检查您的价值是否符合您的预期!

def example(myVar):
    if myVar is None:
        print("My parameter is None !")
    elif isinstance(myVar, int):
        print("My parameter is an Int !")
    elif isinstance(myVar, list):
        print("My parameter is a List !")
    else:
        print("Eh. Not something I want.")

example(None)
example(16)
example([1, 2, 3])
example("Hello")

输出:

  • 我的参数是无!
  • 我的参数是一个 Int !
  • 我的参数是一个列表!
  • 嗯。不是我想要的。

【讨论】:

    【解决方案2】:

    typing 模块包括Union[],它允许您自动将参数转换为任何预选类型列表。例如,您可以这样做:

    async def post(ctx, type : typing.Union[None,int,str,bool]):
    

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 2023-03-20
      • 2021-03-30
      • 1970-01-01
      相关资源
      最近更新 更多