Python 在discord.py上有搜索命令

Python 在discord.py上有搜索命令,python,discord.py,Python,Discord.py,想知道是否有可能添加一个搜索命令到我的discord机器人,我将基本上使用该命令来查找目录中的文件。例如,有一个名为name.txt的文件,我可以执行/search nam,它将搜索该文件并在目录中输出类似文件的名称。很简单,只需从os模块导入listdir,并将文件夹路径指定给listdir函数,然后在命令中添加一个参数,用于匹配给定路径中的文件 请尝试以下代码: @bot.command() async def search(ctx, file_name): search_resul

想知道是否有可能添加一个搜索命令到我的discord机器人,我将基本上使用该命令来查找目录中的文件。例如,有一个名为name.txt的文件,我可以执行
/search nam
,它将搜索该文件并在目录中输出类似文件的名称。

很简单,只需从
os
模块导入
listdir
,并将文件夹路径指定给
listdir
函数,然后在命令中添加一个参数,用于匹配给定路径中的文件

请尝试以下代码:

@bot.command()
async def search(ctx, file_name):
    search_result = 'Search Results:'
    from os import listdir
    for file in listdir('data'):
        if file_name in file.lower():
            search_result = search_result+'\n'+file
    if search_result == 'Search Results:':
        await ctx.send('Error: Not matched with any file.')
    else:
        await ctx.send(search_result)

在服务器上的目录?主机上的目录中,我的bot托管在一个树莓pi上,所以搜索命令将搜索rpi上的目录,而不是discord服务器。谢谢!像我想的那样工作。还想知道是否可以在现有命令中添加此代码,我有一个get命令可以获取某个文件并输出指向该文件的链接,当参数(您想要获取的文件)不正确时是否可以输出搜索结果,类似于:
#get file
未找到文件,但找到了类似的文件:
文件结果
NVM,实际上找到了一种方法,添加:
if get(commands.CommandNotFound):wait ctx.send(“未找到文件,这里有类似的名称:”)search\u result='search results:,查找listdir中的文件('directory/…'):if-arg-in-file.lower():search\u-result=search\u-result+'\n'+file-if-search\u-result=='search-Results:':wait ctx.send('错误:与任何文件都不匹配。')其他:wait ctx.send(search\u-result)