- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
Latest commit
175 lines (130 loc) · 4.53 KB
/
Copy pathlambda_function.py
File metadata and controls
175 lines (130 loc) · 4.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
'''
Slack "slash command" bot, via AWS Lambda, serving a random Wikipedia link+blurb.
http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html
https://api.slack.com/slash-commands
Based on existing Lambda Slack template.
For generating the encrypted verification key:
$ aws kms encrypt --profile <name> --key-id alias/<KMS key name> --region us-west-2 --plaintext "<verification>"
'''
importboto3
importjson
importlogging
importos
importre
importrequests
importtraceback
importurllib
frombase64importb64decode
fromurlparseimportparse_qs
ENCRYPTED_EXPECTED_TOKEN=os.environ['kmsEncryptedToken']
kms=boto3.client('kms')
expected_token=kms.decrypt(CiphertextBlob=b64decode(ENCRYPTED_EXPECTED_TOKEN))['Plaintext']
logger=logging.getLogger()
logger.setLevel(logging.DEBUG)
# `err` should only be used for auth error,
# everything else should be 200 so it goes to Slack.
defbuild_response(err, msg=None, attachment=None):
response= {}
iferr:
response['statusCode'] ='400'
response['body'] =err.message
else:
response['statusCode'] ='200'
body= {
"response_type": "in_channel",
"text": msg
}
ifattachmentisnotNone:
body['attachments'] = [
{
'text': attachment
}
]
response['body'] =json.dumps(body)
response['headers'] = {
'Content-Type': 'application/json'
}
logger.info("Responding: %s "%response)
returnresponse
defrespond_to_command(text, user=None, channel=None):
iftext=="help":
returnlist_commands()
eliftext=="learn":
returnrandom_wikipedia_link()
# elif text == "info":
# return show_info()
else:
returnbuild_response(
None,
"Hello %s! I don't understand '%s'."% (user, text)
)
deflist_commands():
valid_commands= [
'help',
'learn',
#'info'
]
returnbuild_response(
None,
("Valid commands are: %s"%', '.join(valid_commands))
)
defrandom_wikipedia_link():
logger.info("Fetching random Wikipedia article")
req=requests.head("https://en.wikipedia.org/wiki/Special:Random")
logger.debug('req.url for random article: %s'%req.url)
article_url=req.headers['location']
logger.info('Returned URL: %s'%article_url)
# Fetch the article extract
# URL looks like 'https://en.wikipedia.org/wiki/foo'
article_slug=re.findall(r"/wiki/(.*)$", article_url)[0]
logger.debug('Extracted article_slug: %s'%article_slug)
article_slug=urllib.unquote(article_slug)
req=requests.get('https://en.wikipedia.org/w/api.php', params={
'format': 'json',
'action': 'query',
'prop': 'extracts',
'titles': article_slug
})
logger.debug('req.url for article metadata: %s'%req.url)
logger.debug('metadata raw response: status: %s, body: %s'% (req.status_code, req.text))
article_meta=req.json()
logger.debug('article_meta: %s', article_meta)
_pages=article_meta['query']['pages']
_article_id=_pages.keys()[0]
logger.debug('parsed article id: %s'%_article_id)
extract=_pages[_article_id]['extract']
logger.debug('parsed extract: %s'%extract)
extract=simplify_html(extract, 600)
returnbuild_response(None, article_url, extract)
defsimplify_html(html, max_len=None):
# line breaks
html=re.sub('(</p>|<br>)', '\n', html)
# remove all other tags
html=re.sub('<[^<]+?>', '', html)
iflen(html) >max_len:
html=html[:max_len] +'...'
logger.debug('simplified html %s'%html)
returnhtml
defshow_info():
logger.info('Returning environment info')
returnbuild_response(
None,
'\n'.join([("%s: %s"%item) foriteminos.environ.items()])
)
deflambda_handler(event, context):
logger.info("Received: %s"%event)
params=parse_qs(event['body'])
token=params['token'][0]
iftoken!=expected_token:
logger.error("Request token (%s) does not match expected: %s"%token)
returnbuild_response(Exception('Invalid request token'))
try:
returnrespond_to_command(
params['text'][0],
params['user_name'][0],
params['channel_name'][0]
)
exceptExceptionaserr:
err_msg='Error: %s\n%s'% (err, traceback.format_exc())
logger.error(err_msg)
returnbuild_response(None, err_msg)