-
Notifications
You must be signed in to change notification settings - Fork 1
/
tldr.py
81 lines (70 loc) · 2.55 KB
/
tldr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from typing import List, Optional, Tuple
import zipfile
import discord
import re
cache: List[str] = []
def refresh_cache():
"""
Update the zip file and refresh the file list cache
:return: the list of files in the zip file
"""
global cache
import requests
file = requests.get("https://tldr-pages.github.io/assets/tldr.zip").content
with open("tldr.zip", "wb") as zf:
zf.write(file)
with zipfile.ZipFile("tldr.zip") as zf:
cache = zf.namelist()
def get_or_none(name: str, language: str = "", preferred_os: str = "common") -> Tuple[Optional[str], str]:
"""
Get the markdown file, or None if it doesn't exist
"""
if name.startswith("pages"):
if name in cache:
with zipfile.ZipFile("tldr.zip") as zf:
file_loc = zf.extract(name)
with open(file_loc) as file:
return file.read(), ""
else:
return None, ""
else:
for i in [preferred_os, "common", "linux", "windows", "osx", "sunos"]:
results = get_or_none(f'pages{"." + language if language else ""}/{i}/{name}.md')
if results == (None, "") and language:
results = get_or_none(name)
elif results != (None, ""):
break
return results[0], i
def parse(name: str, language: str = "", preferred_os="common") -> discord.Embed:
"""
Take a command and return a Discord Embed of the tldr command
:param name: the command (using dashes in place of spaces)
:param language: the language to use for the pages, or an empty string for English
:param preferred_os: the OS to check first
:return: an embed of the tldr file
"""
file = get_or_none(name, language, preferred_os)
if file[0]:
lines = file[0].replace("\n\n", "\n").splitlines()
title = lines[0][2:]
embed = discord.Embed(
title=title + ("" if preferred_os == file[1] else f' ({file[1]})'),
colour=0x00F0FF,
description="\n".join(lines[1:]).strip()
)
return embed
else:
return discord.Embed(
title="No item found!",
colour=0xF23C3C,
description="The database does not include this item! Send `!tldrrefresh` to refresh the cache."
)
def languages() -> List[str]:
lang_list: List[str] = []
for i in cache:
if not re.match(r'pages\..*', i):
continue
lang = i.split(".")[1].split("/")[0]
if lang not in lang_list:
lang_list.append(lang)
return lang_list