repl.it
@mat1/

Stonks Bot

Python

No description

fork
loading
Files
  • main.py
  • blackmarket
  • templates
  • website
  • betterbot.py
  • database.py
  • giveaway.py
  • investing.py
  • utils.py
  • website.py
  • Packager files
  • poetry.lock
  • pyproject.toml
  • requirements.txt
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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
import discord
from discord.ext import commands
from database import db
import website
import os
import asyncio
from utils import display_money, check_fraction, find_date
from contextlib import redirect_stdout
import io
import investing
import giveaway
from operator import itemgetter
from betterbot import BetterBot
import time
import traceback
#to reactivate bot type this in the command line: 
#pip install discord aiohttp motor dnspython jinja2
#then press start or restart.
#import blackmarket.main


print('Starting')

bot = commands.Bot(
	command_prefix='$',
	case_insensitive=True
)

betterbot = BetterBot(
	prefix='$'
)

bot.remove_command('help')

db.bot = bot
investing.bot = bot
giveaway.bot = bot

main_channel = None


async def coming_soon(ctx, *_, **__):
	await ctx.send('Coming soon...')


def dev_only(func):
	if dev:
		return func
	else:
		return coming_soon


def execute(_code, loc):  # Executes code asynchronously
	_code = _code.replace('\n', '\n ')
	globs = globals()
	globs.update(loc)
	exec(
		'async def __ex():\n ' + _code,
		globs
	)
	return globs['__ex']()


def check_user_id(ctx, arg):
	try:
		member = ctx.guild.get_member(int(arg))
		if member is not None:
			return member
	except ValueError:
		pass


def check_mention(ctx, arg):
	if arg.startswith('<@') and arg[-1] == '>':
		if arg[2] == '!':
			user_id = arg[3:-1]
		else:
			user_id = arg[2:-1]
		try:
			member = ctx.guild.get_member(int(user_id))
			if member is not None:
				return member
		except ValueError:
			pass


def check_name_with_discrim(ctx, arg):
	member = discord.utils.find(
		lambda m: str(m).lower() == arg.lower(),
		get_channel_members(ctx.channel.id)
	)
	return member


def check_name_without_discrim(ctx, arg):
	member = discord.utils.find(
		lambda m: m.name.lower == arg.lower(),
		get_channel_members(ctx.channel.id)
	)
	return member


def check_nickname(ctx, arg):
	member = discord.utils.find(
		lambda m: m.display_name.lower() == arg.lower(),
		get_channel_members(ctx.channel.id)
	)
	return member


def check_name_starts_with(ctx, arg):
	member = discord.utils.find(
		lambda m: m.name.lower().startswith(arg.lower()),
		get_channel_members(ctx.channel.id)
	)
	return member


def check_nickname_starts_with(ctx, arg):
	member = discord.utils.find(
		lambda m: m.display_name.lower().startswith(arg.lower()),
		get_channel_members(ctx.channel.id)
	)
	return member


def check_name_contains(ctx, arg):
	member = discord.utils.find(
		lambda m: arg.lower() in m.name.lower(),
		get_channel_members(ctx.channel.id)
	)
	return member


def check_nickname_contains(ctx, arg):
	member = discord.utils.find(
		lambda m: arg.lower() in m.display_name.lower(),
		get_channel_members(ctx.channel.id)
	)
	return member


class Member(commands.Converter):
	async def convert(self, ctx, arg):
		if arg[0] == '@':
			arg = arg[1:]
		# Check user id
		member = check_user_id(ctx, arg)
		if member is not None:
			return member

		# Check mention
		member = check_mention(ctx, arg)
		if member is not None:
			return member

		# Name + discrim
		member = check_name_with_discrim(ctx, arg)
		if member is not None:
			return member

		# Name
		member = check_name_with_discrim(ctx, arg)
		if member is not None:
			return member

		# Nickname
		member = check_nickname(ctx, arg)
		if member is not None:
			return member

		# Name starts with
		member = check_name_starts_with(ctx, arg)
		if member is not None:
			return member

		# Nickname starts with
		member = check_nickname_starts_with(ctx, arg)
		if member is not None:
			return member

		# Name contains
		member = check_name_contains(ctx, arg)
		if member is not None:
			return member

		# Nickname contains
		member = check_nickname_contains(ctx, arg)
		if member is not None:
			return member





