Python 如何编写接受整数、布尔值、字符串或无的discord.py函数?
我正在尝试在discord.py中编写一个函数,它接受整数、字符串、布尔值或None作为参数 这是我目前的代码:Python 如何编写接受整数、布尔值、字符串或无的discord.py函数?,python,python-3.x,discord.py,Python,Python 3.x,Discord.py,我正在尝试在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.
@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))))
@commands.command()
异步def post(self,ctx,type=”“):
''从预选库中随机发布图片''
path=“我想对公众隐藏的文件夹哈哈哈,好吧…”
x=0
如果ctx.channel.is_nsfw()=真:
等待ctx.send(“对不起,我不能在这里发布此类图片!\n我只能在工作区的保险箱中发布。服务器规则!”)
返回
如果是_编号(类型):
如果类型>5:
等待ctx.send(“很抱歉,我发布的图片不能超过5张。\n我们不希望我因为滥发图片而被踢。”)
返回
而x<类型:
x+=1
等待ctx.send(“,file=discord.file(path+“\\”+random.choice(os.listdir(path)))
elif类型==“maxindex()”:
_文件数=len([如果os.path.isfile(os.path.join(path,item)),则os.listdir(path)中的项目对应于项目])
wait ctx.send(f'I found:{number_of_files}total files')
其他:
等待ctx.send(“,file=discord.file(path+“\\”+random.choice(os.listdir(path)))
我希望能够做一些像;帖子1
,;post maxindex()
或;post
。带有整数或零的命令将发布该数量或一个图像(如果没有)。带有“MaxIndex()”字符串的命令将允许查看文件夹中有多少“可用”图像
如果我不够清楚,请让我澄清。(呃,我的回答太长了。)
我要寻找的是一种允许整数、字符串和布尔值进入函数参数的方法
你可以检查你的价值是否与你期望的一样
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李>
- 我的参数是一个列表李>
- 嗯。不是我想要的东西
Union[]
,可用于自动将参数转换为预先选择的任何类型列表。例如,您可以执行以下操作:
async def post(ctx,type:typing.Union[None,int,str,bool]):
使用isinstance(…,int)
,isinstance(…,bool)
,是否可以简化它?另外,如果ctx.channel.is_nsfw()=True:
将不起作用,您需要=
来测试是否相等。此外,我不会使用类型作为变量-它对内置类型()
进行隐藏,这在这里并不重要,但是一个坏习惯,可能导致confusion@roganjosh我知道==是必需的,但我不得不对代码进行快速编辑,不小心删除了第二个等号