-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
419 lines (359 loc) · 12.8 KB
/
main.py
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import sqlite3
from bs4 import BeautifulSoup
import os
from flask import Flask, request
from json import load, dump, dumps, loads
import sqlite3
from datetime import datetime, timedelta
from urllib.parse import parse_qs
import requests
import builtins
import asyncio
import time
from requests import get
import random
app = Flask(__name__)
global lock_list
lock_list = []
# path to database.db is ./yt_stats_api/database.db
# make a json file that stores the user_id and username relation
def get_user_file():
try:
with open(os.path.join(os.path.dirname(__file__), "users.json")) as f:
return load(f)
except FileNotFoundError:
with open(os.path.join(os.path.dirname(__file__), "users.json"), "w") as f:
dump({}, f)
return {}
return {}
def update_user_file(json):
with open(os.path.join(os.path.dirname(__file__), "users.json"), "w") as f:
dump(json, f)
def get_user_id(username):
for key, value in get_user_file().items():
if value.lower() == username.lower():
return key
return None
points_conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), "points.db"), check_same_thread=False)
points_cursor = points_conn.cursor()
# make a table named points with user_id and points
points_cursor.execute("CREATE TABLE IF NOT EXISTS points (user_id TEXT, points INTEGER, channel_id TEXT)")
points_conn.commit()
def get_preference_file(channel_id:str):
try:
with open(os.path.join(os.path.dirname(__file__), "preferences.json")) as f:
prefs = load(f)
if channel_id not in prefs:
prefs[channel_id] = {"pname": "points"}
update_pref(prefs)
return prefs
return prefs
except FileNotFoundError:
with open(os.path.join(os.path.dirname(__file__), "preferences.json"), "w") as f:
prefs = {}
prefs[channel_id] = {"pname": "points"}
update_pref(prefs)
return prefs
return {}
return {}
def update_pref(json):
with open(os.path.join(os.path.dirname(__file__), "preferences.json"), "w") as f:
dump(json, f)
class User:
name = None
id = None
class Channel:
name = None
id = None
class Points:
points = None
def __init__(self, points:int) -> None:
self.points = points
def add_points(self, amount):
self.points += amount
def remove_points(self, amount):
self.points -= amount
def set_points(self, amount):
self.points = amount
def update(self, user_id, channel_id):
# update the database
points_cursor.execute("SELECT * FROM points WHERE user_id = ? and channel_id = ?", (user_id, channel_id))
if not points_cursor.fetchone():
points_cursor.execute("INSERT INTO points VALUES (?, ?, ?)", (user_id, self.points, channel_id))
else:
points_cursor.execute("UPDATE points SET points = ? WHERE user_id = ? and channel_id = ?", (self.points, user_id, channel_id))
points_conn.commit()
def __str__(self) -> str:
return str(self.points)
def nightbot_parse(headers:dict):
c = parse_qs(headers["Nightbot-Channel"])
u = parse_qs(headers["Nightbot-User"])
channel = Channel()
user = User()
relation = get_user_file()
channel.name = c.get("displayName")[0]
channel.id = c.get("providerId")[0]
user.name = u.get("displayName")[0]
user.id = u.get("providerId")[0]
relation[user.id] = user.name.lower()
relation[channel.id] = channel.name.lower()
update_user_file(relation)
return channel, user
@app.get("/lock")
def lock():
channel, user = nightbot_parse(request.headers)
lock_list.append(channel.id)
return "Locked the points"
@app.get("/unlock")
def unlock():
channel, user = nightbot_parse(request.headers)
lock_list.remove(channel.id)
return "Unlocked the points"
@app.get("/")
def slash():
return "Point System is working fine. You should not be here."
@app.get("/callit")
def callit():
q = request.args.get("q")
new_name = q
channel, user = nightbot_parse(request.headers)
prefs = get_preference_file(channel.id)
prefs[channel.id]["pname"] = new_name
update_pref(prefs)
return f"Changed the name of the points to {new_name}"
@app.get("/give")
def give():
channel, user = nightbot_parse(request.headers)
if channel.id in lock_list:
return "This channel is locked. Moderators have locked the gambling."
q = request.args.get("q")
if not q:
return "Please provide a user to give the points to."
# q should be name and ammount
l = q.split(" ")
prefs = get_preference_file(channel.id)
amount = l[-1]
try:
amount = int(amount)
except ValueError:
return "Please provide a valid amount."
if amount < 0:
return "Please provide a valid amount."
name = " ".join(l[:-1])
if name.startswith("@"):
name = name[1:]
uid = get_user_id(name)
if not uid:
return "Please provide a valid user."
giver_points = get_points(user.id, channel.id)
taker_points = get_points(uid, channel.id)
if giver_points.points < amount:
return "You don't have enough points to give."
giver_points.remove_points(amount)
taker_points.add_points(amount)
giver_points.update(user.id, channel.id)
taker_points.update(uid, channel.id)
return f"{user.name} gave {amount} {prefs[channel.id]['pname']} to {name}."
@app.get("/top")
async def top():
try:
channel, user = nightbot_parse(request.headers)
except KeyError:
return "Not able to auth"
if channel.id in lock_list:
return "This channel is locked. Moderators have locked the gambling."
q = request.args.get("q")
if q:
if not q.isdigit():
return "Please Enter a number between 1 to 20"
q = int(q)
if q > 20:
return "Please enter a number below 20"
if q < 1:
return "Not a Valid number. Enter a number between 1 and 20"
else:
q = 10
# get top 10
points_cursor.execute("SELECT * FROM points WHERE channel_id = ? ORDER BY points DESC LIMIT ?", (channel.id, q))
points = points_cursor.fetchall()
if not points:
return "No data found"
prefs = get_preference_file(channel.id)
string = ""
counter = 1
for p in points:
string += f"{counter}. {get_user_name(p[0])}: {p[1]} {prefs[channel.id]['pname']} | "
counter += 1
if len(string) > 200:
#await asyncio.sleep(5)
response_url = request.headers["Nightbot-Response-Url"]
parts = [string[i:i+200] for i in range(0, len(string), 200)]
for part in parts:
requests.post(response_url, data={"message": part})
await asyncio.sleep(5)
return " "
return string
def get_user_name(uid:str):
relation = get_user_file()
name = ""
try:
name = relation[uid]
except KeyError:
channel_link = f"https://youtube.com/channel/{uid}"
html_data = get(channel_link).text
soup = BeautifulSoup(html_data, 'html.parser')
name = soup.find("meta", {"property": "og:title"})["content"]
return name
def get_points(uid:str, cid:str) -> Points:
points_cursor.execute("SELECT * FROM points WHERE user_id = ? and channel_id = ?", (uid, cid))
points = points_cursor.fetchone()
if not points:
points = Points(50)
points.update(uid, cid) # give free 50 points to start the journey with
else:
points = Points(int(points[1]))
return points
@app.get("/points")
def points():
try:
channel, user = nightbot_parse(request.headers)
except KeyError:
return "Not able to auth"
if channel.id in lock_list:
return "This channel is locked. Moderators have locked the gambling."
q = request.args.get("q")
if q:
if q.startswith("@"):
q = q[1:]
user = User()
user.name = q
user.id = get_user_id(q)
points = get_points(user.id, channel.id)
print(points)
prefs = get_preference_file(channel.id)
string = f"User: {user.name} have {points} {prefs[channel.id]['pname']}"
return string
@app.get("/addpoints")
def addpoints():
try:
channel, user = nightbot_parse(request.headers)
except KeyError:
return "Not able to auth"
prefs = get_preference_file(channel.id)
q = request.args.get("q")
if not q:
return "No query"
l = q.split(" ")
amount = l[-1]
qchannel = " ".join(l[:-1]).lower()
if qchannel.startswith("@"):
qchannel = qchannel[1:]
uid = get_user_id(qchannel)
points = get_points(uid, channel.id)
if not uid:
return "Channel have no account. can you ask them to use the bot once?"
try:
amount = int(amount)
except ValueError:
return "Not a number"
points.add_points(amount)
points.update(uid, channel.id)
return f"Added {amount} {prefs[channel.id]['pname']} to {qchannel}"
@app.get("/removepoints")
def removepoints():
try:
channel, user = nightbot_parse(request.headers)
except KeyError:
return "Not able to auth"
prefs = get_preference_file(channel.id)
q = request.args.get("q")
if not q:
return "No query given"
l = q.split(" ")
amount = l[-1]
qchannel = " ".join(l[:-1]).lower()
if qchannel.startswith("@"):
qchannel = qchannel[1:]
uid = get_user_id(qchannel)
points = get_points(uid, channel.id)
if not uid:
return "Channel have no account. can you ask them to use the bot once?"
try:
amount = int(amount)
except ValueError:
return "Not a number"
points.remove_points(amount)
points.update(uid, channel_id=channel.id)
return f"Removed {amount} {prefs[channel.id]['pname']} from {qchannel}"
@app.get("/gamble")
def gamble():
try:
channel, user = nightbot_parse(request.headers)
except KeyError:
return "Not able to auth"
if channel.id in lock_list:
return "This channel is locked. Moderators have locked the gambling."
prefs = get_preference_file(channel.id)
chance = random.randint(1, 100)
points = get_points(user.id, channel.id)
stake = request.args.get("q")
if not stake:
return "No stake given"
try:
stake = int(stake)
except ValueError:
return "Not a number"
if stake < 1:
return "Stake must be greater than 0"
if stake > points.points:
return f"{user.name} does not have enough {prefs[channel.id]['pname']} to gamble {stake} {prefs[channel.id]['pname']}"
# do the gamble
if chance > 50:
points.add_points(stake)
points.update(user.id, channel.id)
return f"{user.name} won {stake} {prefs[channel.id]['pname']}, and now have {points} {prefs[channel.id]['pname']}"
else:
points.remove_points(stake)
points.update(user.id, channel.id)
return f"{user.name} lost {stake} {prefs[channel.id]['pname']}, and now have {points} {prefs[channel.id]['pname']}"
@app.get("/flip")
def flip():
try:
channel, user = nightbot_parse(request.headers)
except KeyError:
return "Not able to auth"
if channel.id in lock_list:
return "This channel is locked. Moderators have locked the gambling."
call = request.args.get("q")
try:
quantity, call = call.split(" ")
except ValueError:
return "Not a valid call, please use h for heads or t for tails, Format !flip <quantity> <call>"
try:
quantity = int(quantity)
except ValueError:
return "Not a number"
if quantity < 1:
return "Quantity must be greater than 0"
call = call.lower()
if call not in ["h", "head", "heads", "tails", "tail", "t"]:
return "Not a valid call, please use h for heads or t for tails"
if call in ["h", "head", "heads"]:
call = "heads"
else:
call = "tails"
prefs = get_preference_file(channel.id)
points = get_points(user.id, channel.id)
if quantity > points.points:
return f"{user.name} does not have enough {prefs[channel.id]['pname']} to gamble {quantity} {prefs[channel.id]['pname']}"
cpu_call = random.choice(["heads", "tails"])
if cpu_call == call:
points.add_points(quantity)
points.update(user.id, channel.id)
return f"Flipped {cpu_call}, {user.name} won {quantity} {prefs[channel.id]['pname']}, You now have {points.points} {prefs[channel.id]['pname']}"
else:
points.remove_points(quantity)
points.update(user.id, channel.id)
return f"Flipped {cpu_call}, {user.name} lost {quantity} {prefs[channel.id]['pname']}, You now have {points.points} {prefs[channel.id]['pname']}"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5002, debug=True)