1
0
Fork 0

Merge pull request #6 from kvarga/check_existing_emojis

Refactoring, Check if emoji already exists, and improved error detection
This commit is contained in:
Ash Wilson 2016-08-01 08:38:55 -04:00 committed by GitHub
commit c49d621746
1 changed files with 39 additions and 8 deletions

View File

@ -1,6 +1,10 @@
#!/usr/bin/env python
# Upload files named on ARGV as Slack emoji.
# https://github.com/smashwilson/slack-emojinator
import os
import re
import sys
import requests
@ -10,20 +14,40 @@ team_name = os.getenv('SLACK_TEAM')
cookie = os.getenv('SLACK_COOKIE')
url = "https://{}.slack.com/customize/emoji".format(team_name)
headers = {
'Cookie': cookie,
}
for filename in sys.argv[1:]:
print("Processing {}.".format(filename))
emoji_name = os.path.splitext(os.path.basename(filename))[0]
def main():
existing_emojis = get_current_emoji_list()
uploaded = 0
skipped = 0
for filename in sys.argv[1:]:
print("Processing {}.".format(filename))
emoji_name = os.path.splitext(os.path.basename(filename))[0]
if emoji_name in existing_emojis:
print("Skipping {}. Emoji already exists").format(emoji_name)
skipped += 1
else:
upload_emoji(emoji_name, filename)
print("{} upload complete.".format(filename))
uploaded += 1
print('\nUploaded {} emojis. ({} already existed)'.format(uploaded, skipped))
headers = {
'Cookie': cookie,
}
def get_current_emoji_list():
r = requests.get(url, headers=headers)
r.raise_for_status()
x = re.findall("data-emoji-name=\"(.*)\"", r.text)
return x
def upload_emoji(emoji_name, filename):
# Fetch the form first, to generate a crumb.
r = requests.get(url, headers=headers)
r.raise_for_status()
soup = BeautifulSoup(r.text)
soup = BeautifulSoup(r.text, "html.parser")
crumb = soup.find("input", attrs={"name": "crumb"})["value"]
data = {
@ -35,4 +59,11 @@ for filename in sys.argv[1:]:
files = {'img': open(filename, 'rb')}
r = requests.post(url, headers=headers, data=data, files=files, allow_redirects=False)
r.raise_for_status()
print("{} complete.".format(filename))
# Slack returns 200 OK even if upload fails, so check for status of 'alert_error' info box
if 'alert_error' in r.content:
soup = BeautifulSoup(r.text, "html.parser")
crumb = soup.find("p", attrs={"class": "alert_error"})
raise Exception("Error with uploading %s: %s" % (emoji_name, crumb.text))
if __name__ == '__main__':
main()