我试图在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
之类的操作。带有整数或不带整数的命令将发布该数量或一个图像(如果为无)。带有&#39; MaxIndex()&#39;的命令字符串将允许查看有多少&#34;可用&#34;图像在文件夹中。
如果我不够清楚,请让我澄清一下。
答案 0 :(得分:0)
(呃,写下我的答案太长了。)
我正在寻找的是一种允许将整数,字符串和布尔值作为函数参数的方法。
您可以检查您的价值是否符合预期!
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")
输出:
答案 1 :(得分:0)
typing
模块包括Union[]
,它使您可以将参数自动转换为任何预选类型的列表。例如,您可以执行以下操作:
async def post(ctx, type : typing.Union[None,int,str,bool]):