@bot.event
async def on_message(message):  # Taking from charity
	if message.channel.id == 618957055364956182:
		charity_amount = await db.get_charity_amount()
		if charity_amount >= 500:
			await db.change_charity(-500)
			await db.change_balance(message.author.id, 500)
			await message.add_reaction('👍')
		else:
			await message.add_reaction('❌')
	else:
		try:
			await betterbot.process_commands(message)
		except investing.InvestingException as e:
			await on_investing_exception(e, message)
		except Exception as e:
			error_channel = bot.get_channel(
				629827397163941898 if dev else 629830358241771539
			)
			tb = '\n'.join(traceback.format_tb(e.__traceback__))
			await error_channel.send(
				f'https://discordapp.com/channels/{message.guild.id}/'
				f'{message.channel.id}/{message.id}\n'
				'```py\n'
				f'{tb}\n'
				f'{type(e).__name__}: {e}'
				'```'
			)
			await message.channel.send(f'{type(e)} {e}')
		except betterbot.NothingFound:
			await message.channel.send(
				'Invalid syntax.'
			)
		except BaseException as e:
			await message.channel.send(
				f'if this happens im sad but at least i have an error: {type(e)} {e}'
			)
		except:
			await message.channel.send(
				'this should never ever ever happen and if it does then im sad'
			)


@bot.event
async def on_command_error(ctx, error):
	if isinstance(error, commands.errors.CommandNotFound):
		pass


async def on_investing_exception(e, message):
	error_message = str(e)
	if not error_message:
		if hasattr(e, 'message'):
			error_message = e.message
		else:
			error_message = type(e).__name__
	await message.channel.send(
		embed=discord.Embed(
			description=error_message,
			color=discord.Color.red()
		)
	)


async def delete_tutorial_channels(guild):
	print('deleting tutorial channels and roles...')
	for channel in guild.channels:
		if channel.name == 'tutorial':
			await channel.delete(reason='Bot restarted')

	tutorial_role = guild.get_role(629460687336374283)
	for member in guild.members:
		if tutorial_role in member.roles:
			await member.remove_roles(tutorial_role)
	print('deleted tutorial channels and roles')


async def on_ready_main():
	leaderboard, in_circulation = await db.get_leaderboard_data()

	leaderboard_channel = bot.get_channel(617835287103668228)
	leaderboard_msg = await leaderboard_channel.fetch_message(617836970571202562)
	leaderboard_before = None

	stonk_exchange_server = bot.get_guild(617444598515499087)
	over_10k_role = stonk_exchange_server.get_role(617929768071069707)
	over_100k_role = stonk_exchange_server.get_role(618124419402956823)
	while True:
		leaderboard, in_circulation = await db.get_leaderboard_data()
		if leaderboard != leaderboard_before:
			leaderboard_embed = await create_leaderboard_embed(
				leaderboard,
				in_circulation
			)
			await leaderboard_msg.edit(embed=leaderboard_embed)
		await asyncio.sleep(1.1)
		leaderboard_before = leaderboard
		# ratelimit is 5/5 but i made it 1.1 just in case so it never hits it

		# Update the people that need their roles added
		for i in list(db.over_10k_queue):
			# print('adding', i, 'to 10k')
			the_member = stonk_exchange_server.get_member(i)
			if the_member is not None:
				await the_member.add_roles(over_10k_role)
			db.over_10k_queue.remove(i)

		for i in list(db.under_10k_queue):
			# print('removing', i, 'from 10k')
			the_member = stonk_exchange_server.get_member(i)
			if the_member is not None:
				await the_member.remove_roles(over_10k_role)
			db.under_10k_queue.remove(i)

		for i in list(db.over_100k_queue):
			the_member = stonk_exchange_server.get_member(i)
			if the_member is not None:
				await the_member.add_roles(over_100k_role)
			db.over_100k_queue.remove(i)

		for i in list(db.under_100k_queue):
			the_member = stonk_exchange_server.get_member(i)
			if the_member is not None:
				await the_member.remove_roles(over_100k_role)
			db.under_100k_queue.remove(i)


dev = os.getenv('dev') == 'true'



def get_channel_members(channel_id):
	return bot.get_channel(channel_id).members


@bot.event
async def on_ready():
	print('Ready')
	print(bot.guilds)

	game = discord.Activity(
		name='The Stonk Market',
		type=discord.ActivityType.watching
	)
	await bot.change_presence(status=discord.Status.online, activity=game)

	await db.on_ready()

	website.start_server()

	stonk_exchange_server = bot.get_guild(617444598515499087)

	await delete_tutorial_channels(stonk_exchange_server)

	if not dev:
		asyncio.ensure_future(giveaway.on_ready())
		await on_ready_main()
		#asyncio.ensure_future(blackmarket.main.start())


async def sell_all(user_id):
	for i in await db.get_all_investments(user_id):
		user, invested_amount, invested_percent = i
		try:
			await investing.sell(user_id, user, 'all')
		except:
			pass


