#!/usr/bin/python # Copyright 2015 (c) Anna Schumaker. # import re import slack import sys from email.parser import Parser headers = Parser().parsestr(sys.stdin.read()) # # Only allow replies that come from the slack user's email address. # sender = headers.get("sender", headers.get("from")) match = re.search("<(.*?)@(.*?)>", sender) addr = match.group(0)[1:-1] if match else sender if addr.replace(".", "") != slack.user().email().replace(".", ""): print("Reply not from user!") sys.exit(1) # # Find the message payload (this is tricky for multipart messages) # if headers.is_multipart(): for part in headers.get_payload(): if part.get_content_type() == "text/plain": payload = part.get_payload(decode = True) else: payload = headers.get_payload(decode = True) if type(payload) is bytes: payload = payload.decode() # # Find the thread id in the message payload # reply = "--- Reply above this line ---(\s*?)thread=(.*?)\n" match = re.search(reply, payload) if match == None: print("Reply line missing!") sys.exit(1) thread_id = match.group(0).rsplit("=")[-1].rstrip() # # Parse the message payload to find the text that was sent. # Note that we make the following assumptions: # # - Quoted text will always begin with ">" # - The email reply will always have "Reply sent on " text # message = re.sub("^>(.*?)\n", "", payload, flags=re.MULTILINE).rstrip() split = message.split("\n") message = "\n".join(split[:-1]).rstrip() # # Post the message to the thread # thread = slack.find_thread(thread_id) if thread == None: print("No such thread: %s!" % thread_id) sys.exit(1) if thread.post(message) == False: print("Error posting to thread: %s" % thread_id) sys.exit(1)