NOTE
The script relies on ruamel-yaml and requests packages available on pypi.
I wrote a script which goes over the pack file details as specified by the emojipacks project, and downloads (and saves) to the local drive. It downloads the files as threads, and saves to disk with the shutil's copyfileobj
method.
Feel free to nitpick each and everything which could be improved.
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfileobj
from threading import Thread
import requests
import ruamel.yaml as YAML
yaml = YAML.YAML(typ="safe")
DOWNLOAD_DIR: str = "emojis"
def download_file(url: str, filename: str, parent: Path):
"""
Downloads the file from `url` and saves to `filename` inside the `parent` directory.
"""
suffix = url.split(".")[-1]
if suffix in ("png", "jpg", "gif", "jpeg"):
filename = f"{filename}.{suffix}"
path = Path(parent / filename)
with requests.get(url, stream=True) as response:
with path.open(mode="wb") as f:
copyfileobj(response.raw, f)
def create_download_thread(url: str, name: str, path: Path) -> Thread:
thread = Thread(target=download_file, args=(url, name, path))
thread.start()
return thread
def main(dir_path: str, download_dir: str):
path = Path(dir_path)
threads = []
if not path.is_dir():
return
for yaml_file in path.glob("*.yaml"):
data = yaml.load(yaml_file)
emoji_dir = Path(download_dir) / data["title"]
emoji_dir.mkdir(parents=True, exist_ok=True)
for emoji in data["emojis"]:
names = [emoji.get("name"), *emoji.get("aliases", [])]
src = emoji.get("src")
threads += [create_download_thread(src, name, emoji_dir) for name in names]
for thread in threads:
thread.join()
if __name__ == "__main__":
parser = ArgumentParser(description="Download emojipacks to specified directory!")
parser.add_argument(
"directory",
nargs="+",
help="Directory(ies) with yaml for the emojipack specifications.",
)
parser.add_argument(
"-p",
"--download-path",
help="Directory where emojis will be downloaded.",
default=DOWNLOAD_DIR,
)
args = parser.parse_args()
for path in args.directory:
main(path, args.download_path)
The script was created because the project emojipacks itself is no longer maintained and the authentication system has been updated from slack. The downloaded emojis are then bulk uploaded to slack using another utility slack-emojinator.
EDIT
Since this point was raised in the answer(s), the yaml specification is:
Also note that the yaml file must be indented properly and formatted as such:
title: food emojis: - name: apple src: http://i.imgur.com/Rw0Vlda.png - name: applepie src: http://i.imgur.com/g4RU1fM.png
..with the src pointing to an image file. According to Slack:
[...]
It is possible to give multiple names to a single emoji using yaml such as:
title: octicons emojis: - name: pr aliases: - pullrequest - mergerequest src: https://i.imgur.com/rhwNxfc.png
emphasis mine