首页 > 解决方案 > 在 discord.py 上有一个搜索命令

问题描述

想知道是否可以向我的不和谐机器人添加搜索命令,我基本上会使用该命令在目录中查找文件。例如有一个名为 name.txt 的文件,我可以这样做/search nam,它会搜索这个文件并输出目录中类似文件的名称。

标签: pythondiscord.py

解决方案


listdir这很简单,只需从模块导入os并指定文件夹路径即可,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)

推荐阅读