repl.it
@akpkushkid/

Stonks Bot

Python

No description

fork
loading
Files
  • main.py
  • 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
from discord.ext import commands
from database import db
import website
import os
import discord
import typing
import asyncio
from utils import display_money, check_fraction
from contextlib import redirect_stdout
import io
import investing
import giveaway
from operator import itemgetter
from betterbot import BetterBot

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:
			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 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()

	if not dev:
		asyncio.ensure_future(giveaway.on_ready())
		await on_ready_main()


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


@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)
# 	await 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**')


@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)

	if bal >= 0:
		color = discord.Color.green()
	else:
		color = discord.Color.red()

	money_display = display_money(bal)

	if user == ctx.author:
		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 != bal:
		embed.set_footer(text=f'Net worth: {display_money(net_worth)}')
	await ctx.send(embed=embed)

	# await give_cash_if_broke(user)


@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)

	if percent >= 1:
		displayed_percent = 100
	else:
		displayed_percent = round(percent * 100, 3)

	await ctx.send(embed=discord.Embed(
		description=f"You've bought {displayed_percent}% of {user.mention}"
	))


@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)


@betterbot.command(name='sell', aliases=('devest', 's', 'uninvest'))
async def _sell(
	ctx,
	user: Member = None,
	amount='all'
):
	error_text = None
	profit_percent, amount, other_balance = await investing.sell(
		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)

	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

# 	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):
		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)


@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, amount, text):
	await ctx.send('ok')
	exit()

website.bot = bot

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