-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
322 lines (268 loc) · 9.25 KB
/
Copy pathapp.py
File metadata and controls
322 lines (268 loc) · 9.25 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
from crypt import methods
import os
import requests
import json
import random
import urllib.parse
from flask import abort, Flask, config, jsonify, request, json, render_template, Response, make_response, g
from flask_apscheduler import APScheduler
from pornhub_api import PornhubApi
from flask_caching import Cache
url = "https://icanhazdadjoke.com/"
headers = {
"Accept": "application/json"
}
subreddits = ["buildapcsales", "freegamestuff"]
slack_urls = {}
postTokens = {}
for subreddit in subreddits:
postTokens[subreddit] = os.environ["postToken_" + subreddit]
slack_urls[subreddit] = "https://hooks.slack.com/services/" + postTokens[subreddit]
limit = 5
timeframe = 'all' #hour, day, week, month, year, all
listing = 'new' # controversial, best, hot, new, random, rising, top
debug = os.environ['debug']
#print(f'Debug: {debug}\nToken: {postTokens}')
app = Flask(__name__)
# initialize and start the flask app scheduler
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
# configure and initilize the memory based cache
cacheConfig = {
"CACHE_TYPE": "FileSystemCache",
"CACHE_DEFAULT_TIMEOUT": 3600,
"CACHE_DIR": "/tmp"
}
cache = Cache()
cache.init_app(app=app, config=cacheConfig)
# put an emptyList in the cache entry named "latest_list"
emptyList = {}
cache.set("latest_list", emptyList, timeout=0)
for item in subreddits:
cache.set(item, emptyList, timeout=0)
# get a reddit post from a subreddit and return a dict indexed on id with:
# title
# url
# flair
def get_reddit(subreddit,listing,limit,timeframe):
response = {}
try:
base_url = f'https://www.reddit.com/r/{subreddit}/{listing}.json?limit={limit}&t={timeframe}'
# print(base_url)
request = requests.get(base_url, headers = {'User-agent': 'slackbot/dadjokes'})
except:
print('An Error Occured')
r = request.json()
#print(r)
for post in r['data']['children']:
title = post['data']['title']
id = post['data']['id'].strip()
url = post['data']['url']
if len(post['data']['link_flair_richtext']) == 0:
flair = ""
else:
flair = post['data']['link_flair_richtext'][0]['t']
# if the post is considered expired or is a meta post, skip it
if flair.strip().lower() == "expired" or flair.strip().lower() == "meta":
continue
response[id] = {
'title': title,
'url': url,
'flair': flair
}
return response
# returns a dict that is a valid slack block object
def format_post(r):
rDict = {
"blocks": []
}
for id in r:
title = r[id]['title']
url = r[id]['url']
flair = r[id]['flair']
rDict['blocks'].append(
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"{title} | {url}"
}
}
)
return(rDict)
# returns the difference between 2 dicts. If the new one is empty then it returns the current one
def diff(current, new):
output = {}
if debug == "1":
print("Current is: ")
simple_print(current)
print("")
print("New is: ")
simple_print(new)
print("")
if len(new) == 0:
output = current
else:
for key in new:
if key not in current:
print(f"Found a new item [{key}]")
output[key] = new[key]
return output
# debugging printing
# prints out in a readable format instead of raw dict output
def simple_print(r):
for id in r:
title = r[id]['title']
url = r[id]['url']
flair = r[id]['flair']
print(f"[{id}] {title} [{url}] [{flair}]")
def is_request_valid(request):
is_token_valid = request.form['token'] in os.environ['token'].split(',')
is_team_id_valid = request.form['team_id'] in os.environ['team'].split(',')
# print(request.form)
return is_token_valid and is_team_id_valid
@app.route('/dadjoke', methods=['POST'])
def dadjoke():
if not is_request_valid(request):
abort(400)
r = requests.get(url=url, headers=headers)
if ( r.status_code == 200 ):
resp = r.json()['joke']
else:
resp = "Something went wrong!"
return jsonify(
response_type='in_channel',
text=resp
)
@app.route('/aidream', methods=['POST'])
def aidream():
if not is_request_valid(request):
abort(400)
if request.form['text'] is not None:
query=request.form['text']
else:
query="I dream of androids"
equery = urllib.parse.quote(query)
imageurl = "https://api.computerender.com/generate/{equery}".format(equery=equery)
markdown = "<{imageurl}|{query}>".format(imageurl=imageurl, query=query)
if debug:
print("DEBUG: requesting the following URL: [{query}]".format(query=urllib.parse.quote(query)))
rDict = {
"blocks": [
{
"type": "image",
"image_url": str(imageurl),
"alt_text": str(query)
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": str(markdown)
}
}
],
"response_type": "in_channel"
}
if debug:
print("DEBUG: {rDict}".format(rDict=rDict))
return rDict
@app.route('/nsfp', methods=['POST'])
def phub():
if not is_request_valid(request):
abort(400)
api = PornhubApi()
if request.form['text'] is not None:
search=request.form['text']
else:
search="tits"
results = api.search.search(q=search, ordering="featured", thumbsize="large_hd")
vid = random.choice(results.videos)
thumbnail = random.choice(vid.thumbs)
# If we got back both the title, image url, and video url, then we are good to go
if vid is not None:
if vid.title is not None and thumbnail.src is not None and vid.url is not None:
resp = True
else:
resp = False
# If the response was valid then create an slack block API response with the image, title, and a link to the video
if resp is True:
rDict = {
"blocks": [
{
"type": "image",
"image_url": str(thumbnail.src),
"alt_text": vid.title
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": "{title} | {url}".format(title=vid.title, url=str(vid.url))
}
]
}
],
"response_type": "in_channel"
}
# otherwise respond with an error message
else:
rDict = {
"blocks": [
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Something went wrong!"
}
}
]
}
# print("test: [{}]".format(rDict))
return rDict
@app.route('/', methods=['GET'])
def slash():
return "<html><a href=\"https://github.com/linkages/dadjokes\">Dad jokes repo</a></html>"
@scheduler.task('interval', id='reddit', seconds=120, misfire_grace_time=900)
def reddit():
for subreddit in subreddits:
# get the latest list from the cache
latest_list = cache.get(subreddit)
# make a request to reddit to get the lastest items
new_request = get_reddit(subreddit,listing,limit,timeframe)
if debug == "1":
print("Newist list is for [" + subreddit + "]: ")
simple_print(new_request)
# Calculate the difference between the new request and the latest cache list
difference = diff(current=latest_list, new=new_request)
if debug == "1":
print("Difference for [" + subreddit + "]:")
simple_print(difference)
print("")
# If the size of the difference dict is zero then nothing changed since we last checked
# lets just remove the cache entry and refresh it
if len(difference) == 0:
print("Nothing new to post for [" + subreddit + "]")
cache.delete(subreddit)
cache.set(subreddit, new_request, timeout=0)
else:
# Something is different
print("Found some new stuff and updating the cache for [" + subreddit + "]")
# set the local latest_list to the new items
latest_list = new_request
# delete the cache
cache.delete(subreddit)
# update the cache
cache.set(subreddit, latest_list, timeout=0)
#print("Would post the following:")
#simple_print(latest_list)
#print("")
# create a slack block post dict using just the differences
post = format_post(difference)
# print(post)
# Set appropriate headers and post to slack
headers = {'Content-type': 'application/json'}
response = requests.post(slack_urls[subreddit], headers=headers, data=json.dumps(post))
#print(response)