@betterbot.command(name='begone')
@commands.has_permissions(administrator=True)
async def _begone(ctx, user: int):
	await sell_all(user)
	await db.reset_balance(user)
	await ctx.send('BEGONE THOT!')


@betterbot.command(name='exec')
@commands.has_permissions(administrator=True)
async def _exec(ctx, *_):
	f = io.StringIO()
	with redirect_stdout(f):
		command = ctx.message.content.split(None, 1)[1]
		await execute(command, locals())
	out = f.getvalue()
	if out == '':
		out = 'No output.'
	await ctx.send(
		embed=discord.Embed(
			title='Unsafe Eval',
			description=out
		)
	)

@betterbot.command(name='cheat')
@commands.has_permissions(administrator=True)
async def _moneys(
 	ctx,
 	money_amount,
	  	user: Member = None
 ):
    if user is None:
        user = ctx.author

    money_amount = check_fraction(money_amount, money_amount)
    await db.change_balance(user.id, money_amount)
    return ctx.send('aight cheater')


@betterbot.command(name='addcharity')
@commands.has_permissions(administrator=True)
async def _add_charity(
	ctx,
	money_amount
):
	money_amount = check_fraction(money_amount, money_amount)
	await db.change_charity(money_amount)
	await ctx.send('ok')


@betterbot.command(name='NUKE')  # Clear the data of all users
@commands.has_permissions(administrator=True)
async def _nuke_economy(ctx):
	all_user_ids = list(await db.get_all_user_balances())
	msg = await ctx.send('nuking everything...')
	for user_id in all_user_ids:
		await db.new_user(user_id)
	await msg.edit(content=':fire: done :fire:')



@betterbot.command(name='removeuser')
@commands.has_permissions(administrator=True)
async def _remove_user(ctx, user_id:int):
	await delete_member(user_id)
	await ctx.send('ok')



@betterbot.command(name='lottery')
@dev_only
async def _lottery(ctx, *_):  # Manually starts a lottery
	message_text = ctx.message.content.split(None, 1)[1]
	await giveaway.create_new_lottery(message_text)


@betterbot.command(name='ping')
async def _ping(ctx):  # A ping.
	ping = int(bot.latency * 1000)
	await ctx.send(f'Pong! **{ping}ms**')


def create_balance_embed(balance, net_worth, user_mention, is_self):
	if balance >= 0:
		color = discord.Color.green()
	else:
		color = discord.Color.red()

	money_display = display_money(balance)

	if is_self:
		embed = discord.Embed(
			description=f'You have **{money_display}**',
			color=color
		)
	else:
		embed = discord.Embed(
			description=f'{user_mention} has **{money_display}**',
			color=color
		)

	if net_worth != balance:
		embed.set_footer(text=f'Net worth: {display_money(net_worth)}')
	return embed


@betterbot.command(name='balance', aliases=('bal', ''))
async def _balance(ctx, user: Member = 'self'):
	if user == 'self':
		user = ctx.author
	elif user is None:
		raise investing.InvalidUser('Invalid user.')
	bal = await db.get_balance(user.id)
	net_worth = await db.get_net_worth(user.id, alternate=True)

	embed = create_balance_embed(
		balance=bal,
		net_worth=net_worth,
		user_mention=user.mention,
		is_self=user == ctx.author
	)

	await ctx.send(embed=embed)


def create_buy_embed(percent, user_mention):
	if percent >= 1:
		displayed_percent = 100
	else:
		displayed_percent = round(percent * 100, 3)
	return discord.Embed(
		description=f"You've bought {displayed_percent}% of {user_mention}"
	)


@betterbot.command(name='buy', aliases=('invest', 'b'))
async def _buy(
	ctx,
	user: Member = None,
	amount='all'
):
	percent = await investing.buy(ctx.author.id, user, amount)

	embed = create_buy_embed(percent, user.mention)

	await ctx.send(embed=embed)


@betterbot.command(name='profit', aliases=('profits',))
async def _profit(
	ctx,
	user: Member = None
):
	profit_percent = await investing.get_sell_profit_percent(ctx.author.id, user)
	percent_display = str(round(profit_percent * 100, 3)) + '%'
	return await ctx.send(percent_display)


def create_sell_embed(profit_percent, amount):
	if profit_percent == 1:
		color = discord.Color.greyple()

	elif profit_percent > 2:
		color = discord.Color.green()
	elif profit_percent > 1:
		color = discord.Color.dark_green()

	elif profit_percent < 2:
		color = discord.Color.red()
	elif profit_percent < 1:
		color = discord.Color.dark_red()

	profit_percent_display = round(profit_percent * 100, 3)

	return discord.Embed(
		description=f'Done! You got **{display_money(amount)}** back. '
		f'({profit_percent_display}%)',
		color=color
	)

