-
Notifications
You must be signed in to change notification settings - Fork 1
/
levels.py
532 lines (458 loc) · 23.7 KB
/
levels.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
import random
import time
import discord
from discord.ext import commands
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc
import aiohttp
from io import BytesIO
import markovify
try:
from PIL import Image, ImageFile, ImageOps, ImageDraw, ImageFont
except Exception as error: # this is to avoid heroku being dum dum with pillow dependency
print(error)
import Image
import ImageFile
import ImageOps
import ImageDraw
import ImageFont
with open('priv.txt', 'r') as e:
privdb = e.read()
with open('pub.txt', 'r') as f:
pubdb = f.read()
ImageFile.LOAD_TRUNCATED_IMAGES = True
app = Flask(__name__)
ENV = 'prod'
if ENV == 'dev':
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = privdb
else:
app.debug = False
app.config['SQLALCHEMY_DATABASE_URI'] = pubdb
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
priv_channels = (404841053242523668, 738075158467837962, 761039653951766569, 821798504405663815, 379843937377976321)
txt = open('funny.txt', 'r', encoding='utf-8')
thing = txt.read()
txt.close()
class LevelDatabase(db.Model):
__tablename__ = 'levels'
id = db.Column(db.Integer, primary_key=True)
id_user = db.Column(db.Text)
xp = db.Column(db.Integer, default=0)
level = db.Column(db.Integer, default=0)
last_modified = db.Column(db.Integer, default=1615398960)
xp_lvl = db.Column(db.Integer, default=0)
bg_link = db.Column(db.Text,
default='https://cdn.discordapp.com/attachments/819169940400635908/820605358930001930/bg_empty.png')
def __init__(self, id_user, xp, level, last_modified, xp_lvl, bg_link):
self.id_user = id_user
self.xp = xp
self.level = level
self.last_modified = last_modified # last time xp was added, unix epoch
self.xp_lvl = xp_lvl # xp since last level
self.bg_link = bg_link
async def add_new_user(author):
if db.session.query(LevelDatabase).filter(
LevelDatabase.id_user == str(author)).count() == 0: # if user doesn't appear in the db
data = LevelDatabase(str(author), 0, 0, 1615398960, 0,
'https://cdn.discordapp.com/attachments/819169940400635908/820605358930001930/bg_empty.png')
db.session.add(data)
db.session.commit()
return print(f'Added {author}.')
else:
print(f'{author} already added.')
async def add_xp(author, channel):
channel1 = channel
original = channel.id
if db.session.query(LevelDatabase).filter(
LevelDatabase.id_user == str(author.id)).count() != 0: # if user is in database
user_row = db.session.query(LevelDatabase).filter_by(id_user=str(author.id)).first()
current = int(time.time()) # current time
if current - user_row.last_modified < 60: # if current time is less than a minute ahead of last time xp was added, do nothing
user_row.last_modified = current
db.session.commit()
return
else:
num = random.randint(15, 25) # add random xp between 15 and 25
user_row.xp_lvl += num
user_row.xp += num
user_row.last_modified = current # update time for xp
lvl = user_row.level
lvl_calc = 5 * (lvl ** 2) + (50 * lvl) + 100 - user_row.xp_lvl # how much xp needed for the next level
if lvl_calc <= 0:
user_row.level += 1
lvl += 1
user_row.xp_lvl = 0 + abs(
lvl_calc) # level up, reset the xp counter and add what remained from the last level
descr = f'{author.mention} has leveled up to level **{lvl}**, chuckle.'
if lvl == 1:
role = discord.utils.get(author.guild.roles, name="The Fabricated")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
print(channel1.id, channel.id)
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
elif lvl == 5:
role = discord.utils.get(author.guild.roles, name="The Undying")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
elif lvl == 11:
role = discord.utils.get(author.guild.roles, name="The Condemned")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
elif lvl == 17:
role = discord.utils.get(author.guild.roles, name="The Frightening")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
elif lvl == 23:
role = discord.utils.get(author.guild.roles, name="The Unholy")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
elif lvl == 31:
role = discord.utils.get(author.guild.roles, name="The Forbidden")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
elif lvl == 41:
role = discord.utils.get(author.guild.roles, name="The Hurtful")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
elif lvl == 53:
role = discord.utils.get(author.guild.roles, name="The Hatred")
if not role:
channel1.id = 343323003288813569
await channel1.send("I couldn't find the role :sad:")
else:
try:
await author.add_roles(role)
descr += f"\nYou have also gained the cursed role of: {role.name}"
except discord.Forbidden:
channel1.id = 343323003288813569
await channel1.send(f"I would have added the role {role.name} to {author.name}, but I lack the permission to do so :sadsadsad:")
embed = discord.Embed(title='',
description=descr,
color=0xff005a)
if channel.id not in priv_channels:
channel.id = original
await channel.send(embed=embed)
else:
channel.id = 343323003288813569
await channel.send(embed=embed)
db.session.commit()
return
else:
await add_new_user(author.id)
print(f'{author} not in DB, so I added him.')
async def check_level(author):
if db.session.query(LevelDatabase).filter(LevelDatabase.id_user == str(author)).count() != 0:
user_row = db.session.query(LevelDatabase).filter_by(id_user=str(author)).first()
lvl_tot = 5 * (user_row.level ** 2) + (50 * user_row.level) + 100
return user_row.level, user_row.xp, user_row.xp_lvl, lvl_tot, user_row.bg_link
else:
return -1
async def get_all(ctx, start, end):
err = False
stats = {}
list_db = db.session.query(LevelDatabase).order_by(desc(LevelDatabase.xp))[start:end]
pos = start + 1
if ENV == 'dev':
for ids in list_db:
# print(await ctx.guild.fetch_member(ids.id_user)) # for final deploy
stats[ids.id_user] = f'Total XP: {ids.xp} | Level: {ids.level} | Position: {pos}°\n'
pos += 1
else:
for ids in list_db:
# noinspection PyBroadException
try:
stats[await ctx.guild.fetch_member(
ids.id_user)] = f'Total XP: {ids.xp} | Level: {ids.level} | Position: {pos}\n'
except Exception:
err = True
stats[ids.id_user] = f'Total XP: {ids.xp} | Level: {ids.level} | Position: {pos}\n'
pos += 1
if err:
print('There was an error making the lb, probably a user in the page isn\'t in the server')
return stats
async def change_bg(user_id, url):
if url == 'none':
url = 'https://cdn.discordapp.com/attachments/819169940400635908/820605358930001930/bg_empty.png'
url_db = db.session.query(LevelDatabase).filter_by(id_user=str(user_id)).first()
url_db.bg_link = url
db.session.commit()
return '1'
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}) as r:
pic = BytesIO(await r.read())
Image.open(pic).convert('RGBA').crop((0, 0, 934, 282))
except Exception as error1:
return str(error1)
url_db = db.session.query(LevelDatabase).filter_by(id_user=str(user_id)).first()
url_db.bg_link = url
db.session.commit()
return '1'
def add(id_user, xp, level): # XP TOT - XP PREV LEVELS
if db.session.query(LevelDatabase).filter(
LevelDatabase.id_user == str(id_user)).count() == 0: # if user doesn't appear in the db
i = level - 1
xp_lvl = 0
while i >= 0:
xp_lvl += 5 * (i ** 2) + (50 * i) + 100
i -= 1
xp_lvl = xp - xp_lvl
data = LevelDatabase(str(id_user), xp, level, 1615398960, xp_lvl,
'https://cdn.discordapp.com/attachments/819169940400635908/820605358930001930/bg_empty.png')
db.session.add(data)
db.session.commit()
return print(f'Added {id_user}.')
else:
user_row = db.session.query(LevelDatabase).filter_by(id_user=str(id_user)).first()
user_row.xp = xp
user_row.level = level
i = level - 1
xp_lvl = 0
while i >= 0:
xp_lvl += 5 * (i ** 2) + (50 * i) + 100
i -= 1
xp_lvl = xp - xp_lvl
user_row.xp_lvl = xp_lvl
db.session.commit()
print(f'{id_user} updated info')
def round_corner(radius, fill):
"""Draw a round corner"""
corner = Image.new('RGB', (radius, radius), (32, 41, 47, 0))
draw = ImageDraw.Draw(corner)
draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill)
return corner
def round_rectangle(size, radius, fill):
"""Draw a rounded rectangle"""
width, height = size
rectangle = Image.new('RGB', size, fill)
corner = round_corner(radius, fill)
rectangle.paste(corner, (0, 0))
rectangle.paste(corner.rotate(90), (0, height - radius)) # Rotate the corner and paste it
rectangle.paste(corner.rotate(180), (width - radius, height - radius))
rectangle.paste(corner.rotate(270), (width - radius, 0))
return rectangle
add_users = (544556502573121554, 259280989715562496)
class Level(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
await add_xp(message.author, message.channel)
if message.channel.id == 494549477407850526 and message.author.id != 787735815575961610 and message.author.id != 492893838575271936:
if random.randint(0, 100) > 50:
markov = markovify.NewlineText(thing)
try:
funny = markov.make_sentence(tries=200)
await message.channel.send(funny)
except discord.errors.HTTPException:
print('sad')
@commands.Cog.listener()
async def on_member_join(self, member):
if not member.bot:
await add_new_user(member.id)
@commands.command(aliases=['bg'])
async def background(self, ctx, url='none'):
with ctx.typing():
value = await change_bg(ctx.author.id, url)
if value != '1':
return await ctx.reply(
f"**Fool.**\nCouldn't get an image from the link, please specify a valid link to an image to set as background for your rank card.\n```{value}```",
mention_author=False)
else:
return await ctx.reply(
'Changed background image <:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:737675219937787974>\n(Use .bg to set default bg)',
mention_author=False)
@commands.command(aliases=['haelp', 'commands'])
async def help(self, ctx):
help_em = discord.Embed(
title='command the onion',
color=0xff005a
)
help_em.add_field(name='.rank (User ID/tag [optional])', value='Current rank shown in a convenient card™')
help_em.add_field(name='.lb/.leaderboard/.levels (Page #, default is 1)', value='Leaderboard of powerful flesh ridden beings', inline=False)
help_em.add_field(name='.background/.bg (image link)', value='Change the background of your .rank card, if link isn\'t specified it restores the default (has to be link to an image and not a file)', inline=False)
help_em.add_field(name='.mk', value='Generate wacky and unpredictable sentences, Reginald will watch from the heavens :place_of_worship:', inline=False)
help_em.add_field(name='.inspire/.inspiro', value='You are about to turn into a silly member of the species homo sapiens. That\'s right')
help_em.set_thumbnail(url='https://cdn.discordapp.com/attachments/819169940400635908/825316562633359390/d.png')
help_em.set_footer(text='remember to onion your lawn')
await ctx.reply(embed=help_em, mention_author=False)
@commands.command()
async def mk(self, ctx):
markov = markovify.NewlineText(thing)
try:
await ctx.send(markov.make_sentence(tries=200))
except discord.errors.HTTPException:
print('sad')
return
@commands.command()
async def add(self, ctx, id_user, xp, lvl):
if ctx.author.id not in add_users:
return await ctx.reply('You can\'t run this command!', mention_author=False)
try:
await ctx.guild.fetch_member(id_user)
except discord.errors.NotFound:
return await ctx.reply('User ID error, user not in guild?', mention_author=False)
else:
try:
add(id_user, int(xp), int(lvl))
return await ctx.reply(f'Added {id_user}!', mention_author=False)
except Exception as add_err:
return await ctx.reply(f'Add function error\n{add_err}', mention_author=False)
@commands.command(aliases=['leaderboard', 'levels'])
async def lb(self, ctx, page: int = 1):
if not page >= 1:
return await ctx.reply(f'There is no such thing as page {page}.', mention_author=False)
with ctx.typing():
err = False
added = False
page -= 1
list_db = db.session.query(LevelDatabase).order_by(desc(LevelDatabase.xp))[page * 21:(page * 21) + 21]
pos = (page * 21) + 1
lb_emb = discord.Embed(
title="r/surrealmemes Server Leaderboard",
description=f"Page {page + 1} | Positions: {(page * 21) + 1} to {(page * 21) + 21}",
color=0xff005a
)
for ids in list_db:
try:
lb_emb.add_field(name=f'{pos} | {str(await ctx.guild.fetch_member(ids.id_user))[:-5]}',
value=f"Total XP: {ids.xp} | Level: {ids.level}")
added = True
except discord.errors.NotFound:
lb_emb.add_field(name=f'{pos} | {ids.id_user}', value=f"Total XP: {ids.xp} | Level: {ids.level}")
added = True
err = True
pos += 1
if not added:
return await ctx.reply(f'There is no such thing as page {page + 1}.', mention_author=False)
if err:
print('There was an error making the lb, probably a user in the page isn\'t in the server')
return await ctx.reply(embed=lb_emb, mention_author=False)
@commands.command()
async def rank(self, ctx, user='none'):
if user == 'none':
user = str(ctx.author.id)
if len(ctx.message.mentions) == 0:
if not user.isnumeric():
return await ctx.reply('Specify a user, or the user will specify you.', mention_author=False)
try:
await ctx.guild.fetch_member(user)
except discord.errors.NotFound:
return await ctx.reply('Specify a user, or the user will specify you\n(Invalid User ID).',
mention_author=False)
else:
user = ctx.message.mentions[0].id
level = await check_level(user)
try:
if level[0] >= 0:
with ctx.typing():
member = await ctx.guild.fetch_member(user)
# mask for circle crop
await member.avatar_url.save("pics/avatar.png")
mask = Image.new('L', (200, 200), 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + (200, 200), fill=255)
# import bg from link and avatar
overlay = Image.open("pics/overlay.png").convert('RGBA')
img = Image.open("pics/avatar.png").convert('RGBA').resize((200, 200), resample=0)
try:
async with aiohttp.ClientSession() as session1:
async with session1.get(level[4], headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}) as r:
pic = BytesIO(await r.read())
bg = Image.open(pic).convert('RGBA').resize((934, 282))
except Exception as err:
await ctx.reply(
f'There was an error while retrieving/processing the background image, using default image\n```{err}\nWelcome to the Cloud Room.```',
mention_author=False)
bg = Image.open('pics/bg_empty.png').convert('RGBA')
# fit overlay on bg
bg.paste(overlay, (0, 0), overlay)
# fit mask on avatar
avatar = ImageOps.fit(img, mask.size, centering=(0.5, 0.5))
avatar.putalpha(mask)
# paste avatar on bg
bg.paste(avatar, (36, 43), avatar)
# add text to it
bg1 = ImageDraw.Draw(bg)
font = ImageFont.truetype('pics/sansb.ttf', 45)
bg1.text((310, 132), f'Level: {level[0]} | Total XP: {level[1]}', font=font,
fill=(40, 40, 40)) # text shadow
bg1.text((312, 130), f'Level: {level[0]} | Total XP: {level[1]}', font=font,
fill=(0, 0, 0)) # actual text
# level meter
perc = round(level[2] / level[3], 2)
thing = round_rectangle((int(563 * perc), 20), 10, (37, 150, 190, 0))
bg.paste(thing, (325, 187))
bg.save("pics/big.png")
file = discord.File('pics/big.png')
await ctx.reply(file=file, mention_author=False)
else:
await ctx.reply('There was an error! The sky has now turned a funky color.', mention_author=False)
except Exception as err:
print(err)
return await ctx.reply(
'There was an error! (Maybe user isn\'t in the server?) The sky has now turned a funky color.',
mention_author=False)
def setup(client):
client.add_cog(Level(client))
if __name__ == '__main__':
app.run()