forked from JosXa/BotListBot
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbotlistapi.py
More file actions
276 lines (228 loc) · 7.62 KB
/
Copy pathbotlistapi.py
File metadata and controls
276 lines (228 loc) · 7.62 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
import datetime
import random
import markdown
import os
from flask import Flask, request, jsonify, send_from_directory, send_file
from flask import Markup
from flask_autodoc.autodoc import Autodoc
from peewee import fn
import settings
from models import Bot
from models import Category
from models.apiaccess import APIAccess
def md2html(text):
text = str(text)
import textwrap
res = Markup(markdown.markdown(
textwrap.dedent(text),
[
'markdown.extensions.codehilite',
'markdown.extensions.nl2br',
'markdown.extensions.extra',
'markdown.extensions.admonition'
], extension_configs={
'markdown.extensions.codehilite': {
'noclasses': True,
'pygments_style': 'colorful'
}
}))
return res
app = Flask(__name__, static_url_path='/doc')
app.jinja_env.filters['markdown'] = md2html
auto = Autodoc(app)
# Disabled until security issues are figured out
# admin = Admin(app, name='botlist', template_mode='bootstrap3')
#
# admin.add_view(ModelView(Bot))
# admin.add_view(ModelView(Category))
# admin.add_view(ModelView(Channel))
# admin.add_view(ModelView(Favorite))
# admin.add_view(ModelView(Group))
# admin.add_view(ModelView(Suggestion))
# TODO: doesn't work
# app.config['APPLICATION_ROOT'] = '/botlist/api/v1'
def start_server():
http_server = WSGIServer((settings.API_URL, settings.API_PORT), app)
return http_server.serve_forever()
def _error(message):
return jsonify({
'error': message,
'url': request.url
})
@app.route('/submit', methods=['POST'])
@auto.doc()
def submit():
if not request.is_json:
res = _error('MimeType must be application/json.')
res.status_code = 400
return res
content = request.get_json()
try:
access = APIAccess.get(APIAccess.token == content.get('token'))
except APIAccess.DoesNotExist:
res = _error('The access token is invalid.')
res.status_code = 401
return res
username = content.get('username')
if username is None or not isinstance(username, str):
res = _error('You must supply a username.')
res.status_code = 400
return res
# insert `@` if omitted
username = '@' + username if username[0] != '@' else username
try:
Bot.get(Bot.username == username)
res = _error('The bot {} is already in the BotList.'.format(username))
res.status_code = 409
return res
except Bot.DoesNotExist:
b = Bot(username=username)
name = content.get('name')
description = content.get('description')
inlinequeries = content.get('inlinequeries')
try:
if name:
if isinstance(name, str):
b.name = name
else:
raise AttributeError('The name field must be a string.')
if description:
if isinstance(description, str):
b.description = description
else:
raise AttributeError('The description field must be a string.')
if inlinequeries:
if isinstance(inlinequeries, bool):
b.inlinequeries = inlinequeries
else:
raise AttributeError('The inlinequeries field must be a boolean.')
except Exception as e:
res = _error(str(e))
res.status_code = 400
return res
b.date_added = datetime.date.today()
b.submitted_by = access.user
b.approved = False
b.save()
res = jsonify({
'success': '{} was submitted for approval.'.format(b)
})
res.status_code = 201
return res
@app.route('/bots', methods=['GET'])
@app.route('/bots/<int:page>', methods=['GET'])
@auto.doc()
def bots_endpoint(page=1):
"""
Return bots from the BotList.
Use the url parameters `url` or `username` to perform a search on the BotList.
The @-character in usernames can be omitted.
:param page: The page to display
:return: All bots (paginated) or the search result if url parameters were used.
"""
if request.method == 'GET':
results = list()
if len(request.args) > 0:
# return bots matching the request arguments (after ?)
id_arg = request.args.get('id', None)
username_arg = request.args.get('username', None)
if id_arg:
results = Bot.select().where(Bot.id == id_arg).limit(1)
elif username_arg:
# allow for omitting the `@` in the username
results = Bot.select().where(
(Bot.username == username_arg) | (Bot.username == '@' + username_arg)).limit(1)
data = results[0].serialize
if data:
res = jsonify({
'search_result': data,
'meta': {'url': request.url}
})
res.status_code = 200
else:
res = _error('No bot found with your search parameters.')
res.status_code = 404
return res
else:
# return all bots (paginated)
per_page = 50
results = Bot.select().paginate(page, per_page)
data = [i.serialize for i in results]
if data:
res = jsonify({
'bots': data,
'meta': {'page': page, 'per_page': per_page, 'page_url': request.url}
})
res.status_code = 200
else:
res = _error('No bots found.')
res.status_code = 500
return res
@app.route('/offline', methods=['POST'])
@auto.doc()
def set_offline():
pass
@app.route('/categories', methods=['GET'])
@auto.doc()
def categories_endpoint():
"""
Returns all categories of the BotList.
"""
if request.method == 'GET':
query = Category.select_all()
data = [i.serialize for i in query]
if data:
res = jsonify({
'categories': data,
'meta': {'url': request.url}
})
res.status_code = 200
else:
res = _error('No categories found.')
res.status_code = 500
return res
@app.route('/random', methods=['GET'])
@auto.doc()
def random_bot():
"""
Returns a random bot from the BotList. By default, only "interesting" bots with description and tags are shown.
Use the parameter `?all=True` to receive _all_ possible choices.
"""
show_all = bool(request.args.get("all", False))
if show_all:
random_bot = Bot.select().order_by(fn.Random()).limit(1)[0]
else:
random_bot = random.choice(Bot.explorable_bots())
data = random_bot.serialize
if data:
res = jsonify({
'search_result': data,
'meta': {'url': request.url}
})
res.status_code = 200
else:
res = _error("No bot found.")
return res
@app.route('/thumbnail/<username>.jpeg', methods=['GET'])
@auto.doc()
def thumbnail(username):
if username[0] != '@':
username = '@' + username
try:
item = Bot.by_username(username)
except Bot.DoesNotExist:
item = None
if not item:
return _error("There is no bot in the BotList with the username {}.".format(username))
if not os.path.exists(item.thumbnail_file):
return _error("Sorry, we don't have a thumbnail for this bot.")
return send_file(item.thumbnail_file, mimetype='image/jpeg')
@app.route('/')
def documentation():
return auto.html(
template='autodoc.html',
title='BotListBot API',
author='JosXa',
)
if __name__ == '__main__':
app.run(debug=True)