@betterbot.command(name='sell', aliases=('devest', 's', 'uninvest'))
async def _sell(
	ctx,
	user: Member = None,
	amount='all'
):
	profit_percent, amount, other_balance = await investing.sell(
		ctx.author.id,
		user,
		amount
	)

	embed = create_sell_embed(profit_percent, amount)

	await ctx.send(embed=embed)

	if other_balance <= amount:
		await ctx.send(embed=discord.Embed(
			description=f'Because of your greediness, '
			'{user.mention} has gone bankrupt.',
			color=discord.Color.red()
		))
		await user.send(embed=discord.Embed(
			description=f'You have gone bankrupt!',
			color=discord.Color.red()
		))
	return

# 	invested_data = await db.get_invested_amount(user.id, ctx.author.id)
# 	if invested_data is None or invested_data.get('percent', 0) == 0:
# 		return await ctx.send(embed=discord.Embed(
# 			description="You haven't invested in this user yet!"
# 		))

# 	other_balance = await db.get_balance(user.id)

# 	if other_balance < 0:
# 		# await give_cash_if_broke(user)
# 		return await ctx.send(embed=discord.Embed(
# 			description="This user has gone bankrupt "
# 			"so you can't get your money back :(",
# 			color=discord.Color.dark_red()
# 		))

# 	owned_amount = int(invested_data['percent'] * other_balance)

# 	print('SELL CHECK FRACTION', invested_data['percent'], amount)
# 	amount = check_fraction(owned_amount, amount)
# 	print('SELL CHECK FRACTION2', amount)

# 	percent = amount / other_balance

# 	print('PERCENT', percent, other_balance)

# 	if amount > other_balance:
# 		amount = other_balance


# 	print('AMOUNT', amount)
# 	print('OWNED AMOUNT', owned_amount)

# 	if amount == 0:
# 		return await ctx.send(embed=discord.Embed(
# 			description="You haven't invested in this user enough!"
# 		))

# 	if amount > owned_amount:
# 		display_percent = round(invested_data['percent'] * 100, 3)
# 		return await ctx.send(embed=discord.Embed(
# 			description=f'You only own {display_percent}%\
# (**{display_money(owned_amount)}**) of this user!'
# 		))

# 	profit_percent = await db.devest_in_user(user.id, ctx.author.id, percent)

# 	profit_percent = round(profit_percent, 15)

# 	print('PROFIT_PERCENT', profit_percent)

# 	await db.change_balance(user.id, -amount)
# 	await db.change_balance(ctx.author.id, amount)

# 	if profit_percent == 1:
# 		color = discord.Color.greyple()

# 	elif profit_percent > 2:
# 		color = discord.Color.green()
# 	elif profit_percent > 1:
# 		color = discord.Color.dark_green()

# 	elif profit_percent < 2:
# 		color = discord.Color.red()
# 	elif profit_percent < 1:
# 		color = discord.Color.dark_red()

# 	profit_percent_display = round(profit_percent * 100, 3)

# 	await ctx.send(embed=discord.Embed(
# 		description=f'Done! You got **{display_money(amount)}** back. '
# 		f'({profit_percent_display}%)',
# 		color=color
# 	))
 
# 	if other_balance <= amount:
# 		await ctx.send(embed=discord.Embed(
# 			description=f'Because of your greediness, '
# 			'{user.mention} has gone bankrupt.',
# 			color=discord.Color.red()
# 		))
# 		await user.send(embed=discord.Embed(
# 			description=f'You have gone bankrupt!',
# 			color=discord.Color.red()
# 		))


@betterbot.command(name='donate', aliases=('give',))
async def _donate(
	ctx,
	user: Member = None,
	amount=None
):
	if amount is None:
		raise investing.InvalidAmount('Please enter the amount of money you would like to donate.')
	my_money = await db.get_balance(ctx.author.id)
	amount = check_fraction(my_money, amount)
	try:
		await investing.donate(ctx.author.id, user, amount)
	except investing.InvestingException as e:
		return await ctx.send(str(e))

	return await ctx.send(embed=discord.Embed(
		description=f'Donated **{display_money(amount)}** to {user.mention}'
	))


async def create_leaderboard_embed(data=None, in_circulation=None, maximum=20):
	if data is None:
		data, in_circulation = await db.get_leaderboard_data()
	leaderboard_display = []
	for i, user_data in enumerate(data[:maximum]):
		display_name = user_data.get('display_name')
		money_display = display_money(user_data.get('worth'))
		line = f'{display_name} - **{money_display}**'
		leaderboard_display.append(f'{i + 1}) {line}')
	return discord.Embed(
		description='\n'.join(leaderboard_display),
		title=f'{display_money(in_circulation)} in circulation'
	)


@betterbot.command(name='board', aliases=('leaders', 'leaderboard', 'l'))
async def _board(ctx):
	embed = await create_leaderboard_embed()
	return await ctx.send(embed=embed)


@betterbot.command(name='charity')
async def _charity(
	ctx,
	take_or_add=None,
	amount='half'
):
	if take_or_add in {'add', 'give', 'donate'}:
		bal = await db.get_balance(ctx.author.id)
		amount = check_fraction(bal, amount)
		if amount > bal:
			return await ctx.send("You don't have enough money :(")
		if amount <= 0:
			return await ctx.send(
				'You must enter an amount you would like to donate to the charity'
			)
		await db.change_charity(amount)
		await db.change_balance(ctx.author.id, -amount)
		return await ctx.send(
			f'Donated **{display_money(amount)}** to charity. Thank you!'
		)
	elif take_or_add in {'take'}:
		# bal = await db.get_balance(ctx.author.id)
		# if
		# await db.change_charity(-amount)
		pass
	else:
		charity_amount = await db.get_charity_amount()
		return await ctx.send(
			f'There are **{display_money(charity_amount)}** in the charity.'
		)


def get_username(user_id):
	guild = list(bot.guilds)[0]
	user = guild.get_member(user_id)
	if user is None:
		user = bot.get_user(int(user_id))
		if user is None:
			username = '???'
	if user is not None:
		username = user.display_name
	return username


@betterbot.command(name='portfolio', aliases=('p', 'port'))
async def _portfolio(ctx, user: Member = None):
	if user is None:
		user = ctx.author
	output = []
	for i in await db.get_all_investments(user.id): #IN HERE
		user_id, amount, percentage = i
		username = get_username(user_id)
		if int(amount) <= 0:
			continue
		if amount < 0:
			money_display = 'BANKRUPT' 
		else:
			money_display = display_money(amount)
		percent_display = round(percentage * 100, 3)
		output.append(f'{username} - **{money_display}** - {percent_display}%')
	if dev:
		output.append(f'Shortings:')
		for i in await db.get_all_shortings(user.id):
			user_id, amount, percentage = i
			username = get_username(user_id)
			print(user_id, ctx.author.id)
			if amount < 0:
				money_display = 'BANKRUPT'
			else:
				money_display = display_money(amount)
			percent_display = round(percentage * 100, 3)
			output.append(f'{username} - **{money_display}** - {percent_display}%')

	if user == ctx.author:
		title = 'Your portfolio'
	else:
		title = f"{user.display_name}'s portfolio"

	await ctx.send(embed=discord.Embed(
		title=title,
		description='\n'.join(output)[:2048]
	))


@betterbot.command(name='investors', aliases=('invs', 'i'))
async def _investors(ctx, user: Member = None):
	if user is None:
		user = ctx.author
	user_data = await db.get_user(user.id)
	investors = user_data['investors']
	investors = sorted(investors, key=itemgetter('percent'), reverse=True)
	output = []
	balance = await db.get_net_worth(user.id)
	for investor in investors:
		user_id = investor['user']
		username = get_username(user_id)
		displayed_money = display_money(balance * investor['percent'])
		percent = round(investor['percent'] * 100, 3)
		output.append(f'{username} - **{percent}%** ({displayed_money})')
	await ctx.send(embed=discord.Embed(
		title='Investors',
		description='\n'.join(output)
	))


@betterbot.command(name='refund', aliases=("rnow",))
async def _refund(ctx, user: Member = None, money: int = 'all'):
	return await ctx.send('Command has been temporarily disabled')
	if money <= 0:
		return await ctx.send('You must invest at least $1')
	investements = await db.get_all_investors(ctx.author.id)
	print(user.id)
	print(investements)
	for investement in investements:
		if investement['user'] == user.id:
			break
	if user.id != investement['user']:
		return await ctx.send('This user has not invested in you yet!')
	elif money > await db.get_balance(ctx.author.id):
		return await ctx.send(
			"You don't have enough green papers to do that! Sell sell sell!"
		)
	stuff = await db.get_invested_amount(ctx.author.id, user.id)
	icost = (stuff["percent"] * 100) * await db.get_balance(ctx.author.id)
	print(icost)
	if icost <= money:
		return await ctx.send(
			"I don't think you'd like to give more green papers then they paid to you! So, NO!"
		)
	else:
		await db.change_balance(ctx.author.id, -money)
		await db.change_balance(user.id, money)
		if icost == money:
			await db.remove_investor(ctx.author.id, user.id)
			# >>>>>>>>>>>>>>>>> !!!! TODO !!!!!!!!! ^^^^^^^^^^^^ (IMPORTANT) <<<<<<<<<<<<<<< (FIX THIS)
		await ctx.send('Done!')


