-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathviews.py
2669 lines (2086 loc) · 102 KB
/
views.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
from __future__ import annotations
import asyncio
import collections
import random
import traceback
import typing
from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, Union
import discord
import mathjspy
from discord import ButtonStyle, Embed, File, Interaction
from discord.abc import Messageable
from discord.ext import commands
from discord.ext.commands.context import Context
from discord.flags import UserFlags
from discord.ui import Button, Modal, TextInput, View
from discord.utils import MISSING, maybe_coroutine
if TYPE_CHECKING:
from tweepy import Media
from .emoji import CustomEmoji
from .tweet import TweepyTweet
PossiblePage = Union[str, Embed, File, Sequence[Union[Embed, Any]], tuple[Union[File, Any], ...], dict[str, Any]]
def default_check(view: Paginator, interaction_user_id: int, view_author_id: int) -> bool:
cxint = view._context_or_interaction
bot = (cxint.bot if isinstance(cxint, commands.Context) else cxint.client) if cxint else None
bot_owners: list[int] = []
if bot:
bot_owners.extend(getattr(bot, "owner_ids", []))
if owner_id := getattr(bot, "owner_id", None):
bot_owners.append(owner_id)
return interaction_user_id in bot_owners + [view_author_id]
class ChooseNumber(Modal):
def __init__(self, current_page: int, total_pages: int, page_string: str, /):
super().__init__(
title="Which page would you like to go to?",
timeout=15,
custom_id="paginator:modal:choose_number",
)
self._current_page: int = current_page
self._total_pages: int = total_pages
self.value: Optional[int] = None # filled in by on_submit
self.number_input = TextInput(
placeholder=f"Current: {page_string}",
label=f"Enter a page number between 1 and {total_pages}",
custom_id="paginator:choose_number",
max_length=len(str(total_pages)),
min_length=1,
)
self.add_item(self.number_input)
async def on_submit(self, interaction: Interaction) -> None:
assert isinstance(self.number_input.value, str)
if (
not self.number_input.value.isdigit()
or int(self.number_input.value) <= 0
or int(self.number_input.value) > self._total_pages
):
await interaction.response.send_message(
f"Please enter a valid number between 1 and {self._total_pages}", ephemeral=True
)
self.stop()
return
number = int(self.number_input.value) - 1
if number == self._current_page: # type: ignore
await interaction.response.send_message("That is the current page!", ephemeral=True)
self.stop()
return
self.value = number
await interaction.response.send_message(f"There is page {self.value + 1} for you <3", ephemeral=True)
self.stop()
class PaginatorButton(Button["Paginator"]):
def __init__(
self,
*,
emoji: Optional[str] = None,
label: Optional[str] = None,
custom_id: Optional[str] = None,
style: ButtonStyle = ButtonStyle.blurple,
row: Optional[int] = None,
disabled: bool = False,
position: int = MISSING,
):
super().__init__(emoji=emoji, label=label, custom_id=custom_id, style=style, row=row, disabled=disabled)
self.position = position
self.view: Paginator
async def __handle_number_modal(self, interaction: Interaction) -> Optional[int]:
modal = ChooseNumber(self.view._current_page, self.view.max_pages, self.view.page_string)
await interaction.response.send_modal(modal)
await modal.wait()
return modal.value
async def callback(self, interaction: Interaction) -> None:
if self.custom_id == "stop_button":
await self.view.stop()
return
if self.custom_id == "right_button":
self.view._current_page += 1
elif self.custom_id == "left_button":
self.view._current_page -= 1
elif self.custom_id == "first_button":
self.view._current_page = 0
elif self.custom_id == "last_button":
self.view._current_page = self.view.max_pages - 1
elif self.custom_id == "page_indicator_button":
new_page = await self.__handle_number_modal(interaction)
if new_page is not None:
self.view._current_page = new_page
else:
return
self.view._update_buttons_state()
pages = self.view.get_page(self.view._current_page)
edit_kwargs = (await self.view.get_kwargs_from_page(pages)).copy()
edit_kwargs["attachments"] = edit_kwargs.pop("files")
await self.view._edit_message(interaction, **edit_kwargs)
class Paginator(View):
FIRST: Optional[PaginatorButton] = None # filled in __add_buttons
LEFT: Optional[PaginatorButton] = None # filled in __add_buttons
RIGHT: Optional[PaginatorButton] = None # filled in __add_buttons
LAST: Optional[PaginatorButton] = None # filled in __add_buttons
STOP: Optional[PaginatorButton] = None # filled in __add_buttons
PAGE_INDICATOR: Optional[PaginatorButton] = None # filled in __add_buttons
def __init__(
self,
pages: Sequence[PossiblePage],
*,
ctx: Context = MISSING,
interaction: Interaction = MISSING,
author_id: int = MISSING,
per_page: int = 1,
buttons: dict = MISSING,
check: Callable = MISSING,
timeout: Union[int, float] = 180.0,
always_show_stop_button: bool = False,
delete_after: bool = False,
disable_after: bool = False,
clear_buttons_after: bool = False,
) -> None:
"""Initialize the Paginator."""
super().__init__(timeout=timeout)
if ctx is not MISSING and interaction is not MISSING:
raise ValueError("ctx and interaction cannot be used together")
DEFAULT_BUTTONS = {
"FIRST": PaginatorButton(emoji="⏮️", position=0, style=ButtonStyle.secondary),
"LEFT": PaginatorButton(emoji="◀️", position=1, style=ButtonStyle.secondary),
# "PAGE_INDICATOR": PaginatorButton(label="Page N/A / N/A", position=2, style=ButtonStyle.secondary),
"PAGE_INDICATOR": None,
"STOP": PaginatorButton(emoji="⏹️", position=2, style=ButtonStyle.danger),
"RIGHT": PaginatorButton(emoji="▶️", position=3, style=ButtonStyle.secondary),
"LAST": PaginatorButton(emoji="⏭️", position=4, style=ButtonStyle.secondary),
}
self._buttons: dict[str, PaginatorButton] = DEFAULT_BUTTONS.copy()
if buttons is not MISSING:
self._buttons.update(buttons)
self.timeout: Union[int, float] = timeout
# self._message: PossibleMessage = None # type: ignore # this cannot be None # filled in .send()
self.ctx = ctx # can be filled in .send()
self.interaction = interaction # can be filled in .send() and when the paginator is used
self.author_id: int = author_id
self.check = check if check is not MISSING else default_check
self.pages: Sequence[PossiblePage] = pages
self.per_page: int = per_page
self._max_pages_passed: int = len(pages)
self._should_always_show_stop_button: bool = always_show_stop_button
self._should_delete_after: bool = delete_after
self._should_disable_after: bool = disable_after
self._should_clear_buttons_after: bool = clear_buttons_after
self._current_page: int = 0
if per_page > self._max_pages_passed or per_page < 1:
raise ValueError( # nice try though
f"per_page ({per_page}) must be >= 1 or = len(pages) # >>> {self._max_pages_passed}"
)
total_pages, left_over = divmod(self._max_pages_passed, per_page)
if left_over:
total_pages += 1
self._max_pages = total_pages
self.__add_buttons()
self.__base_kwargs = {"content": None, "embeds": [], "files": [], "view": self}
def __reset_base_kwargs(self) -> None:
self.__base_kwargs = {"content": None, "embeds": [], "files": [], "view": self}
def __add_buttons(self) -> None:
if not self._max_pages > 1:
if self._should_always_show_stop_button:
if "STOP" not in self._buttons:
raise ValueError("STOP button is required if always_show_stop_button is True.")
name = "STOP"
button = self._buttons[name]
button.custom_id = f"{name.lower()}_button"
setattr(self, name, button)
self.add_item(button)
return
else:
super().stop()
return
_buttons: dict[str, PaginatorButton] = {
name: button for name, button in self._buttons.items() if button is not None
}
sorted_buttons = sorted(_buttons.items(), key=lambda b: b[1].position if b[1].position is not MISSING else 0)
for name, button in sorted_buttons:
button.custom_id = f"{name.lower()}_button"
setattr(self, name, button)
if button.custom_id == "page_indicator_button":
button.label = self.page_string
if self._max_pages <= 2:
button.disabled = True
if button.custom_id in ("first_button", "last_button") and self.max_pages <= 2:
continue
self.add_item(button)
self._update_buttons_state()
def _update_buttons_state(self) -> None:
button: PaginatorButton
for button in self.children: # type: ignore
if button.custom_id in ("page_indicator_button", "stop_button"):
if button.custom_id == "page_indicator_button":
button.label = self.page_string
else:
button.style = ButtonStyle.red
continue
elif button.custom_id in ("right_button", "last_button"):
button.disabled = self._current_page >= self.max_pages - 1
elif button.custom_id in ("left_button", "first_button"):
button.disabled = self._current_page <= 0
if not button.disabled:
button.style = ButtonStyle.green
elif button.disabled:
button.style = ButtonStyle.secondary
@property
def _context_or_interaction(self) -> Optional[Union[Context, Interaction]]:
if self.ctx is not MISSING:
return self.ctx
elif self.interaction is not MISSING:
return self.interaction
else:
return None
@property
def view_author(self) -> Optional[Union[discord.Member, discord.User, int]]:
if self.ctx is not MISSING:
return self.ctx.author
elif self.interaction is not MISSING:
return self.interaction.user
elif self.author_id is not MISSING:
return self.author_id
else:
return None
@property
def current_page(self) -> int:
return self._current_page
@current_page.setter
def current_page(self, value: int) -> None:
self._current_page = value
self._update_buttons_state()
@property
def max_pages(self) -> int:
return self._max_pages
@property
def page_string(self) -> str:
return f"Page {self.current_page + 1} / {self.max_pages}"
async def on_timeout(self) -> None:
await self.stop()
async def interaction_check(self, interaction: Interaction):
# Allow everyone if interaction.user or ctx or author_id is None.
if not self.view_author:
return True
author_id = self.view_author.id if not isinstance(self.view_author, int) else self.view_author
is_allowed = await maybe_coroutine(self.check, self, interaction.user.id, author_id)
if not is_allowed:
await interaction.response.send_message(
f"This paginator can only be controlled by <@{author_id}> and my owner(s), sorry!", ephemeral=True
)
return False
return is_allowed
async def _edit_message(self, interaction: Interaction = MISSING, /, **kwargs: Any) -> None:
kwargs["attachments"] = kwargs.pop("files", [])
if interaction is not MISSING:
self.interaction = interaction
respond = self.interaction.response.edit_message # type: ignore
if self.interaction.response.is_done(): # type: ignore
respond = self.message.edit if self.message else interaction.message.edit # type: ignore
await respond(**kwargs)
else:
await self.message.edit(**kwargs)
async def stop(self) -> None:
self.__reset_base_kwargs()
super().stop()
if self._should_delete_after:
await self.message.delete()
return
if self._should_clear_buttons_after:
await self._edit_message(view=None)
return
elif self._should_disable_after:
for button in self.children:
button.disabled = True # type: ignore
await self._edit_message(view=self)
return
def format_page(self, page: Union[PossiblePage, Sequence[PossiblePage]]) -> PossiblePage:
return page # type: ignore
def get_page(self, page_number: int) -> Union[PossiblePage, Sequence[PossiblePage]]:
if page_number < 0 or page_number >= self.max_pages:
self._current_page = 0
return self.pages[self._current_page]
if self.per_page == 1:
return self.pages[page_number]
else:
base = page_number * self.per_page
return self.pages[base : base + self.per_page]
async def get_kwargs_from_page(
self,
page: Union[PossiblePage, Sequence[PossiblePage]],
send_kwargs: dict[str, Any] = {},
skip_formatting: bool = False,
) -> dict[str, Any]:
if not skip_formatting:
self.__reset_base_kwargs()
page = await maybe_coroutine(self.format_page, page)
if send_kwargs:
for key, value in send_kwargs.items():
if key in ("embed", "file"):
self.__base_kwargs[f"{key}s"] = value
elif key == "view":
continue
else:
self.__base_kwargs.update(send_kwargs) # type: ignore
if self.per_page > 1 and isinstance(page, (list, tuple)):
raise ValueError("format_page must be used to format multiple pages.")
if isinstance(page, (list, tuple)):
_page: PossiblePage
for _page in page: # type: ignore
await self.get_kwargs_from_page(_page, skip_formatting=True) # type: ignore
if isinstance(page, str):
self.__base_kwargs["content"] = f"{page}\n\n{self.page_string}"
elif isinstance(page, dict):
self.__base_kwargs.update(page) # type: ignore
elif isinstance(page, Embed):
# self.__base_kwargs["embeds"].append(page)
# set_footer_on = self.__base_kwargs["embeds"][-1]
# if not set_footer_on.footer.text or set_footer_on.footer.text == self.page_string:
if not page.footer.text:
page.set_footer(text=self.page_string)
else:
# set_footer_on.set_footer(text=f"{set_footer_on.footer.text} | {self.page_string}")
if not "|" in page.footer.text:
page.set_footer(text=f"{page.footer.text} | {self.page_string}")
self.__base_kwargs["embeds"].append(page)
elif isinstance(page, File):
page.reset()
self.__base_kwargs["files"].append(page)
if not self.__base_kwargs["content"]:
self.__base_kwargs["content"] = self.page_string
else:
self.__base_kwargs["content"] += f"\n\n{self.page_string}"
return self.__base_kwargs
async def send(
self,
*,
ctx: Context = MISSING,
send_to: Messageable = MISSING,
interaction: Interaction = MISSING,
override_custom: bool = True,
**kwargs,
):
if interaction is not MISSING and ctx is not MISSING:
raise ValueError("ctx and interaction cannot be used together")
page = self.get_page(self.current_page)
send_kwargs = await self.get_kwargs_from_page(page, send_kwargs=kwargs if override_custom else {})
self.interaction = self.interaction if interaction is MISSING else interaction # type: ignore
self.ctx = self.ctx if ctx is MISSING else ctx # type: ignore
if send_to is not MISSING:
self.message = await send_to.send(**send_kwargs)
return self.message
elif self.interaction is not MISSING:
respond = self.interaction.response.send_message # type: ignore
if self.interaction.response.is_done(): # type: ignore
send_kwargs["wait"] = True # type: ignore
respond = self.interaction.followup.send # type: ignore
maybe_message = await respond(**send_kwargs)
if maybe_message:
self.message = maybe_message
return self.message
else:
self.message = await self.interaction.original_response() # type: ignore
return self.message
elif self.ctx is not MISSING:
self.message = await self.ctx.send(**send_kwargs) # type: ignore
return self.message
else:
raise ValueError("ctx or interaction or send_to must be provided")
# thank you so much Soheab for allowing me to use this paginator you made and putting in the work to do this :D (That's his github name so...)
class EmojiInfoEmbed(Paginator):
async def format_page(self, item: typing.Union[str, CustomEmoji]) -> discord.Embed:
DEFAULT_COLOUR = random.randint(0, 16777215)
invalid_emoji_embed = discord.Embed(
title="Invalid Emoji",
description=f"The following input could not be resolved to a valid emoji: `{item}`",
colour=DEFAULT_COLOUR,
)
# bail early if the emoji is invalid
if isinstance(item, str):
return invalid_emoji_embed
emoji_type = "Custom Emoji" if not item.unicode else "Default Emoji"
emoji_url = item.url if not item.unicode else f"https://emojiterra.com/{item.name.lower().replace(' ', '-')}/"
field_name = "Emoji Info" if not item.unicode else "Unicode Info"
main_embed = discord.Embed(
title=f'Emoji Info for "{item.emoji}" ({emoji_type})',
colour=DEFAULT_COLOUR,
)
main_embed.set_image(url=item.url)
global_text = (f"**Name:** {item.name}", f"**ID:** {item.id}", f"**URL:** [click here]({emoji_url})")
if item.unicode:
# provide different styles because why not
# twitter == twemoji
styles = [
f"[{style}]({item.with_style(style).url})"
for style in ("twitter", "whatsapp", "apple", "google", "samsung")
]
styles_text = "Styles: see how this emoji looks on different platforms: " + " | ".join(styles)
global_text += (f"**Code:** {item.unicode}", styles_text)
else:
global_text += (
f"**Created:** {discord.utils.format_dt(item.created_at, 'R')}",
f"**Animated:** {item.animated}",
)
main_embed.add_field(
name=field_name,
value="\n".join(global_text),
)
return main_embed
class MutualGuildsEmbed(Paginator):
def format_page(self, item):
embed = discord.Embed(title="Mutual Servers:", description=item, color=random.randint(0, 16777215))
return embed
class cdnViewer(Paginator):
def format_page(self, item):
embed = discord.Embed(title="CDN Viewer", description=f"Image ID: {item}", color=random.randint(0, 16777215))
embed.set_image(url=f"https://cdn.senarc.net/image/{item}.gif?opengraph_pass=true")
return embed
class ServersEmbed(Paginator):
def format_page(self, item):
embed = discord.Embed(title="Servers:", description=item, color=random.randint(0, 16777215))
return embed
class PrefixesEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(title="Usable Prefixes:", description=item, color=random.randint(0, 16777215))
return embed
class LeaderboardEmbed(Paginator):
async def format_page(self, item):
emby = discord.Embed(title="Leaderboard", color=15428885)
emby.set_author(
name=f"Leaderboard Requested by {self.ctx.author}", icon_url=(self.ctx.author.display_avatar.url)
)
for i, b, w in item:
emby.add_field(
name=f"**${i}:**", value=f"```yaml\nBank: ${b:,}\nWallet: ${w:,}\nTotal: ${b+w:,}```", inline=False
)
return emby
class RandomHistoryEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(title="Random History:", description=f"{item}", color=random.randint(0, 16777215))
embed.set_footer(text="Powered by Random quotes From: \nhttps://www.youtube.com/watch?v=xuCn8ux2gbs")
return embed
class TestersEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(title="Testing Users:", color=random.randint(0, 16777215))
embed.add_field(name="User ID:", value=f"{item}", inline=False)
return embed
class SusUsersEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(title="Users Deemed Suspicious by JDJG Inc. Official", color=random.randint(0, 16777215))
embed.add_field(
name=f"User ID : {item}", value=f"**Reason :** {self.ctx.bot.sus_users.get(item)}", inline=False
)
return embed
class BlacklistedUsersEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(title="Users Blacklisted by JDJG Inc. Official", color=random.randint(0, 16777215))
embed.add_field(
name=f"User ID : {item}", value=f"**Reason :** {self.ctx.bot.blacklisted_users.get(item)}", inline=False
)
return embed
class ErrorEmbed(Paginator):
async def format_page(self, item):
item = discord.utils.escape_markdown(item, as_needed=False, ignore_links=True)
return discord.Embed(title="Error", description=item, color=random.randint(0, 16777215))
class RtfmEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(title="Packages:", description=item, color=random.randint(0, 16777215))
return embed
class HelpEmbed(discord.Embed):
def __init__(self, ctx, *args, **kwargs):
super().__init__(title=f"{ctx.bot.user} Help Menu", *args, **kwargs)
self.set_author(name=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar)
class SendHelp(Paginator):
async def format_page(self, item):
emby = HelpEmbed(self.ctx, description=item, color=15428885)
return emby
class charinfoMenu(Paginator):
async def format_page(self, item):
return discord.Embed(description=item, color=random.randint(0, 16777215))
class InviteInfoEmbed(Paginator):
async def format_page(self, item):
if isinstance(item, discord.Invite):
if item.guild:
image = item.guild.icon.url if item.guild.icon else "https://i.imgur.com/3ZUrjUP.png"
guild = item.guild
guild_id = item.guild.id
if item.guild is None:
guild = "Group Chat"
image = "https://i.imgur.com/pQS3jkI.png"
guild_id = "Unknown"
embed = discord.Embed(title=f"Invite for {guild}:", color=random.randint(0, 16777215))
embed.set_author(name="Discord Invite Details:", icon_url=(image))
embed.add_field(name="Inviter:", value=f"{item.inviter}")
embed.add_field(name="User Count:", value=f"{item.approximate_member_count}")
embed.add_field(name="Active User Count:", value=f"{item.approximate_presence_count}")
embed.add_field(
name="Invite Channel",
value=f"{item.channel}\nChannel Mention : {'None' if isinstance(item.channel, discord.Object) else item.channel.mention}",
)
embed.set_footer(text=f"ID: {guild_id}\nInvite Code: {item.code}\nInvite Url: {item.url}")
if isinstance(item, str):
embed = discord.Embed(
title="Failed grabbing the invite code:",
description=f"Discord couldnt fetch the invite with the code {item}.",
color=random.randint(0, 16777215),
)
embed.set_footer(text="If this is a consistent problem please contact JDJG Inc. Official#3493 (jdjg)")
return embed
class GoogleEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(
title="Gooogle Search",
description=f"[{item.title}]({item.link}) \n{item.snippet}",
color=random.randint(0, 16777215),
)
if item.image:
embed.set_image(url=item.image)
embed.set_footer(
text=f"Google does some sketchy ad stuff, and descriptions from google are shown here, please be careful :D, thanks :D"
)
return embed
class ScanStatusEmbed(Paginator):
async def format_page(self, item):
ctx = self.ctx
embed = discord.Embed(title="Status Scan Complete!", description=item, color=15428885)
embed.set_author(name=f"Requested by {ctx.author}", icon_url=ctx.author.display_avatar)
return embed
def guild_join(guilds):
return "\n".join(map(str, guilds))
def grab_mutualguilds(ctx, user):
if isinstance(user, discord.ClientUser):
return ctx.author.mutual_guilds
mutual_guilds = set(ctx.author.mutual_guilds)
mutual_guilds2 = set(user.mutual_guilds)
return list(mutual_guilds.intersection(mutual_guilds2))
async def get_sus_reason(ctx, user):
sus_users = dict(await ctx.bot.db.fetch("SELECT * FROM SUS_USERS;"))
return sus_users.get(user.id)
class ScanGlobalEmbed(Paginator):
async def format_page(self, item):
embed = discord.Embed(color=random.randint(0, 16777215))
embed.set_author(name=f"{item}", icon_url=item.display_avatar.url)
embed.add_field(name="Shared Guilds:", value=f"{guild_join(grab_mutualguilds(self.ctx, item))}")
embed.set_footer(text=f"Sus Reason : {await get_sus_reason(self.ctx, item)}")
return embed
class TodoEmbed(Paginator):
def format_page(self, item):
embed = discord.Embed(
description=item, color=random.randint(0, 16777215), timestamp=self.ctx.message.created_at
)
embed.set_author(name=f"Todo Requested By {self.ctx.author}:", icon_url=self.ctx.author.display_avatar.url)
return embed
# this is using the paginator above, which is why It's not underneath the BasicButtons.
class dm_or_ephemeral(discord.ui.View):
def __init__(self, ctx, menu=None, **kwargs):
super().__init__(**kwargs)
self.ctx = ctx
self.menu = menu
@discord.ui.button(label="Ephemeral", style=discord.ButtonStyle.success, emoji="🕵️")
async def secretMessage(self, interaction: discord.Interaction, button: discord.ui.Button):
self.clear_items()
await interaction.response.edit_message(content="Will be sending you the information, ephemerally", view=self)
await self.menu.send(interaction=interaction, ephemeral=True)
@discord.ui.button(label="Direct", style=discord.ButtonStyle.success, emoji="📥")
async def dmMessage(self, interaction: discord.Interaction, button: discord.ui.Button):
self.clear_items()
await interaction.response.edit_message(content="Well be Dming you the paginator to view this info", view=self)
await self.menu.send(send_to=self.ctx.author)
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger, emoji="✖️")
async def denied(self, interaction: discord.Interaction, button: discord.ui.Button):
self.clear_items()
await interaction.response.edit_message(content=f"not sending the paginator to you", view=self)
async def interaction_check(self, interaction: discord.Interaction):
if self.ctx.author.id != interaction.user.id:
return await interaction.response.send_message(
content=f"You Can't Use that button, {self.ctx.author.mention} is the author of this message.",
ephemeral=True,
)
return True
async def on_timeout(self):
await self.message.edit(content="You took too long to respond, so I cancelled the paginator", view=None)
class TweetsDestinationHandler(discord.ui.View):
message: discord.Message
def __init__(
self,
*,
ctx: Context,
pagintor: TweetsPaginator,
):
super().__init__()
self.ctx: Context = ctx
self.pagintor: TweetsPaginator = pagintor
@discord.ui.button(label="Normal", style=discord.ButtonStyle.success, emoji="📄")
async def normal_message(self, interaction: discord.Interaction, button: discord.ui.Button):
self.pagintor.message = interaction.message # type: ignore
first_page = self.pagintor.get_page(0)
kwargs = await self.pagintor.get_kwargs_from_page(first_page)
await self.pagintor._edit_message(interaction, **kwargs)
@discord.ui.button(label="Ephemeral", style=discord.ButtonStyle.success, emoji="🕵️")
async def ephemeral_message(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(content="ephemerally sending Tweets", view=None)
await self.pagintor.send(interaction=interaction, ephemeral=True)
@discord.ui.button(label="Direct", style=discord.ButtonStyle.success, emoji="📥")
async def dm_message(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(content="Dming Tweets", view=None)
await self.pagintor.send(send_to=self.ctx.author)
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger, emoji="✖️")
async def cancel_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(content="I will not send you the tweets", view=None)
async def interaction_check(self, interaction: discord.Interaction):
if self.ctx.author.id != interaction.user.id:
return await interaction.response.send_message(
content=f"You Can't Use that button, {self.ctx.author.mention} is the author of this message.",
ephemeral=True,
)
return True
async def on_timeout(self):
try:
await self.message.edit(content="You took too long to respond, so I cancelled the paginator", view=None)
except discord.NotFound:
pass
class TweetsPaginator(Paginator):
class ShowImagesButton(Button):
view: "TweetsPaginator"
def __init__(self) -> None:
super().__init__(label="Show Images")
self.position: int = 4
self.medias: list[Media] = []
async def callback(self, interaction: Interaction) -> None:
pag = Paginator(
ctx=self.view.ctx,
pages=self.medias, # type: ignore
delete_after=self.view._should_delete_after,
always_show_stop_button=True,
)
pag.format_page = self.view.media_page_formater # type: ignore
await pag.send()
def __init__(
self,
*,
ctx: commands.Context,
tweets: TweepyTweet,
delete_after: bool = False,
author_name: str,
author_url: str,
author_icon: str,
**kwargs,
):
self.media_button = self.ShowImagesButton()
super().__init__(ctx=ctx, pages=tweets, delete_after=delete_after, **kwargs) # type: ignore
self.add_item(self.media_button)
self.author_name: str = author_name
self.author_url: str = author_url
self.author_icon: str = author_icon
self._update_buttons_state()
def media_page_formater(self, media: Media) -> Embed:
embed = discord.Embed(title=f"Images", description=f"url: {media.url}", color=0x1DA1F2)
embed.set_image(url=media.url)
return embed
def format_page(self, item: TweepyTweet) -> discord.Embed:
tweet_url = f"https://twitter.com/twitter/statuses/{item.id}"
embed = discord.Embed(
title=f"Tweet!", description=f"{item.text}", url=tweet_url, color=0x1DA1F2, timestamp=item.created_at
)
embed.set_author(name=self.author_name, url=self.author_url, icon_url=self.author_icon)
embed.set_footer(text=f"Requested by {self.ctx.author}\nJDJG does not own any of the content of the tweets")
embed.set_thumbnail(url="https://i.imgur.com/zpLkfHo.png")
return embed
def _update_buttons_state(self) -> None:
current_page = self.get_page(self.current_page)
self.media_button.medias = [x for x in current_page.media if x.url] # type: ignore
self.media_button.disabled = not self.media_button.medias # type: ignore
super()._update_buttons_state()
class UserInfoButton(discord.ui.Button):
def __init__(self, style, label: str, emoji, custom_id: str):
super().__init__(style=style, label=label, emoji=emoji, custom_id=custom_id)
async def callback(self, interaction: discord.Interaction):
guilds_list = grab_mutualguilds(self.view.ctx, self.view.user)
pag = commands.Paginator(prefix="", suffix="")
for g in guilds_list:
pag.add_line(f"{g}")
pages = pag.pages or ["None"]
menu = MutualGuildsEmbed(pages, ctx=self.view.ctx, delete_after=True)
for child in self.view.children:
if isinstance(child, (discord.Button, discord.ui.Button)):
self.view.remove_item(child)
if self.custom_id == "0":
await interaction.response.edit_message(
content="Will be sending you the information, ephemerally", view=self.view
)
await menu.send(interaction=interaction, ephemeral=True)
if self.custom_id == "1":
await interaction.response.edit_message(
content=f"Well be Dming you the paginator to view this info", view=self.view
)
await menu.send(send_to=self.view.ctx.author)
if self.custom_id == "2":
await interaction.response.edit_message(content=f"not sending the paginator to you", view=self.view)
def profile_converter(
_type: typing.Literal["badges", "mobile", "status", "web", "desktop", "mobile", "activity"],
_enum: typing.Union[
discord.Status, discord.UserFlags, discord.Activity, discord.BaseActivity, discord.Spotify, str
],
):
badges_emoji = {
UserFlags.staff: "<:discord_staff:1040719569116999680>",
UserFlags.partner: "<:discord_partner:1040723650162212985>",
UserFlags.hypesquad: "<:hypesquad:1040720248158040154>",
UserFlags.bug_hunter: "<:bug_hunter:1040719548128702544>",
UserFlags.hypesquad_bravery: "<:bravery:917747437450457128>",
UserFlags.hypesquad_brilliance: "<:brilliance:917747437509177384>",
UserFlags.hypesquad_balance: "<:balance:917747437412704366>",
UserFlags.early_supporter: "<:early_supporter:1040720490676895846>",
UserFlags.team_user: "🤖",
"system": "<:verifiedsystem1:848399959539843082><:verifiedsystem2:848399959241261088>",
UserFlags.bug_hunter_level_2: "<:bug_hunter_2:1040721850520571914>",
UserFlags.verified_bot: "<:verifiedbot1:848395737279496242><:verifiedbot2:848395736982749194>",
UserFlags.verified_bot_developer: "<:early_developer:1040719588385624074>",
UserFlags.discord_certified_moderator: "<:certified_moderator:1040719606102380687>",
UserFlags.bot_http_interactions: "<:bot_http_interactions:1040746049821757522>",
UserFlags.spammer: "⚠️",
UserFlags.active_developer: "<:active_dev:1040717993895800853>",
"bot": "<:bot:848395737138069514>",
}
status_emojis = {
discord.Status.online: "<:online:917747437882458122>",
discord.Status.dnd: "<:do_not_disturb:917747437756633088>",
discord.Status.idle: "<:away:917747437479821332>",
discord.Status.offline: "<:offline:917747437815349258>",
}
devices_emojis = {
"mobile": {
discord.Status.online: "<:mobile_online:917753163417813053>",
discord.Status.dnd: "<:mobile_dnd:917753135672459276>",
discord.Status.idle: "<:mobile_away:917753135672459275>",
discord.Status.offline: "<:mobile_offline:917752338532425739>",
},
"desktop": {
discord.Status.online: "<:desktop_online:917755694852235265>",
discord.Status.dnd: "<:desktop_dnd:917755694839656448>",
discord.Status.idle: "<:desktop_away:917755694902558790>",
discord.Status.offline: "<:desktop_offline:917755694948708402> ",
},
"web": {
discord.Status.online: "<:website_online:917753204396142623>",
discord.Status.dnd: "<:website_dnd:917753204396142622>",
discord.Status.idle: "<:website_away:917753204400336956> ",
discord.Status.offline: "<:website_offline:917752338574348289>",
},
}
activity_emojis = {
discord.ActivityType.unknown: "❓",
discord.ActivityType.playing: "🎮",
discord.ActivityType.streaming: "<:streaming:917747437920219156>",
discord.ActivityType.listening: "🎧",
discord.ActivityType.watching: "📺",
discord.Spotify: "<:spotify:1041484515748618343>",
discord.ActivityType.competing: "🏃",
discord.ActivityType.custom: "🎨",
}
dc = {"status": status_emojis, "badges": badges_emoji, "devices": devices_emojis, "activity": activity_emojis}
is_devices = False
if _type in ("mobile", "desktop", "web"):
is_devices = True
dict_to_use = dc.get(_type) if not is_devices else dc["devices"][_type]
if _type == "activity":
_enum = _enum.type if not isinstance(_enum, discord.Spotify) else _enum.__class__
emoji = dict_to_use.get(_enum)
if not emoji: