Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring, Check if emoji already exists, and improved error detection #6

Merged
merged 1 commit into from
Aug 1, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 39 additions & 8 deletions upload.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -10,20 +14,40 @@
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 = {
Expand All @@ -35,4 +59,11 @@
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()