forked from milenakos/cat-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
4206 lines (3522 loc) · 176 KB
/
Copy pathmain.py
File metadata and controls
4206 lines (3522 loc) · 176 KB
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
import asyncio
import base64
import datetime
import io
import json
import logging
import os
import random
import re
import subprocess
import time
import traceback
from typing import Literal, Optional, Union
import aiohttp
import discord
import discord_emoji
import peewee
from aiohttp import web
from discord import ButtonStyle
from discord.ext import commands
from discord.ui import Button, View
from PIL import Image
import config
import msg2img
from database import Channel, Prism, Profile, Reminder, User, db
logging.basicConfig(level=logging.INFO)
# trigger warning, base64 encoded for your convinience
NONOWORDS = [base64.b64decode(i).decode('utf-8') for i in ["bmlja2E=", "bmlja2Vy", "bmlnYQ==", "bmlnZ2E=", "bmlnZ2Vy"]]
type_dict = {
"Fine": 1000,
"Nice": 750,
"Good": 500,
"Rare": 350,
"Wild": 275,
"Baby": 230,
"Epic": 200,
"Sus": 175,
"Brave": 150,
"Rickroll": 125,
"Reverse": 100,
"Superior": 80,
"TheTrashCell": 50,
"Legendary": 35,
"Mythic": 25,
"8bit": 20,
"Corrupt": 15,
"Professor": 10,
"Divine": 8,
"Real": 5,
"Ultimate": 3,
"eGirl": 2
}
# create a huge list where each cat type is multipled the needed amount of times
CAT_TYPES = []
for k, v in type_dict.items():
CAT_TYPES.extend([k] * v)
# this list stores unique non-duplicate cattypes
cattypes = list(type_dict.keys())
allowedemojis = []
for i in type_dict.keys():
allowedemojis.append(i.lower() + "cat")
prism_names = [
"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November",
"Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-ray", "Yankee"
]
vote_button_texts = [
"You havent voted today!",
"I know you havent voted ;)",
"If vote cat will you friend :)",
"Vote cat for president",
"vote = 0.01% to escape basement",
"vote vote vote vote vote",
"mrrp mrrow go and vote now",
"if you vote you'll be free (no)",
"Like gambling? Vote!",
"vote. btw, i have a pipebomb",
"No votes? :megamind:",
"Cat says you should vote",
"vote = random cats. lets gamble?",
"cat will be happy if you vote",
"VOTE NOW!!!!!",
"Vote on top.gg for free cats",
"Vote for free cats",
"No vote = no free cats :(",
"0.04% to get egirl on voting",
"I voted and got 1000000$",
"I voted and found a gf",
"lebron james forgot to vote",
"vote if you like cats",
"vote if cats > dogs",
"you should vote for cat NOW!"
]
# laod the jsons
with open("config/aches.json", "r") as f:
ach_list = json.load(f)
with open("config/battlepass.json", "r") as f:
battle = json.load(f)
# convert achievement json to a few other things
ach_names = ach_list.keys()
ach_titles = {value["title"].lower(): key for (key, value) in ach_list.items()}
bot = commands.AutoShardedBot(command_prefix="this is a placebo bot which will be replaced when this will get loaded", intents=discord.Intents.default())
funny = [
"why did you click this this arent yours",
"absolutely not",
"cat bot not responding, try again later",
"you cant",
"can you please stop",
"try again",
"403 not allowed",
"stop",
"get a life",
"not for you",
"no",
"nuh uh",
"access denied",
"forbidden",
"don't do this",
"cease",
"wrong",
"aw dangit",
"why don't you press buttons from your commands",
"you're only making me angrier"
]
milenakoos = None
# store credits usernames to prevent excessive api calls
gen_credits = {}
# due to some stupid individuals spamming the hell out of reactions, we ratelimit them
# you can do 50 reactions before they stop, limit resets on global cat loop
reactions_ratelimit = {}
# sort of the same thing but for pointlaughs and per channel instead of peruser
pointlaugh_ratelimit = {}
# cooldowns for /fake cat /catch
catchcooldown = {}
fakecooldown = {}
# cat bot auto-claims in the channel user last ran /vote in
# this is a failsafe to store the fact they voted until they ran that atleast once
pending_votes = []
# prevent ratelimits
casino_lock = []
slots_lock = []
# ???
rigged_users = []
# cat rains
cat_rains = {}
# to prevent double catches
temp_catches_storage = []
# to prevent weird behaviour shortly after a rain
temp_rains_storage = []
# prevent timetravel
in_the_past = False
about_to_stop = False
# manual restarts
queue_restart: Optional[discord.Message] = None
# docs suggest on_ready can be called multiple times
on_ready_debounce = False
# d.py doesnt cache app emojis so we do it on our own yippe
emojis = {}
# for mentioning it in catch message, will be auto-fetched in on_ready()
DONATE_ID = 1249368737824374896
RAIN_ID = 1270470307102195752
# for funny starts, you can probably edit maintaince_loop to restart every X of them
loop_count = 0
# loops in dpy can randomly break, i check if is been over X minutes since last loop to restart it
last_loop_time = 0
def get_profile(guild_id, user_id):
try:
return Profile.get(
(Profile.guild_id == int(guild_id)) &
(Profile.user_id == int(user_id))
)
except Exception:
return Profile.create(
guild_id=guild_id,
user_id=user_id
)
def get_emoji(name):
global emojis
if name in emojis.keys():
return emojis[name]
else:
return "🔳"
# news stuff
news_list = [
{"title": "Cat Bot Survey - win rains!", "emoji": "📜"},
{"title": "New Cat Rains perks!", "emoji": "✨"}
]
async def send_news(interaction: discord.Interaction):
news_id, original_caller = interaction.data["custom_id"].split(" ") # pyright: ignore
if str(interaction.user.id) != original_caller:
await do_funny(interaction)
return
await interaction.response.defer()
news_id = int(news_id)
user, _ = User.get_or_create(user_id=interaction.user.id)
current_state = user.news_state.strip()
user.news_state = current_state[:news_id] + "1" + current_state[news_id + 1:]
user.save()
if news_id == 0:
embed = discord.Embed(
title="📜 Cat Bot Survey",
description="Hello and welcome to The Cat Bot Times:tm:! I kind of want to learn more about your time with Cat Bot because I barely know about it lmao. This should only take a couple of minutes.\n\nGood high-quality responses will win FREE cat rain prizes.\n\nSurvey is closed!",
color=0x6E593C
)
await interaction.edit_original_response(content=None, view=None, embed=embed)
elif news_id == 1:
embed = discord.Embed(
title="✨ New Cat Rains perks!",
description="Hey there! Buying Cat Rains now gives you access to `/editprofile` command! You can add an image, change profile color, and add an emoji next to your name. Additionally, you will now get a special role in our [discord server](https://discord.gg/staring).\nEveryone who ever bought rains and all future buyers will get it.\nAnyone who bought these abilities separately in the past (known as 'Cat Bot Supporter') have received 10 minutes of Rains as compensation.\n\nThis is a really cool perk and I hope you like it!",
color=0x6E593C
)
await interaction.edit_original_response(content=None, view=None, embed=embed)
# this is some common code which is run whether someone gets an achievement
async def achemb(message, ach_id, send_type, author_string=None):
if not author_string:
try:
author_string = message.author
except Exception:
author_string = message.user
author = author_string.id
if not message.guild:
return
profile = get_profile(message.guild.id, author)
if not profile[ach_id]:
profile[ach_id] = True
profile.save()
ach_data = ach_list[ach_id]
desc = ach_data["description"]
if ach_id == "dataminer":
desc = "Your head hurts -- you seem to have forgotten what you just did to get this."
if ach_id != "thanksforplaying":
embed = discord.Embed(
title=ach_data["title"],
description=desc,
color=0x007F0E
).set_author(
name="Achievement get!",
icon_url="https://wsrv.nl/?url=raw.githubusercontent.com/staring-cat/emojis/main/cat_throphy.png"
).set_footer(text=f"Unlocked by {author_string.name}")
else:
embed = discord.Embed(
title="Cataine Addict",
description="Defeat the dog mafia\nThanks for playing! ✨",
color=0xC12929
).set_author(
name="Demonic achievement unlocked! 🌟",
icon_url="https://wsrv.nl/?url=raw.githubusercontent.com/staring-cat/emojis/main/demonic.png"
).set_footer(text=f"Congrats to {author_string.name}!!")
embed2 = discord.Embed(
title="Cataine Addict",
description="Defeat the dog mafia\nThanks for playing! ✨",
color=0xFFFF00
).set_author(
name="Demonic achievement unlocked! 🌟",
icon_url="https://wsrv.nl/?url=raw.githubusercontent.com/staring-cat/emojis/main/demonic.png"
).set_footer(text=f"Congrats to {author_string.name}!!")
try:
result = None
perms: discord.Permissions = message.channel.permissions_for(message.guild.me)
correct_perms = perms.send_messages and (not isinstance(message.channel, discord.Thread) or perms.send_messages_in_threads)
if send_type == "reply" and correct_perms:
result = await message.reply(embed=embed)
elif send_type == "send" and correct_perms:
result = await message.channel.send(embed=embed)
elif send_type == "followup":
result = await message.followup.send(embed=embed, ephemeral=True)
elif send_type == "response":
result = await message.response.send_message(embed=embed)
await battlepass_finale(message, profile)
except Exception:
pass
if result and ach_id == "thanksforplaying":
await asyncio.sleep(2)
await result.edit(embed=embed2)
await asyncio.sleep(2)
await result.edit(embed=embed)
await asyncio.sleep(2)
await result.edit(embed=embed2)
await asyncio.sleep(2)
await result.edit(embed=embed)
# handle curious people clicking buttons
async def do_funny(message):
await message.response.send_message(random.choice(funny), ephemeral=True)
await achemb(message, "curious", "send")
user = get_profile(message.guild.id, message.user.id)
user.funny += 1
user.save()
if user.funny >= 50:
await achemb(message, "its_not_working", "send")
# :eyes:
async def battlepass_finale(message, user):
# check ach req
for k in ach_names:
if not user[k] and ach_list[k]["category"] != "Hidden":
return
# check battlepass req
if user.battlepass != len(battle["levels"]) - 2:
return
user.battlepass += 2
user.save()
perms: discord.Permissions = message.channel.permissions_for(message.guild.me)
if perms.send_messages and (not isinstance(message.channel, discord.Thread) or perms.send_messages_in_threads):
try:
author_string = message.author
except Exception:
author_string = message.user
await asyncio.sleep(5)
await message.channel.send("...")
await asyncio.sleep(3)
await message.channel.send("You...")
await asyncio.sleep(3)
await message.channel.send("...actually did it.")
await asyncio.sleep(3)
await message.channel.send(embed=discord.Embed(
title="True Ending achieved!",
description="You are finally free.",
color=0xFF81C6
).set_author(
name="Cattlepass complete!",
icon_url="https://wsrv.nl/?url=raw.githubusercontent.com/milenakos/cat-bot/main/images/cat.png"
).set_footer(
text=f"Congrats to {author_string}"
)
)
# function to autocomplete cat_type choices for /givecat, and /forcespawn, which also allows more than 25 options
async def cat_type_autocomplete(interaction: discord.Interaction, current: str) -> list[discord.app_commands.Choice[str]]:
return [discord.app_commands.Choice(name=choice, value=choice) for choice in cattypes if current.lower() in choice.lower()][:25]
# function to autocomplete cat_type choices for /gift, which shows only cats user has and how many of them they have
async def gift_autocomplete(interaction: discord.Interaction, current: str) -> list[discord.app_commands.Choice[str]]:
user = get_profile(interaction.guild.id, interaction.user.id)
actual_user, _ = User.get_or_create(user_id=interaction.user.id)
choices = []
for choice in cattypes:
if current.lower() in choice.lower() and user[f"cat_{choice}"] != 0:
choices.append(discord.app_commands.Choice(name=f"{choice} (x{user[f'cat_{choice}']})", value=choice))
if current.lower() in "rain" and actual_user.rain_minutes != 0:
choices.append(discord.app_commands.Choice(name=f"Rain ({actual_user.rain_minutes} minutes)", value="rain"))
return choices[:25]
# function to autocomplete achievement choice for /giveachievement, which also allows more than 25 options
async def ach_autocomplete(interaction: discord.Interaction, current: str) -> list[discord.app_commands.Choice[str]]:
return [discord.app_commands.Choice(name=val["title"], value=key) for (key, val) in ach_list.items() if (alnum(current) in alnum(key) or alnum(current) in alnum(val["title"]))][:25]
# converts string to lowercase alphanumeric characters only
def alnum(string):
return "".join(item for item in string.lower() if item.isalnum())
async def unsetup(channel):
try:
wh = discord.Webhook.from_url(channel.webhook, client=bot)
await wh.delete(prefer_auth=False)
except Exception:
pass
channel.delete_instance()
async def spawn_cat(ch_id, localcat=None, force_spawn=None):
try:
channel = Channel.get(channel_id=ch_id)
except Exception:
return
if channel.cat or in_the_past:
return
if not localcat:
localcat = random.choice(CAT_TYPES)
icon = get_emoji(localcat.lower() + "cat")
file = discord.File(f"images/spawn/{localcat.lower()}_cat.png", description="forcespawned" if force_spawn else None)
try:
channeley = discord.Webhook.from_url(channel.webhook, client=bot)
thread_id = channel.thread_mappings
except Exception:
try:
temp_channel = bot.get_channel(int(ch_id))
if not temp_channel \
or not isinstance(temp_channel, Union[discord.TextChannel, discord.StageChannel, discord.VoiceChannel]) \
or not temp_channel.permissions_for(temp_channel.guild.me).manage_webhooks:
raise Exception
with open("images/cat.png", "rb") as f:
wh = await temp_channel.create_webhook(name="Cat Bot", avatar=f.read())
channel.webhook = wh.url
channel.save()
await spawn_cat(ch_id, localcat) # respawn
except Exception:
await unsetup(channel)
return
appearstring = "{emoji} {type} cat has appeared! Type \"cat\" to catch it!" if not channel.appear else channel.appear
if channel.cat or in_the_past:
# its never too late to return
return
try:
if thread_id:
message_is_sus = await channeley.send(appearstring.replace("{emoji}", str(icon)).replace("{type}", localcat), file=file, wait=True, thread=discord.Object(int(ch_id)))
else:
message_is_sus = await channeley.send(appearstring.replace("{emoji}", str(icon)).replace("{type}", localcat), file=file, wait=True)
except discord.Forbidden:
await unsetup(channel)
return
except discord.NotFound:
await unsetup(channel)
return
except Exception:
return
if message_is_sus.channel.id != int(ch_id):
# user changed the webhook destination, panic mode
if thread_id:
await channeley.send("uh oh spaghettio you changed webhook destination and idk what to do with that so i will now self destruct do /setup to fix it", thread=discord.Object(int(ch_id)))
else:
await channeley.send("uh oh spaghettio you changed webhook destination and idk what to do with that so i will now self destruct do /setup to fix it")
await unsetup(channel)
return
channel.cat = message_is_sus.id
channel.yet_to_spawn = 0
channel.save()
# a loop for various maintaince which is ran every 5 minutes
async def maintaince_loop():
global pointlaugh_ratelimit, reactions_ratelimit, last_loop_time, loop_count, in_the_past, about_to_stop
last_loop_time = time.time()
pointlaugh_ratelimit = {}
reactions_ratelimit = {}
await bot.change_presence(
activity=discord.CustomActivity(name=f"Catting in {len(bot.guilds):,} servers")
)
async with aiohttp.ClientSession() as session:
if config.TOP_GG_TOKEN:
# send server count to top.gg
try:
await session.post(f'https://top.gg/api/bots/{bot.user.id}/stats',
headers={"Authorization": config.TOP_GG_TOKEN},
json={"server_count": len(bot.guilds), "shard_count": len(bot.shards)},
timeout=15)
except Exception:
print("Posting to top.gg failed.")
for channel in Channel.select().where((Channel.yet_to_spawn < time.time()) & (Channel.cat == 0)):
await spawn_cat(str(channel.channel_id))
await asyncio.sleep(0.1)
notified_users = []
errored_users = []
processed_users = []
# THIS IS CONSENTUAL AND TURNED OFF BY DEFAULT DONT BAN ME
for user in User.select().where((User.vote_remind != 0) & (User.vote_time_topgg + 43200 < time.time()) & (User.reminder_topgg_exists == 0)):
if user.user_id in processed_users:
# prevent double notifis
continue
await asyncio.sleep(0.1)
processed_users.append(user.user_id)
channeley = bot.get_channel(user.vote_remind)
if not isinstance(channeley, discord.TextChannel):
user.vote_remind = 0
errored_users.append(user)
continue
view = View(timeout=1)
button = Button(emoji=get_emoji("topgg"), label=random.choice(vote_button_texts), style=ButtonStyle.gray, url="https://top.gg/bot/966695034340663367/vote")
view.add_item(button)
try:
await channeley.send(f"<@{user.user_id}> You can vote now!", view=view)
user.reminder_topgg_exists = time.time()
notified_users.append(user)
except Exception:
user.vote_remind = 0
errored_users.append(user)
with db.atomic():
User.bulk_update(notified_users, fields=[User.reminder_topgg_exists], batch_size=50)
User.bulk_update(errored_users, fields=[User.vote_remind], batch_size=50)
for reminder in Reminder.select().where(Reminder.time < time.time()):
try:
user = await bot.fetch_user(reminder.user_id)
await user.send(reminder.text)
await asyncio.sleep(0.5)
except Exception:
pass
reminder.delete_instance()
backupchannel = bot.get_channel(config.BACKUP_ID)
if not isinstance(backupchannel, Union[discord.TextChannel, discord.StageChannel, discord.VoiceChannel, discord.Thread]):
raise ValueError
await backupchannel.send(f"In {len(bot.guilds)} servers, loop {loop_count}.")
loop_count += 1
# some code which is run when bot is started
async def on_ready():
global milenakoos, OWNER_ID, on_ready_debounce, gen_credits, emojis
if on_ready_debounce:
return
on_ready_debounce = True
print("cat is now online")
emojis = {emoji.name: str(emoji) for emoji in await bot.fetch_application_emojis()}
appinfo = bot.application
if appinfo.team and appinfo.team.owner_id:
milenakoos = await bot.fetch_user(appinfo.team.owner_id)
else:
milenakoos = appinfo.owner
OWNER_ID = milenakoos.id
credits = {
"author": [553093932012011520],
"contrib": [576065759185338371, 819980535639572500, 432966085025857536, 646401965596868628, 696806601771974707, 804762486946660353, 931342092121280543, 695359046928171118],
"tester": [712639066373619754, 902862104971849769, 709374062237057074, 520293520418930690, 689345298686148732, 1004128541853618197, 839458185059500032],
"trash": [520293520418930690]
}
# fetch discord usernames by user ids
for key in credits.keys():
peoples = []
try:
for i in credits[key]:
user = await bot.fetch_user(i)
peoples.append(user.name.replace("_", r"\_"))
except Exception:
# death
pass
gen_credits[key] = ", ".join(peoples)
# this is all the code which is ran on every message sent
# a lot of it is for easter eggs or achievements
async def on_message(message: discord.Message):
global in_the_past, emojis, queue_restart, about_to_stop
text = message.content
if not bot.user or message.author.id == bot.user.id:
return
if time.time() > last_loop_time + 300:
await maintaince_loop()
if text == "lol_i_have_dmed_the_cat_bot_and_got_an_ach" and not message.guild:
await message.channel.send("which part of \"send in server\" was unclear?")
return
elif message.guild is None:
await message.channel.send("good job! please send \"lol_i_have_dmed_the_cat_bot_and_got_an_ach\" in server to get your ach!")
return
perms: discord.Permissions = message.channel.permissions_for(message.guild.me)
achs = [
["cat?", "startswith", "???"],
["catn", "exact", "catn"],
["cat!coupon jr0f-pzka", "exact", "coupon_user"],
["pineapple", "exact", "pineapple"],
["cat!i_like_cat_website", "exact", "website_user"],
["cat!i_clicked_there", "exact", "click_here"],
["cat!lia_is_cute", "exact", "nerd"],
["i read help", "exact", "patient_reader"],
[str(bot.user.id), "in", "who_ping"],
["lol_i_have_dmed_the_cat_bot_and_got_an_ach", "exact", "dm"],
["dog", "exact", "not_quite"],
["egril", "exact", "egril"],
["-.-. .- -", "exact", "morse_cat"],
["tac", "exact", "reverse"]
]
reactions = [
["v1;", "custom", "why_v1"],
["proglet", "custom", "professor_cat"],
["xnopyt", "custom", "vanish"],
["silly", "custom", "sillycat"],
["indev", "vanilla", "🐸"],
["bleh", "custom", "blepcat"],
["blep", "custom", "blepcat"]
]
responses = [
["cat!sex", "exact", "..."],
["cellua good", "in", ".".join([str(random.randint(2, 254)) for _ in range(4)])],
["https://tenor.com/view/this-cat-i-have-hired-this-cat-to-stare-at-you-hired-cat-cat-stare-gif-26392360", "exact", "https://tenor.com/view/cat-staring-cat-gif-16983064494644320763"]
]
# here are some automation hooks for giving out purchases and autoupdating
if config.GITHUB_CHANNEL_ID and message.channel.id == config.GITHUB_CHANNEL_ID:
about_to_stop = True
os.system("git pull")
await vote_server.cleanup()
in_the_past = True
await bot.cat_bot_reload_hook() # pyright: ignore
if config.DONOR_CHANNEL_ID and message.channel.id == config.DONOR_CHANNEL_ID:
user, _ = User.get_or_create(user_id=message.content)
user.premium = True
user.save()
if config.RAIN_CHANNEL_ID and message.channel.id == config.RAIN_CHANNEL_ID and text.lower().startswith("cat!rain"):
things = text.split(" ")
user, _ = User.get_or_create(user_id=things[1])
if not user.rain_minutes:
user.rain_minutes = 0
if things[2] == "short":
user.rain_minutes += 2
elif things[2] == "medium":
user.rain_minutes += 10
elif things[2] == "long":
user.rain_minutes += 20
else:
user.rain_minutes += int(things[2])
user.premium = True
user.save()
react_count = 0
# :staring_cat: reaction on "bullshit"
if " " not in text and len(text) > 7 and text.isalnum():
s = text.lower()
total_vow = 0
total_illegal = 0
for i in "aeuio":
total_vow += s.count(i)
illegal = ["bk", "fq", "jc", "jt", "mj", "qh", "qx", "vj", "wz", "zh",
"bq", "fv", "jd", "jv", "mq", "qj", "qy", "vk", "xb", "zj",
"bx", "fx", "jf", "jw", "mx", "qk", "qz", "vm", "xg", "zn",
"cb", "fz", "jg", "jx", "mz", "ql", "sx", "vn", "xj", "zq",
"cf", "gq", "jh", "jy", "pq", "qm", "sz", "vp", "xk", "zr",
"cg", "gv", "jk", "jz", "pv", "qn", "tq", "vq", "xv", "zs",
"cj", "gx", "jl", "kq", "px", "qo", "tx", "vt", "xz", "zx",
"cp", "hk", "jm", "kv", "qb", "qp", "vb", "vw", "yq",
"cv", "hv", "jn", "kx", "qc", "qr", "vc", "vx", "yv",
"cw", "hx", "jp", "kz", "qd", "qs", "vd", "vz", "yz",
"cx", "hz", "jq", "lq", "qe", "qt", "vf", "wq", "zb",
"dx", "iy", "jr", "lx", "qf", "qv", "vg", "wv", "zc",
"fk", "jb", "js", "mg", "qg", "qw", "vh", "wx", "zg"]
for j in illegal:
if j in s:
total_illegal += 1
vow_perc = 0
const_perc = len(text)
if total_vow != 0:
vow_perc = len(text) / total_vow
if total_vow != len(text):
const_perc = len(text) / (len(text) - total_vow)
if (vow_perc <= 3 and const_perc >= 6) or total_illegal >= 2:
try:
if message.channel.permissions_for(message.guild.me).add_reactions:
await message.add_reaction(get_emoji("staring_cat"))
react_count += 1
except Exception:
pass
try:
if perms.send_messages and (not message.thread or perms.send_messages_in_threads):
if "robotop" in message.author.name.lower() and "i rate **cat" in message.content.lower():
icon = str(get_emoji("no_cat_throphy")) + " "
await message.reply("**RoboTop**, I rate **you** 0 cats " + icon * 5)
if "leafbot" in message.author.name.lower() and "hmm... i would rate cat" in message.content.lower():
icon = str(get_emoji("no_cat_throphy")) + " "
await message.reply("Hmm... I would rate you **0 cats**! " + icon * 5)
except Exception:
pass
if message.author.bot or message.webhook_id is not None:
return
if "cat!n4lltvuCOKe2iuDCmc6JsU7Jmg4vmFBj8G8l5xvoDHmCoIJMcxkeXZObR6HbIV6" in text:
msg = message
try:
if perms.manage_messages:
await message.delete()
except Exception:
pass
await achemb(msg, "dataminer", "send")
for ach in achs:
if (ach[1] == "startswith" and text.lower().startswith(ach[0])) or \
(ach[1] == "re" and re.search(ach[0], text.lower())) or \
(ach[1] == "exact" and ach[0] == text.lower()) or \
(ach[1] == "in" and ach[0] in text.lower()):
await achemb(message, ach[2], "reply")
if perms.add_reactions:
for r in reactions:
if r[0] in text.lower() and reactions_ratelimit.get(message.author.id, 0) < 20:
if r[1] == "custom":
em = get_emoji(r[2])
elif r[1] == "vanilla":
em = r[2]
try:
await message.add_reaction(em)
react_count += 1
reactions_ratelimit[message.author.id] = reactions_ratelimit.get(message.author.id, 0) + 1
except Exception:
pass
if perms.send_messages and (not message.thread or perms.send_messages_in_threads):
for resp in responses:
if (resp[1] == "startswith" and text.lower().startswith(resp[0])) or \
(resp[1] == "re" and re.search(resp[0], text.lower())) or \
(resp[1] == "exact" and resp[0] == text.lower()) or \
(resp[1] == "in" and resp[0] in text.lower()):
try:
await message.reply(resp[2])
except Exception:
pass
try:
if message.author in message.mentions and perms.add_reactions:
await message.add_reaction(get_emoji("staring_cat"))
react_count += 1
except Exception:
pass
if react_count >= 3 and perms.add_reactions:
await achemb(message, "silly", "send")
if (":place_of_worship:" in text or "🛐" in text) and (":cat:" in text or ":staring_cat:" in text or "🐱" in text):
await achemb(message, "worship", "reply")
if text.lower() in ["testing testing 1 2 3", "cat!ach"]:
try:
if perms.send_messages and (not message.thread or perms.send_messages_in_threads):
await message.reply("test success")
except Exception:
# test failure
pass
await achemb(message, "test_ach", "reply")
if text.lower() == "please do not the cat":
user = get_profile(message.guild.id, message.author.id)
user.cat_Fine -= 1
user.save()
try:
if perms.send_messages and (not message.thread or perms.send_messages_in_threads):
await message.reply(f"ok then\n{message.author.name.replace("_", r"\_")} lost 1 fine cat!!!1!\nYou now have {user.cat_Fine:,} cats of dat type!")
except Exception:
pass
await achemb(message, "pleasedonotthecat", "reply")
if text.lower() == "please do the cat":
thing = discord.File("images/socialcredit.jpg", filename="socialcredit.jpg")
try:
if perms.send_messages and perms.attach_files and (not message.thread or perms.send_messages_in_threads):
await message.reply(file=thing)
except Exception:
pass
await achemb(message, "pleasedothecat", "reply")
if text.lower() == "car":
file = discord.File("images/car.png", filename="car.png")
embed = discord.Embed(title="car!", color=0x6E593C).set_image(url="attachment://car.png")
try:
if perms.send_messages and perms.attach_files and (not message.thread or perms.send_messages_in_threads):
await message.reply(file=file, embed=embed)
except Exception:
pass
await achemb(message, "car", "reply")
if text.lower() == "cart":
file = discord.File("images/cart.png", filename="cart.png")
embed = discord.Embed(title="cart!", color=0x6E593C).set_image(url="attachment://cart.png")
try:
if perms.send_messages and perms.attach_files and (not message.thread or perms.send_messages_in_threads):
await message.reply(file=file, embed=embed)
except Exception:
pass
try:
if ("sus" in text.lower() or "amog" in text.lower() or "among" in text.lower() or "impost" in text.lower() or "report" in text.lower()) and \
(channel := Channel.get_or_none(channel_id=message.channel.id)) and channel.cat and perms.read_message_history:
catchmsg = await message.channel.fetch_message(channel.cat)
if get_emoji("suscat") in catchmsg.content:
await achemb(message, "sussy", "send")
except Exception:
pass
# this is run whether someone says "cat" (very complex)
if text.lower() == "cat":
user = get_profile(message.guild.id, message.author.id)
channel = Channel.get_or_none(channel_id=message.channel.id)
if not channel or not channel.cat or channel.cat in temp_catches_storage or user.timeout > time.time():
# laugh at this user
# (except if rain is active, we dont have perms or channel isnt setupped, or we laughed way too much already)
if channel and cat_rains.get(str(message.channel.id), 0) < time.time() and perms.add_reactions and pointlaugh_ratelimit.get(message.channel.id, 0) < 10:
try:
await message.add_reaction(get_emoji("pointlaugh"))
pointlaugh_ratelimit[message.channel.id] = pointlaugh_ratelimit.get(message.channel.id, 0) + 1
except Exception:
pass
else:
pls_remove_me_later_k_thanks = channel.cat
temp_catches_storage.append(channel.cat)
times = [channel.spawn_times_min, channel.spawn_times_max]
if cat_rains.get(str(message.channel.id), 0) != 0:
if cat_rains.get(str(message.channel.id), 0) > time.time():
times = [1, 2]
else:
temp_rains_storage.append(message.channel.id)
del cat_rains[str(message.channel.id)]
try:
if perms.send_messages and (not message.thread or perms.send_messages_in_threads):
await message.channel.send("# :bangbang: this concludes the cat rain.")
await message.channel.send("# :bangbang: this concludes the cat rain.")
await message.channel.send("# :bangbang: this concludes the cat rain.")
except Exception:
pass
if queue_restart and (len(cat_rains) == 0 or int(max(cat_rains.values())) < time.time()):
about_to_stop = True
await queue_restart.reply("restarting now!")
os.system("git pull")
await vote_server.cleanup()
in_the_past = True
await bot.cat_bot_reload_hook() # pyright: ignore
decided_time = random.uniform(times[0], times[1])
if channel.yet_to_spawn < time.time():
channel.yet_to_spawn = time.time() + decided_time + 10
else:
decided_time = 0
try:
current_time = message.created_at.timestamp()
channel.lastcatches = current_time
cat_temp = channel.cat
channel.cat = 0
try:
if perms.read_message_history:
var = await message.channel.fetch_message(cat_temp)
else:
raise Exception
except Exception:
try:
if perms.send_messages and (not message.thread or perms.send_messages_in_threads):
await message.channel.send(f"oopsie poopsie i cant access the original message but {message.author.mention} *did* catch a cat rn")
except Exception:
pass
return
catchtime = var.created_at
catchcontents = var.content
try:
send_target = discord.Webhook.from_url(channel.webhook, client=bot)
try:
if channel.thread_mappings:
await send_target.delete_message(cat_temp, thread=discord.Object(int(message.channel.id)))
else:
await send_target.delete_message(cat_temp)
except Exception:
if perms.manage_messages:
await cat_temp.delete()
except Exception:
send_target = message.channel
try:
# some math to make time look cool
then = catchtime.timestamp()
time_caught = round(abs(current_time - then), 3) # cry about it
if time_caught >= 1:
time_caught = round(time_caught, 2)
days = time_caught // 86400
time_left = time_caught - (days * 86400)
hours = time_left // 3600
time_left = time_left - (hours * 3600)
minutes = time_left // 60
seconds = time_left - (minutes * 60)
caught_time = ""
if days:
caught_time = caught_time + str(int(days)) + " days "
if hours:
caught_time = caught_time + str(int(hours)) + " hours "
if minutes:
caught_time = caught_time + str(int(minutes)) + " minutes "
if seconds:
pre_time = round(seconds, 3)
if int(pre_time) == float(pre_time):
# replace .0 with .00 basically
pre_time = str(int(pre_time)) + ".00"
caught_time = caught_time + str(pre_time) + " seconds "
do_time = True
if time_caught <= 0:
do_time = False
except Exception:
# if some of the above explodes just give up
do_time = False
caught_time = "undefined amounts of time "
if cat_rains.get(str(message.channel.id), 0) + 10 > time.time() or message.channel.id in temp_rains_storage:
do_time = False
icon = None
partial_type = None
for v in allowedemojis:
if v in catchcontents:
partial_type = v
break
if not partial_type:
return
for i in cattypes:
if i.lower() in partial_type:
le_emoji = i
break
suffix_string = ""
# calculate prism boost
boost_chance = 0
disabled_chance = 0
boost_prisms = []
disabled_prisms = []
for prism in Prism.select().where(Prism.guild_id == message.guild.id):
if prism.user_id == message.author.id:
if prism[f"enabled_{le_emoji.lower()}"]:
boost_chance += 5
boost_prisms.extend([["Your", prism.name]] * 5)
else:
disabled_chance += 5
disabled_prisms.extend([["Your", prism.name]] * 5)
else:
if prism[f"enabled_{le_emoji.lower()}"]:
boost_chance += 1
boost_prisms.append([prism.user_id, prism.name])
else:
disabled_chance += 1
disabled_prisms.append([prism.user_id, prism.name])
all_prisms = boost_prisms + disabled_prisms
# apply prism boost
if random.randint(1, 100) <= boost_chance + disabled_chance:
boost_prism = random.choice(all_prisms)
if boost_prism[0] != "Your":
prism_user = await bot.fetch_user(boost_prism[0])
boost_applied_prism = str(prism_user) + "'s prism " + boost_prism[1]
else:
boost_applied_prism = "Your prism " + boost_prism[1]