async def delete_member(user_id):
	await sell_all(user_id)
	user_balance = await db.get_balance(user_id)
	await db.change_charity(user_balance)
	await db.change_balance(user_id, -user_balance)
	await db.delete_user(user_id)


@bot.event
async def on_member_remove(member):
	await delete_member(member.id)


@bot.event
async def on_member_join(member):
	if not dev and not member.bot:
		await do_tutorial(member)


@betterbot.command(name='help')
async def _help(ctx):
	await ctx.send('<#617850284722487351>')  # how-to-use


@betterbot.command(name='reportscammer')
async def _reportScammer(ctx):
	await ctx.send(
		'i dont hecking care youre just really dumb if you got scammed'
	)


@betterbot.command(name='member')
@dev_only
async def _member(ctx, member: Member):
	await ctx.send(str(member))


@betterbot.command(name='valuetest')
@dev_only
async def _test(
	ctx,
	value: int,
	member: Member,
	value2: int
):
	await ctx.send(f'{value} {member} {value2}')



@betterbot.command(name='number')
async def _number(ctx, amount, text):
	await ctx.send(str(check_fraction(amount, text)))


@betterbot.command(name='api')
async def _api(ctx, action=''):
	is_new = False
	if action.lower() in {'regenerate', 'new'}:
		api_key = await db.generate_api_key(ctx.author.id)
		is_new = True
	else:
		api_key = await db.get_api_key(ctx.author.id)
	embed = discord.Embed(
		title='Your api key',
		description=f'`{api_key}`'
	)
	embed.set_footer(text='DO NOT SHARE THIS API KEY WITH ANYONE')
	await ctx.author.send(embed=embed)
	if ctx.guild is not None:
		if is_new:
			resp = 'Your new API key has been sent to you in your dms.'
		else:
			resp = 'Your API key has been sent to you in your dms.'
		await ctx.send(resp)


@betterbot.command(name='test')
@dev_only
async def _test(ctx):
	await ctx.send('ok')


@betterbot.command(name='history')
@dev_only
async def _history(ctx):
	history = await db.get_history_for_user(ctx.author.id)
	print('history:', history)
	await ctx.send('printed to console')


@betterbot.command(name='changebal')
@commands.has_permissions(administrator=True)
async def _changebal(
	ctx,
	money_amount,
	user: Member = None
):
	if user is None:
		user = ctx.author
	money_amount = check_fraction(money_amount, money_amount)
	await db.change_balance(user.id, money_amount)
	await ctx.send('Ok')


@betterbot.command(name='shortsell', aliases=('ss',))
@dev_only
async def _shortsell(ctx, user: Member = None, amount: int = 0):
	if amount == 0:
		embed = discord.Embed(
			description='Invalid amount.',
			color=discord.Color.red()
		)
		return await ctx.send(embed=embed)
	user_balance = await db.get_balance(user.id)
	yorn = await db.shortsell(
		user.id, ctx.author.id,
		user_balance / amount * 100,
		amount
	)
	if yorn is True:
		embed = discord.Embed(
			description='Success!', color=discord.Color.green()
		)
		return await ctx.send(embed=embed)
	else:
		embed = discord.Embed(
			description='Either you or your ||victim||target does not have enough'
			"green papers to do that. Or you're taking too much moneys.",
			color=discord.Color.red()
		)
		return await ctx.send(embed=embed)
	print(yorn)


@betterbot.command(name='refundshortsell', aliases=('rss',))
@dev_only
async def _refundshortsell(ctx, user, Member = None, amount: int = 0):
	error_text = None
	if db.getbalance(ctx.author.id) < amount:
		return await user.send(embed=discord.Embed(
			description=f'You do not have enough green papers!',
			color=discord.Color.red()
		))
	profit_percent, other_balance = await db.deshort(
		ctx.author.id,
		user,
		amount
	)
	if profit_percent == 1:
		color = discord.Color.greyple()

	elif profit_percent > 2:
		color = discord.Color.green()
	elif profit_percent > 1:
		color = discord.Color.dark_green()

	elif profit_percent < 2:
		color = discord.Color.red()
	elif profit_percent < 1:
		color = discord.Color.dark_red()

	profit_percent_display = round(profit_percent * 100, 3)
	print("HI")
	await ctx.send(embed=discord.Embed(
		description=f'Done! You got **{display_money(amount)}** back. '
		f'({profit_percent_display}%)',
		color=color
	))

	#if other_balance <= amount:
	#	await ctx.send(embed=discord.Embed(
	#		description=f'Because of your greediness, '
	#		'{user.mention} has gone bankrupt.',
	#		color=discord.Color.red()
	#	))
	#	await user.send(embed=discord.Embed(
	#		description=f'You have gone bankrupt!',
	#		color=discord.Color.red()
	#	))
	return
