Create a gist now

Instantly share code, notes, and snippets.

@matetsu /config.ini
Last active Dec 10, 2015

What would you like to do?
Slack -> (API Gateway -> ) Lambda -> SES (Reply Email)
[slack]
hook_url = https://hooks.slack.com/services/xxxxxxxxxx/yyyyyyyyyy/zzzzzzzzzzzzzzzzzzzzzzz
username = alert_bot
channel = #alert
icon_emoji = :guardsman:
token = TOKEN
[s3]
region = ap-northeast-1
bucket_name = BUCKET_NAME
[ses]
mail_from = no-reply@SES_RECEIVE_DOMAIN
# coding: utf-8
import boto3
import re
import struct
import traceback
import json
import ConfigParser
from email.parser import FeedParser
from email.header import decode_header, Header
from email.utils import parseaddr, formatdate
from email.mime.text import MIMEText
import slackweb
def send_raw_mail(region, subject, message_id, mail_from, reply_to, mail_body, slack_user):
ses = boto3.client('ses', region_name=region)
body = u"""[Slackユーザ %s からの返信です。]
%s""" % (slack_user, mail_body)
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = "%s <%s>" % (slack_user, mail_from)
msg['To'] = reply_to
msg['In-Reply-To'] = message_id
msg['References'] = message_id
res = ses.send_raw_email(
Source = mail_from,
Destinations = [reply_to],
RawMessage = {'Data': msg.as_string()}
)
return res
def lambda_handler(event, context):
inifile = ConfigParser.SafeConfigParser()
inifile.read("./config.ini")
if not event['token'] == inifile.get('slack', 'token'):
return ""
text = event['text']
user_name = event['user_name']
channel_name = event['channel_name']
response = ""
try:
bucket_region = inifile.get('s3', 'region')
bucket_name = inifile.get('s3', 'bucket_name')
reply_pattern = u"^@alert_bot:?\s+reply\s+(.*?)\s+(.*)"
r = re.search(reply_pattern, text, re.DOTALL)
if r:
mail_object_key = r.group(1)
mail_body = r.group(2)
ses_region = mail_object_key.split('/')[0]
s3 = boto3.client('s3', region_name=bucket_region)
mail_object = s3.get_object(Bucket = bucket_name, Key = mail_object_key)
mail = ''
try:
mail = mail_object["Body"].read().decode('utf-8')
except:
try:
mail = mail_object["Body"].read().decode('iso-2022-jp')
except:
mail = mail_object["Body"].read()
parser = FeedParser()
parser.feed(mail)
parsed_mail = parser.close()
(d_sub, sub_charset) = decode_header(parsed_mail['Subject'])[0]
subject = u"Re: %s" % d_sub.decode(sub_charset)
message_id = parsed_mail['Message-ID']
if parsed_mail.has_key('Reply-To'):
reply_to = parsed_mail['Reply-To']
else:
reply_to = parseaddr(parsed_mail['From'])[1]
send_raw_mail(ses_region, subject, message_id, inifile.get('ses', 'mail_from'), reply_to, mail_body, user_name)
response = u"@%s: 受け付けました" % user_name
else:
response = u"@%s: その操作は受け付けられません。" % user_name
except:
response = u"@%s: error" % user_name
print traceback.format_exc()
finally:
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment