-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
286 lines (262 loc) · 8.45 KB
/
functions.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
import spotipy
import os
from spotipy.oauth2 import SpotifyClientCredentials
import lyricsgenius
import random
from flask import session
from string import printable
from html import escape as esc
import pymongo
import dns
import datetime
from PIL import Image
import requests
from io import BytesIO
from werkzeug.security import generate_password_hash, check_password_hash
os.system("pip install profanity")
from profanity import profanity
cid = os.getenv("SPOTIPY_CLIENT_ID")
secret = os.getenv("SPOTIPY_CLIENT_SECRET")
client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
geniustoken = os.getenv("GENIUS_ACCESS_TOKEN")
genius = lyricsgenius.Genius(geniustoken)
clientmongo = pymongo.MongoClient(os.getenv("mongo_client"))
usersdb = clientmongo.Users
profilescol = usersdb.Profiles
def getsongnames(artistname):
results = sp.search(q='artist:' + artistname, type='artist')
songnames = []
items = results['artists']['items']
if len(items) > 0:
artist = items[0]
uri = artist['uri']
albums = sp.artist_albums(artist_id=uri)
for album in albums['items']:
if album['total_tracks'] == 1:
if "remix" not in album['name'].lower() and "acoustic" not in album['name'].lower() and "edit" not in album['name'].lower():
songnames.append(album['name'])
else:
albumsongs = sp.album_tracks(album['uri'])
for track in albumsongs['items']:
if "remix" not in track['name'].lower() and "acoustic" not in track['name'].lower() and "edit" not in track['name'].lower():
songnames.append(track['name'])
return songnames
else:
return False
def searchartist(artistname):
results = sp.search(q='artist:' + artistname, type='artist')
items = results['artists']['items']
if len(items) == 0:
return False
else:
artist = items[0]
return artist['name']
def getlyrics(songname, artistname):
song = genius.search_song(songname, artistname)
return song
def getrandomline(artistname):
names = getsongnames(artistname)
song = random.choice(names)
lyrics = getlyrics(song, artistname)
while lyrics == None:
song = random.choice(names)
lyrics = getlyrics(song, artistname)
chorus = lyrics.lyrics
chorus = chorus.split("\n")
chorus = [ x for x in chorus if x != ""]
realchorus = []
for thelyric in chorus:
if " " in thelyric:
if "embed" not in thelyric.lower() and "verse" not in thelyric.lower() and "chorus" not in thelyric.lower() and "bridge" not in thelyric.lower() and "refrain" not in thelyric.lower() and "outro" not in thelyric.lower() and "intro" not in thelyric.lower():
realchorus.append(profanity.censor(thelyric))
line = random.choice(realchorus)
return song, line
def getrandomalbumcover(artistname):
results = sp.search(q='artist:' + artistname, type='artist')
albumcovers = []
albumnames = []
items = results['artists']['items']
if len(items) > 0:
artist = items[0]
uri = artist['uri']
albums = sp.artist_albums(artist_id=uri)
for album in albums['items']:
if album['images'][1]['url'] != None:
albumcovers.append(album['images'][1]['url'])
albumnames.append(album['name'])
albumcover = random.choice(albumcovers)
index = albumcovers.index(albumcover)
albumname = albumnames[index]
return albumcover, albumname
else:
return False
def addcookie(key, value):
session[key] = value
def delcookies():
session.clear()
def getcookie(key):
try:
if (x := session.get(key)):
return x
else:
return False
except:
return False
def checkusernamealready(username):
myquery = { "Username": username }
mydoc = profilescol.find(myquery)
for x in mydoc:
return True
return False
def makeaccount(username, password, passwordagain):
if len(username) > 25:
return "Your username cannot have more than 25 letters!"
if len(username) < 2:
return "You have to have more than 2 letters in your username!"
if set(username).difference(printable) or esc(username) != username:
return "Your username cannot contain any special characters!"
if username != username.lower():
return "Your username has to be all lowercase!"
if checkusernamealready(username) == True:
return "A user already has this username! Try another one."
if password != passwordagain:
return "The two passwords don't match!"
if len(password) > 25:
return "Your password cannot have more than 25 letters!"
if len(password) < 2:
return "You have to have more than 2 letters in your password!"
if set(password).difference(printable):
return "Your password cannot contain any special characters!"
passhash = generate_password_hash(password)
document = [{
"Username": username,
"Password": passhash,
"Created": str(datetime.datetime.now()),
"Money": 0,
"XP": 0,
"SL": {},
"AC": {}
}]
profilescol.insert_many(document)
return True
def gethashpass(username):
myquery = { "Username": username }
mydoc = profilescol.find(myquery)
for x in mydoc:
return x['Password']
return False
def getuser(username):
myquery = { "Username": username }
mydoc = profilescol.find(myquery)
for x in mydoc:
if x.get("Deleted", None) == None:
return x
return False
return False
def addmoney(username, amount):
user = getuser(username)
money = user['Money']
money = money + amount
del user['Money']
user['Money'] = money
profilescol.delete_one({"_id": user['_id']})
profilescol.insert_many([user])
def addxp(username, amount):
user = getuser(username)
money = user['XP']
money = money + amount
del user['XP']
user['XP'] = money
profilescol.delete_one({"_id": user['_id']})
profilescol.insert_many([user])
def changesonglyricscore(username, score, artist):
user = getuser(username)
songlyric = user['SL']
userscore = songlyric.get(artist.lower(), False)
if userscore == False:
songlyric[artist.lower()] = score
del user['SL']
user['SL'] = songlyric
profilescol.delete_one({"_id": user['_id']})
profilescol.insert_many([user])
else:
if score > userscore:
del songlyric[artist.lower()]
songlyric[artist.lower()] = score
del user['SL']
user['SL'] = songlyric
profilescol.delete_one({"_id": user['_id']})
profilescol.insert_many([user])
return True
def changealbumcoverscore(username, score, artist):
user = getuser(username)
songlyric = user['AC']
userscore = songlyric.get(artist.lower(), False)
if userscore == False:
songlyric[artist.lower()] = score
del user['AC']
user['AC'] = songlyric
profilescol.delete_one({"_id": user['_id']})
profilescol.insert_many([user])
else:
if score > userscore:
del songlyric[artist.lower()]
songlyric[artist.lower()] = score
del user['AC']
user['AC'] = songlyric
profilescol.delete_one({"_id": user['_id']})
profilescol.insert_many([user])
return True
def xpleaderboard():
mydoc = profilescol.find().sort("XP", -1).limit(10)
lb = []
for x in mydoc:
del x['Password']
lb.append(x)
return lb
def moneyleaderboard():
mydoc = profilescol.find().sort("Money", -1).limit(10)
lb = []
for x in mydoc:
del x['Password']
lb.append(x)
return lb
def getalbumnames(artistname):
results = sp.search(q='artist:' + artistname, type='artist')
albumnames = []
items = results['artists']['items']
if len(items) > 0:
artist = items[0]
uri = artist['uri']
albums = sp.artist_albums(artist_id=uri)
for album in albums['items']:
if album['images'][1]['url'] != None:
albumnames.append(album['name'].lower())
return albumnames
def getalbumcover(albumname, artistname):
results = sp.search(q='artist:' + artistname, type='artist')
items = results['artists']['items']
if len(items) > 0:
artist = items[0]
uri = artist['uri']
albums = sp.artist_albums(artist_id=uri)
for album in albums['items']:
if album['images'][1]['url'] != None:
if album['name'].lower() == albumname.lower():
return album['images'][1]['url']
def coverimagetobyte(url):
response = requests.get(url)
img = Image.open(BytesIO(response.content))
buffer = BytesIO()
img.save(buffer, format='png', quality=75)
byte_im = buffer.getvalue()
return byte_im
def removebrackets(name):
start = name.find('(')
end = name.find(')')
name = list(name)
for char in range(end-start+1):
del name[start]
name = "".join(name)
return name