Created
September 2, 2018 12:20
-
-
Save yasuabe/6c5f8ce20d59154509667619b8837ec2 to your computer and use it in GitHub Desktop.
slack-ops-test2-func: connecting to RDS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import json | |
import logging | |
from urllib import request, parse | |
import pymysql | |
token = os.environ['TOKEN'] | |
rds_host = os.environ['RDS_HOST'] | |
name = os.environ['NAME'] | |
password = os.environ['PASSWORD'] | |
db_name = os.environ['DB_NAME'] | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
try: | |
logger.info("connecting: {}, {}, {}, {}".format(rds_host, name, password, db_name)) | |
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=20) | |
logger.info("connected") | |
except: | |
logger.error("ERROR: Unexpected error") | |
sys.exit() | |
def lambda_handler(event, context): | |
logger.info(str(event)) | |
if ('challenge' in event): | |
return { | |
"statusCode": 200, | |
"body": json.dumps({'challenge': event['challenge']}) | |
} | |
else: | |
process_event(event['event']) | |
return { "statusCode": 200 } | |
def process_event(event): | |
item = event['item'] | |
channel = item['channel'] | |
ts = item['ts'] | |
reaction = event['reaction'] | |
logger.info('{}, {}, {}, {}'.format(item, channel, ts, reaction)) | |
text = retrieve_item_text(channel, ts) | |
logger.info(text) | |
post_result(channel, ts, text) | |
def retrieve_item_text(channel, ts): | |
url = 'https://slack.com/api/channels.history' | |
params = { | |
'token': token, | |
'channel': channel, | |
'count': 1, | |
'inclusive': True, | |
'latest': ts | |
} | |
requestUrl = '{}?{}'.format(url, parse.urlencode(params)) | |
req = request.Request(requestUrl) | |
with request.urlopen(req) as res: | |
body = res.read().decode('utf-8') | |
return json.loads(body)['messages'][0]['text'] | |
def post_result(channel, thread_ts, text): | |
url = 'https://slack.com/api/chat.postMessage' | |
params = { | |
'token': token, | |
'channel': channel, | |
'text': text, | |
'thread_ts': thread_ts | |
} | |
requestUrl = '{}?{}'.format(url, parse.urlencode(params)) | |
req = request.Request(requestUrl) | |
with request.urlopen(req) as response: | |
response_body = response.read().decode("utf-8") | |
logger.info(str(response_body)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment