Skip to content

Instantly share code, notes, and snippets.

@azabost
Forked from iam-mhaseeb/slackmojis_downloader.py
Last active October 12, 2022 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azabost/c73394854e4022e9cc67547913b231d5 to your computer and use it in GitHub Desktop.
Save azabost/c73394854e4022e9cc67547913b231d5 to your computer and use it in GitHub Desktop.
Slackmojis.com Downloader
import os
import sys
import requests
from bs4 import BeautifulSoup
def generate_filename(dest_dir, filename, count):
"""
:rtype: basestring
:type dest_dir: basestring
:type count: int
:type filename: basestring
"""
if count == 1:
candidate = filename
else:
candidate, _, extension = filename.rpartition(".")
candidate = candidate + "-" + count.__str__() + "." + extension
print("Checking %s" % candidate)
if os.path.isfile(os.path.join(dest_dir, candidate)):
print("%s already taken. Trying %d" % (candidate, count + 1))
return generate_filename(dest_dir, filename, count + 1)
else:
return candidate
def show_arg():
req = requests.get(sys.argv[1])
soup_response = BeautifulSoup(req.text, "html.parser")
script_dir = os.path.dirname(os.path.abspath(__file__))
dest_dir = os.path.join(script_dir, "slackmojis")
try:
os.makedirs(dest_dir)
except OSError:
pass # already exists
for img in soup_response.find_all("img"):
src_attr = img.get("src")
if src_attr.find("/"):
filename = src_attr.rsplit("/", 1)[1].split("?", 1)[0]
final_filename = generate_filename(dest_dir, filename, 1)
with open(os.path.join(dest_dir, final_filename), "wb") as file:
print("Downloading %s as %s" % (filename, final_filename))
response = requests.get(src_attr, stream=True)
file_size = response.headers.get("content-length")
if file_size is None: # no content length header
file.write(response.content)
else:
dl = 0
file_size = int(file_size)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
file.write(data)
done = int(50 * dl / file_size)
sys.stdout.write("\r[%s%s]" % ("=" * done, " " * (50 - done)))
sys.stdout.flush()
if __name__ == "__main__":
show_arg()
@azabost
Copy link
Author

azabost commented Oct 12, 2022

There's still one more minor issue here.

If two emojis have the same names but the files have different extensions (e.g. foo.png and foo.gif), they will be downloaded normally but the bulk upload to Slack e.g. with this browser extension will probably fail because the generated emoji names (based on the names of the files) will be the same, so only the first file will be uploaded.

I encourage you to further improve this script to generate the suffixes in a smarter way (e.g. when foo.png already exists and we try to download foo.gif, generate foo-2.gif instead)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment