33from discord .ext import commands , tasks
44from discord .utils import MISSING
55
6+ from Levenshtein import distance
67from aiohttp import ClientSession
78from typing import List
89from io import BytesIO
1516
1617db = MongoClient (MONGO_URI ).antbot .minecraft_data
1718versions_pathes = MongoClient (MONGO_URI ).antbot .versions_pathes
18- files = {}
19+ files = []
1920latest_version = ""
2021logs_channel = None
2122
@@ -27,20 +28,20 @@ def __init__(self, bot):
2728
2829 async def get_files_list (self , branches = ("data" , "assets" )):
2930 async with ClientSession (headers = GITHUB_HEADERS ) as session :
30- current_files = {}
31+ current_files = []
3132 for branch in branches :
3233 async with session .get (f"https://api.github.com/repos/misode/mcmeta/git/trees/{ branch } ?recursive=1" ) as response :
3334 if response .status == 200 :
3435 tree = await response .json ()
3536 tree = tree .get ("tree" , [])
36- current_files . update ({
37- "/" . join ( item [ "path" ]. split ( "/" )[ - 2 :]): item ["path" ]
37+ current_files += [
38+ item ["path" ]
3839 for item in tree if item ["type" ] == "blob"
39- })
40+ ]
4041 else :
4142 raise Exception (f"Response error" )
4243 try :
43- current_files .pop (".gitattributes" )
44+ current_files .remove (".gitattributes" )
4445 except :pass
4546 return current_files
4647
@@ -85,13 +86,33 @@ async def update_versions_hashes(self, newer_version=None):
8586 raise Exception ("Mcmeta not updated" )
8687 db .update_one ({"_id" : "versions_hashes" }, {"$set" : {"_" : versions_hashes }}, upsert = True )
8788
88- @commands .hybrid_command (aliases = ["f" , "asset" , "mcasset" , "файл" , "ашду" , "ассет" , "эссет" , "мсассет" , "мсэссэт" ,"фыыуе" ,"ьсфыыуе" ],
89+
90+ @commands .hybrid_command (
91+ aliases = ["f" , "asset" , "mcasset" , "файл" , "ашду" , "ассет" , "эссет" , "мсассет" , "мсэссэт" ,"фыыуе" ,"ьсфыыуе" ],
8992 description = "Скидывает файл с ванильного датапака/ресурспака." ,
9093 usage = "`/file <путь/название интересующего файл>`" ,
9194 help = "Структура файлов обновляется в течении 6 минут сразу после выхода новой версии/снапшота. Слэш команда имеет автокомплит для файлов, что делает их поиск легче.\n ### Пример:\n `/file colormap/grass`" )
9295 @app_commands .describe (path = "Путь/название интересующего файла" )
9396
9497 async def file (self , ctx , path : str , version : str = "latest" ):
98+ def search_files (query , files ):
99+ matches = []
100+ for file in files :
101+ if query in file :
102+ matches .append (file )
103+ else :
104+ match_count = 0
105+ query_items_backwards = query .split ("/" )[::- 1 ]
106+ query_size = len (query_items_backwards )
107+ for i in query_items_backwards :
108+ for j in file .split ("/" )[::- 1 ]:
109+ if distance (i , j ) <= len (i )/ 3 :
110+ match_count += 1
111+ break
112+ if match_count >= query_size :
113+ matches .append (file )
114+ break
115+ return matches
95116 is_image = False
96117 if version == "latest" :
97118 current_files = files
@@ -108,7 +129,7 @@ async def file(self, ctx, path: str, version: str="latest"):
108129 versions_hashes ["assets" ][version_for_mongo ]
109130 ))
110131 versions_pathes .insert_one ({"_id" : version_for_mongo , "_" : current_files })
111- all_results = [ value for _ , value in current_files . items () if path in value ]
132+ all_results = search_files ( path , current_files )
112133 path = all_results [0 ]
113134 #
114135 path_tree = ""
@@ -125,7 +146,7 @@ async def file(self, ctx, path: str, version: str="latest"):
125146 raise Exception (f"Response error { response .status } " )
126147 file = discord .File (BytesIO (await response .read ()), filename = path .split ("/" )[- 1 ])
127148 #
128- embed = discord .Embed (description = f"## <{ path_tree .split ("<" )[- 1 ].split ( ">" )[ 0 ] } > { path . split ( '/' )[ - 1 ] } ({ version } )\n { path_tree } " ,
149+ embed = discord .Embed (description = f"## <{ path_tree .split ("<" )[- 1 ].replace ( "`" , "" ) } ({ version } )\n { path_tree } " ,
129150 color = no_color )
130151 if path .endswith ("png" ):
131152 embed .set_image (url = f"attachment://{ file .filename } " )
@@ -174,4 +195,7 @@ async def file_autocomplete(self, ctx: discord.Interaction, curr: str) -> List[a
174195 versions_pathes .insert_one ({"_id" : version , "_" : current_files })
175196 else :
176197 current_files = files
177- return [app_commands .Choice (name = key , value = value [- 100 :]) for key , value in current_files .items () if curr in value ][:25 ]
198+ return [
199+ app_commands .Choice (name = file [- 100 :], value = file [- 100 :])
200+ for file in current_files if curr in file
201+ ][:25 ]
0 commit comments