@betterbot.command(name='kill')
@commands.has_permissions(manage_channels=True)
async def _kill(ctx):
	await ctx.send('ok')
	await bot.logout()
	exit()


async def do_tutorial(member):
	guild = member.guild
	await member.add_roles(guild.get_role(629460687336374283))
	channel = await guild.create_text_channel(
		'tutorial',
		overwrites={
			member: discord.PermissionOverwrite(
				read_messages=True,
				send_messages=False
			),
			guild.me: discord.PermissionOverwrite(
				read_messages=True,
				send_messages=True
			),
			guild.default_role: discord.PermissionOverwrite(read_messages=False)
		}
	)
	async with channel.typing():
		await asyncio.sleep(1)
	await channel.send(f'{member.mention}, welcome to The Stonk Exchange.')
	async with channel.typing():
		await asyncio.sleep(3)
	await channel.send(
		'The Stonk Exchange is a stock market simulator '
		'with a twist.'
	)
	await asyncio.sleep(2)
	await channel.send(
		'Instead of investing in real companies, '
		'you invest in your fellow server members.'
	)
	await asyncio.sleep(2)
	msg_tmp = await channel.send(
		"*It's not human trafficking I swear.*"
	)
	await asyncio.sleep(0.5)
	await msg_tmp.edit(content="~~*It's not human trafficking I swear.*~~")

	webhook = await channel.create_webhook(
		name='tutorial webhook',
		reason='Webhook as the example for the tutorial.'
	)
	await asyncio.sleep(1)

	await channel.send(
		'You use `$buy {username} [amount]` to buy part of a user, '
		'`$sell {username} [amount]` to sell part of a user, '
		'and `$bal` or just `$` to check your balance.'
	)
	await asyncio.sleep(2)
	await channel.send(
		"Also, you start off with $100, so invest wisely."
	)
	await asyncio.sleep(1)
	await channel.send(
		'For maximum profits, you should buy a user when their value is low '
		'and sell them when their value increases.'
	)
	await asyncio.sleep(1.5)
	await channel.send(
		"This might be a bit confusing, so I'll show you a quick example."
	)

	webhook = await channel.create_webhook(
		name='tutorial webhook',
		reason='Webhook as the example for the tutorial.'
	)
	await asyncio.sleep(2)

	await webhook.send('$', username='Foo')
	embed = create_balance_embed(
		balance=100,
		net_worth=100,
		user_mention='Foo',
		is_self=True
	)
	await channel.send(embed=embed)
	await asyncio.sleep(2)

	await webhook.send(
		'$',
		username='Bar',
		avatar_url='https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png'
	)
	await asyncio.sleep(0.4)
	embed = create_balance_embed(
		balance=100,
		net_worth=100,
		user_mention='Bar',
		is_self=True
	)
	await channel.send(embed=embed)
	await asyncio.sleep(3)

	await webhook.send('$buy bar', username='Foo')
	embed = create_buy_embed(
		percent=0.5,
		user_mention='Bar'
	)
	await channel.send(embed=embed)
	await asyncio.sleep(1.5)

	await webhook.send('$', username='Foo')
	embed = create_balance_embed(
		balance=0,
		net_worth=100,
		user_mention='Foo',
		is_self=True
	)
	await channel.send(embed=embed)
	await asyncio.sleep(3)

	await webhook.send(
		'$',
		username='Bar',
		avatar_url='https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png'
	)
	embed = create_balance_embed(
		balance=200,
		net_worth=200,
		user_mention='Bar',
		is_self=True
	)
	await channel.send(embed=embed)
	await asyncio.sleep(1)
	await webhook.send(
		'Yay!',
		username='Bar',
		avatar_url='https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png'
	)
	await asyncio.sleep(2)

	await webhook.send(
		'$buy bar',
		username='Baz',
		avatar_url='https://discordapp.com/assets/1cbd08c76f8af6dddce02c5138971129.png'
	)
	await asyncio.sleep(0.1)
	embed = create_buy_embed(
		percent=1/3,
		user_mention='Bar'
	)
	await channel.send(embed=embed)
	await asyncio.sleep(2)

	await webhook.send(
		'$',
		username='Bar',
		avatar_url='https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png'
	)
	embed = create_balance_embed(
		balance=300,
		net_worth=300,
		user_mention='Bar',
		is_self=True
	)
	await channel.send(embed=embed)
	await asyncio.sleep(1)
	await webhook.send(
		'Yay again!',
		username='Bar',
		avatar_url='https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png'
	)
	await asyncio.sleep(2)


	await webhook.send('$sell bar', username='Foo')
	embed = create_sell_embed(
		profit_percent=1.5,
		amount=150
	)
	await channel.send(embed=embed)
	await asyncio.sleep(1.5)
	await webhook.send('stonks!', username='Foo')
	await asyncio.sleep(2)
	await webhook.send(
		':(',
		username='Bar',
		avatar_url='https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png'
	)
	await asyncio.sleep(3)

	await channel.send('TL;DR: All users start with $100')
	await asyncio.sleep(1)
	await channel.send(
		'Buying users removes money from your balance but keeps it in your net worth\n'
		"If the user's balance went up and you sell you make money.\n"
		'Otherwise, you lose money.'
	)
	await asyncio.sleep(1)

	await channel.send('Anyways hopefully all that made sense.')
	await asyncio.sleep(1)
	await channel.send("If it didn't make sense, then you'll figure it out, don't worry.")
	await asyncio.sleep(1)
	ready_message = await channel.send(
		'Ready to start investing? React with :thumbsup: to begin.'
	)
	await ready_message.add_reaction('👍')

	def check(reaction, user):
		print(reaction)
		if user.id != member.id:
			print('user isnt member')
			return False
		if str(reaction.emoji) != '👍':
			print('reaction isnt thumbs up')
			return False
		if reaction.message.id != ready_message.id:
			print('different messages')
			return False
		return True

	await bot.wait_for(
		'reaction_add',
		check=check
	)
	rules_channel = guild.get_channel(617846726841335829)
	rules_message = await rules_channel.fetch_message(617847002104856586)
	print(rules_message.reactions)
	await rules_channel.set_permissions(
		member,
		read_messages=True
	)

	await asyncio.sleep(1)
	await channel.send(
		'Oh, before you actually start investing, please familiarize yourself with '
		'the rules in <#617846726841335829> first.'
	)
	await asyncio.sleep(1.5)
	await channel.send('Once you do that, react with 👌 on the message in rules.')
	start_wait_time = time.time()

	def check(reaction):
		print(reaction)
		if reaction.user_id != member.id:
			return False
		if str(reaction.emoji) != '👌':
			return False
		if reaction.message_id != rules_message.id:
			return False
		return True

	await bot.wait_for(
		'raw_reaction_add',
		check=check
	)

	end_wait_time = time.time()
	if end_wait_time - start_wait_time > 30:
		await channel.send(f'Okay {member.mention}, have fun!')
	else:
		await channel.send(f'Wow, {member.mention}, you read that quickly.')
		await asyncio.sleep(0.5)
		ready_message = await channel.send('Are you sure that you want to continue?')
		await ready_message.add_reaction('👍')

		def check(reaction, user):
			if user.id != member.id:
				return False
			if str(reaction.emoji) != '👍':
				return False
			if reaction.message.id != ready_message.id:
				return False
			return True
		
		await bot.wait_for(
			'reaction_add',
			check=check
		)
		if end_wait_time - start_wait_time > 30:
			await channel.send('Okay then, have fun!')
		else:
			ready_message = await channel.send(
				'Are you really really sure that you want to continue?'
			)
			await ready_message.add_reaction('👍')

			def check(reaction, user):
				if user.id != member.id:
					return False
				if str(reaction.emoji) != '👍':
					return False
				if reaction.message.id != ready_message.id:
					return False
				return True

			await bot.wait_for(
				'reaction_add',
				check=check
			)

			await channel.send(
				"Alright then. Have fun and don't break any rules! :wink:"
			)

	tutorial_role = guild.get_role(629460687336374283)
	await member.remove_roles(tutorial_role)
	await rules_channel.set_permissions(
		member,
		overwrite=None
	)

	await asyncio.sleep(10)
	await channel.delete()


@betterbot.command(name='tutorial')
# @dev_only
async def _tutorial(ctx):
	# if member is None:
	await ctx.send('doing tutorial')
	member = ctx.author
	await do_tutorial(member)
	await ctx.send('tutorial ended')


@betterbot.command(name='rollback')
@commands.has_permissions(administrator=True)
async def _rollback(ctx, *timeago):
	timeago = find_date(' '.join(timeago))



website.bot = bot

website.prepare_server(bot.loop)
bot.run(os.getenv('token'))



Fetching token
?