python - 在 discord.py 上有一个搜索命令
问题描述
想知道是否可以向我的不和谐机器人添加搜索命令,我基本上会使用该命令在目录中查找文件。例如有一个名为 name.txt 的文件,我可以这样做/search nam
,它会搜索这个文件并输出目录中类似文件的名称。
解决方案
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)
推荐阅读
- selenium - 使用基本测试类时的 TestNg 并行测试/类
- ajax - Django“ajax-CRUD-tutorial”,“NoReverseMatch”更新客户
- ajax - 如何在 http post 中获取 cookie
- angular - 按值复制数组及其所有元素
- c - 如何在没有直接连接的其他库中调用库函数?
- reactjs - 在 ReactJS 中将 CSS 类添加到 JSX
- firebase - 如何在 Firestore REST API runQuery 中对复合过滤器使用“或”操作
- html - 双击时更改文本颜色
- protobuf-net - 如何忽略作为父类成员的属性?
- azure - Azure 通过 ip 范围限制对 Web 应用程序的访问