Skip to content

Instantly share code, notes, and snippets.

@raybuhr
Created April 3, 2021 01:53
Show Gist options
  • Save raybuhr/5c6ceb34b2925da81a5b33ba75fdced6 to your computer and use it in GitHub Desktop.
Save raybuhr/5c6ceb34b2925da81a5b33ba75fdced6 to your computer and use it in GitHub Desktop.
python script to download and upload a bunch of emojis to slack
import argparse
import os
import pathlib
import sys
from time import sleep
from bs4 import BeautifulSoup
import pandas as pd
import requests
def wget_img(filename, link):
"""download emoji image from emojipack link"""
subprocess.call(['wget', '-O', filename, link, '--no-check-certificate'])
def get_html(url):
r = requests.get(url, verify=False)
soup = BeautifulSoup(r.text, 'html.parser')
img_links = [l for l in r.text.splitlines() if "<img src" in l or '<div class="mt3 gray">' in l]
return {'request': r, 'soup': soup, 'image_links': img_links}
def links_to_df(img_links):
df = pd.DataFrame([(link, name) for link, name in zip(img_links[::2], img_links[1::2])], columns=["link", "name"])
df['link'] = df.link.apply(lambda x: str(x).split('"')[1])
df['name'] = df.name.apply(lambda x: str(x).split('>')[1].replace('</div', ''))
df['filename'] = df.name.apply(lambda x: x.replace(':', '') + '.png')
return df
def download_emojis(url, directory):
html = get_html(url)
df = links_to_df(html['image_links'])
for i in df.itertuples():
wget_img(directory / i.filename, i.link)
def make_session(cookie, api_token, team_name):
session = requests.session()
session.headers = {'Cookie': cookie}
session.api_token = api_token
session.url_customize = f"https://{team_name}.slack.com/customize/emoji"
session.url_add = f"https://{team_name}.slack.com/api/emoji.add"
session.url_list = f"https://{team_name}.slack.com/api/emoji.adminList"
return session
def add_emoji(team_name, filename, api_token):
emoji_name = filename.name.replace(".png", "").replace(".", "-")
data = {
'mode': 'data',
'name': emoji_name,
'token': api_token
}
with open(filename, 'rb') as f:
files = {'image': f}
resp = requests.post(f"https://{team_name}.slack.com/api/emoji.add", data=data, files=files, allow_redirects=False, verify=False)
if resp.status_code == 429:
wait = int(resp.headers.get('retry-after', 5))
print("429 Too Many Requests!, sleeping for %d seconds" % wait)
sleep(wait)
resp.raise_for_status()
# Slack returns 200 OK even if upload fails, so check for status.
response_json = resp.json()
if not response_json['ok']:
print("Error with uploading %s: %s" % (emoji_name, response_json))
return resp
def upload_emoji(session, emoji_name, filename):
data = {
'mode': 'data',
'name': emoji_name,
'token': session.api_token
}
while True:
with open(filename, 'rb') as f:
files = {'image': f}
resp = session.post(session.url_add, data=data, files=files, allow_redirects=False, verify=False)
if resp.status_code == 429:
wait = int(resp.headers.get('retry-after', 1))
print("429 Too Many Requests!, sleeping for %d seconds" % wait)
sleep(wait)
continue
resp.raise_for_status()
# Slack returns 200 OK even if upload fails, so check for status.
response_json = resp.json()
if not response_json['ok']:
print("Error with uploading %s: %s" % (emoji_name, response_json))
break
def parse_args():
parser = argparse.ArgumentParser(
description='Bulk upload emoji to slack'
)
parser.add_argument(
'--team-name',
default=os.getenv('SLACK_TEAM'),
help='Defaults to the $SLACK_TEAM environment variable.'
)
parser.add_argument(
'--api-token',
default=os.getenv('SLACK_API_TOKEN'),
help='Defaults to the $SLACK_API_TOKEN environment variable.'
)
if __name__ == "__main__":
args = _argparse()
packs = [
'https://emojipacks.com/packs/minecraft',
'https://emojipacks.com/packs/rick-and-morty',
'https://emojipacks.com/packs/octicons',
'https://emojipacks.com/packs/neko-atsune',
'https://emojipacks.com/packs/futurama',
'https://emojipacks.com/packs/food',
'https://emojipacks.com/packs/unicorns',
'https://emojipacks.com/packs/business-fish',
'https://emojipacks.com/packs/startups',
'https://emojipacks.com/packs/yoyo',
'https://emojipacks.com/packs/star-wars',
'https://emojipacks.com/packs/scrabble-letters',
'https://emojipacks.com/packs/retro-games',
'https://emojipacks.com/packs/national-basketball-league',
'https://emojipacks.com/packs/logos',
'https://emojipacks.com/packs/shiba',
'https://emojipacks.com/packs/politipack',
'https://emojipacks.com/packs/animals',
]
path = pathlib.Path("emojis")
for url in packs:
directory = path / f'{url.split("/")[-1]}'
directory.mkdir(exist_ok=True)
download_emojis(url, directory)
emojis = [e for e in path.iterdir()]
for e in emojis:
print('*'*50)
print('Uploading', e)
add_emoji(args.team_name, e, args.api_token)
# upload_emoji(s, e.name.replace('.png', ''), e)
print('*'*50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment