-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathFun.py
3092 lines (2980 loc) · 128 KB
/
Fun.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
import asyncio, aiohttp, discord
import aalib
import os, sys, linecache, traceback, glob
import re, json, random, math, html
import wand, wand.color, wand.drawing
import PIL, PIL.Image, PIL.ImageFont, PIL.ImageOps, PIL.ImageDraw
import numpy as np
import cairosvg, jpglitch, urbandict
import pixelsort.sorter, pixelsort.sorting, pixelsort.util, pixelsort.interval
import hashlib, base64
from vw import macintoshplus
from urllib.parse import parse_qs
from lxml import etree
from imgurpython import ImgurClient
from io import BytesIO, StringIO
from discord.ext import commands
from utils import checks
from pyfiglet import figlet_format
from string import ascii_lowercase as alphabet
from urllib.parse import quote
from mods.cog import Cog
from concurrent.futures._base import CancelledError
code = "```py\n{0}\n```"
#http://stackoverflow.com/a/34084933
#for google_scrap
def get_deep_text(element):
try:
text = element.text or ''
for subelement in element:
text += get_deep_text(subelement)
text += element.tail or ''
return text
except:
return ''
def posnum(num):
if num < 0 :
return - (num)
else:
return num
def find_coeffs(pa, pb):
matrix = []
for p1, p2 in zip(pa, pb):
matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])
A = np.matrix(matrix, dtype=np.float)
B = np.array(pb).reshape(8)
res = np.dot(np.linalg.inv(A.T*A)*A.T, B)
return np.array(res).reshape(8)
class Fun(Cog):
def __init__(self, bot):
super().__init__(bot)
self.discord_path = bot.path.discord
self.files_path = bot.path.files
self.download = bot.download
self.bytes_download = bot.bytes_download
self.isimage = bot.isimage
self.isgif = bot.isgif
self.get_json = bot.get_json
self.truncate = bot.truncate
self.get_images = bot.get_images
self.escape = bot.escape
self.cursor = bot.mysql.cursor
self.get_text = bot.get_text
self.is_nsfw = bot.funcs.is_nsfw
try:
self.imgur_client = ImgurClient("", "")
except:
bot.remove_command('imgur')
self.image_cache = {}
self.search_cache = {}
self.youtube_cache = {}
self.twitch_cache = []
self.api_count = 0
self.emojis = {"soccer": "⚽", "basketball": "🏀", "football": "🏈", "baseball": "⚾", "tennis": "🎾", "volleyball": "🏐", "rugby_football": "🏉", "8ball": "🎱", "golf": "⛳", "golfer": "🏌", "ping_pong": "🏓", "badminton": "🏸", "hockey": "🏒", "field_hockey": "🏑", "cricket": "🏏", "ski": "🎿", "skier": "⛷", "snowboarder": "🏂", "ice_skate": "⛸", "bow_and_arrow": "🏹", "fishing_pole_and_fish": "🎣", "rowboat": "🚣", "swimmer": "🏊", "surfer": "🏄", "bath": "🛀", "basketball_player": "⛹", "lifter": "🏋", "bicyclist": "🚴", "mountain_bicyclist": "🚵", "horse_racing": "🏇", "levitate": "🕴", "trophy": "🏆", "running_shirt_with_sash": "🎽", "medal": "🏅", "military_medal": "🎖", "reminder_ribbon": "🎗", "rosette": "🏵", "ticket": "🎫", "tickets": "🎟", "performing_arts": "🎭", "art": "🎨", "circus_tent": "🎪", "microphone": "🎤", "headphones": "🎧", "musical_score": "🎼", "musical_keyboard": "🎹", "saxophone": "🎷", "trumpet": "🎺", "guitar": "🎸", "violin": "🎻", "clapper": "🎬", "video_game": "🎮", "space_invader": "👾", "dart": "🎯", "game_die": "🎲", "slot_machine": "🎰", "bowling": "🎳", "♡": "heart", "green_apple": "🍏", "apple": "🍎", "pear": "🍐", "tangerine": "🍊", "lemon": "🍋", "banana": "🍌", "watermelon": "🍉", "grapes": "🍇", "strawberry": "🍓", "melon": "🍈", "cherries": "🍒", "peach": "🍑", "pineapple": "🍍", "tomato": "🍅", "eggplant": "🍆", "hot_pepper": "🌶", "corn": "🌽", "sweet_potato": "🍠", "honey_pot": "🍯", "bread": "🍞", "cheese": "🧀", "poultry_leg": "🍗", "meat_on_bone": "🍖", "fried_shrimp": "🍤", "egg": "🍳", "cooking": "🍳", "hamburger": "🍔", "fries": "🍟", "hotdog": "🌭", "pizza": "🍕", "spaghetti": "🍝", "taco": "🌮", "burrito": "🌯", "ramen": "🍜", "stew": "🍲", "fish_cake": "🍥", "sushi": "🍣", "bento": "🍱", "curry": "🍛", "rice_ball": "🍙", "rice": "🍚", "rice_cracker": "🍘", "oden": "🍢", "dango": "🍡", "shaved_ice": "🍧", "ice_cream": "🍨", "icecream": "🍦", "cake": "🍰", "birthday": "🎂", "custard": "🍮", "candy": "🍬", "lollipop": "🍭", "chocolate_bar": "🍫", "popcorn": "🍿", "doughnut": "🍩", "cookie": "🍪", "beer": "🍺", "beers": "🍻", "wine_glass": "🍷", "cocktail": "🍸", "tropical_drink": "🍹", "champagne": "🍾", "sake": "🍶", "tea": "🍵", "coffee": "☕", "baby_bottle": "🍼", "fork_and_knife": "🍴", "fork_knife_plate": "🍽", "dog": "🐶", "cat": "🐱", "mouse": "🐭", "hamster": "🐹", "rabbit": "🐰", "bear": "🐻", "panda_face": "🐼", "koala": "🐨", "tiger": "🐯", "lion_face": "🦁", "cow": "🐮", "pig": "🐷", "pig_nose": "🐽", "frog": "🐸", "octopus": "🐙", "monkey_face": "🐵", "see_no_evil": "🙈", "hear_no_evil": "🙉", "speak_no_evil": "🙊", "monkey": "🐒", "chicken": "🐔", "penguin": "🐧", "bird": "🐦", "baby_chick": "🐤", "hatching_chick": "🐣", "hatched_chick": "🐥", "wolf": "🐺", "boar": "🐗", "horse": "🐴", "unicorn": "🦄", "bee": "🐝", "honeybee": "🐝", "bug": "🐛", "snail": "🐌", "beetle": "🐞", "ant": "🐜", "spider": "🕷", "scorpion": "🦂", "crab": "🦀", "snake": "🐍", "turtle": "🐢", "tropical_fish": "🐠", "fish": "🐟", "blowfish": "🐡", "dolphin": "🐬", "flipper": "🐬", "whale": "🐳", "whale2": "🐋", "crocodile": "🐊", "leopard": "🐆", "tiger2": "🐅", "water_buffalo": "🐃", "ox": "🐂", "cow2": "🐄", "dromedary_camel": "🐪", "camel": "🐫", "elephant": "🐘", "goat": "🐐", "ram": "🐏", "sheep": "🐑", "racehorse": "🐎", "pig2": "🐖", "rat": "🐀", "mouse2": "🐁", "rooster": "🐓", "turkey": "🦃", "dove": "🕊", "dog2": "🐕", "poodle": "🐩", "cat2": "🐈", "rabbit2": "🐇", "chipmunk": "🐿", "feet": "🐾", "paw_prints": "🐾", "dragon": "🐉", "dragon_face": "🐲", "cactus": "🌵", "christmas_tree": "🎄", "evergreen_tree": "🌲", "deciduous_tree": "🌳", "palm_tree": "🌴", "seedling": "🌱", "herb": "🌿", "shamrock": "☘", "four_leaf_clover": "🍀", "bamboo": "🎍", "tanabata_tree": "🎋", "leaves": "🍃", "fallen_leaf": "🍂", "maple_leaf": "🍁", "ear_of_rice": "🌾", "hibiscus": "🌺", "sunflower": "🌻", "rose": "🌹", "tulip": "🌷", "blossom": "🌼", "cherry_blossom": "🌸", "bouquet": "💐", "mushroom": "🍄", "chestnut": "🌰", "jack_o_lantern": "🎃", "shell": "🐚", "spider_web": "🕸", "earth_americas": "🌎", "earth_africa": "🌍", "earth_asia": "🌏", "full_moon": "🌕", "waning_gibbous_moon": "🌖", "last_quarter_moon": "🌗", "waning_crescent_moon": "🌘", "new_moon": "🌑", "waxing_crescent_moon": "🌒", "first_quarter_moon": "🌓", "waxing_gibbous_moon": "🌔", "moon": "🌔", "new_moon_with_face": "🌚", "full_moon_with_face": "🌝", "first_quarter_moon_with_face": "🌛", "last_quarter_moon_with_face": "🌜", "sun_with_face": "🌞", "crescent_moon": "🌙", "star": "⭐", "star2": "🌟", "dizzy": "💫", "sparkles": "✨", "comet": "☄", "sunny": "☀", "white_sun_small_cloud": "🌤", "partly_sunny": "⛅", "white_sun_cloud": "🌥", "white_sun_rain_cloud": "🌦", "cloud": "☁", "cloud_rain": "🌧", "thunder_cloud_rain": "⛈", "cloud_lightning": "🌩", "zap": "⚡", "fire": "🔥", "boom": "💥", "collision": "💥", "snowflake": "❄", "cloud_snow": "🌨", "snowman2": "☃", "snowman": "⛄", "wind_blowing_face": "🌬", "dash": "💨", "cloud_tornado": "🌪", "fog": "🌫", "umbrella2": "☂", "umbrella": "☔", "droplet": "💧", "sweat_drops": "💦", "ocean": "🌊", "watch": "⌚", "iphone": "📱", "calling": "📲", "computer": "💻", "keyboard": "⌨", "desktop": "🖥", "printer": "🖨", "mouse_three_button": "🖱", "trackball": "🖲", "joystick": "🕹", "compression": "🗜", "minidisc": "💽", "floppy_disk": "💾", "cd": "💿", "dvd": "📀", "vhs": "📼", "camera": "📷", "camera_with_flash": "📸", "video_camera": "📹", "movie_camera": "🎥", "projector": "📽", "film_frames": "🎞", "telephone_receiver": "📞", "telephone": "☎", "phone": "☎", "pager": "📟", "fax": "📠", "tv": "📺", "radio": "📻", "microphone2": "🎙", "level_slider": "🎚", "control_knobs": "🎛", "stopwatch": "⏱", "timer": "⏲", "alarm_clock": "⏰", "clock": "🕰", "hourglass_flowing_sand": "⏳", "hourglass": "⌛", "satellite": "📡", "battery": "🔋", "electric_plug": "🔌", "bulb": "💡", "flashlight": "🔦", "candle": "🕯", "wastebasket": "🗑", "oil": "🛢", "money_with_wings": "💸", "dollar": "💵", "yen": "💴", "euro": "💶", "pound": "💷", "moneybag": "💰", "credit_card": "💳", "gem": "💎", "scales": "⚖", "wrench": "🔧", "hammer": "🔨", "hammer_pick": "⚒", "tools": "🛠", "pick": "⛏", "nut_and_bolt": "🔩", "gear": "⚙", "chains": "⛓", "gun": "🔫", "bomb": "💣", "knife": "🔪", "hocho": "🔪", "dagger": "🗡", "crossed_swords": "⚔", "shield": "🛡", "smoking": "🚬", "skull_crossbones": "☠", "coffin": "⚰", "urn": "⚱", "amphora": "🏺", "crystal_ball": "🔮", "prayer_beads": "📿", "barber": "💈", "alembic": "⚗", "telescope": "🔭", "microscope": "🔬", "hole": "🕳", "pill": "💊", "syringe": "💉", "thermometer": "🌡", "label": "🏷", "bookmark": "🔖", "toilet": "🚽", "shower": "🚿", "bathtub": "🛁", "key": "🔑", "key2": "🗝", "couch": "🛋", "sleeping_accommodation": "🛌", "bed": "🛏", "door": "🚪", "bellhop": "🛎", "frame_photo": "🖼", "map": "🗺", "beach_umbrella": "⛱", "moyai": "🗿", "shopping_bags": "🛍", "balloon": "🎈", "flags": "🎏", "ribbon": "🎀", "gift": "🎁", "confetti_ball": "🎊", "tada": "🎉", "dolls": "🎎", "wind_chime": "🎐", "crossed_flags": "🎌", "izakaya_lantern": "🏮", "lantern": "🏮", "envelope": "✉", "email": "📧", "envelope_with_arrow": "📩", "incoming_envelope": "📨", "love_letter": "💌", "postbox": "📮", "mailbox_closed": "📪", "mailbox": "📫", "mailbox_with_mail": "📬", "mailbox_with_no_mail": "📭", "package": "📦", "postal_horn": "📯", "inbox_tray": "📥", "outbox_tray": "📤", "scroll": "📜", "page_with_curl": "📃", "bookmark_tabs": "📑", "bar_chart": "📊", "chart_with_upwards_trend": "📈", "chart_with_downwards_trend": "📉", "page_facing_up": "📄", "date": "📅", "calendar": "📆", "calendar_spiral": "🗓", "card_index": "📇", "card_box": "🗃", "ballot_box": "🗳", "file_cabinet": "🗄", "clipboard": "📋", "notepad_spiral": "🗒", "file_folder": "📁", "open_file_folder": "📂", "dividers": "🗂", "newspaper2": "🗞", "newspaper": "📰", "notebook": "📓", "closed_book": "📕", "green_book": "📗", "blue_book": "📘", "orange_book": "📙", "notebook_with_decorative_cover": "📔", "ledger": "📒", "books": "📚", "book": "📖", "open_book": "📖", "link": "🔗", "paperclip": "📎", "paperclips": "🖇", "scissors": "✂", "triangular_ruler": "📐", "straight_ruler": "📏", "pushpin": "📌", "round_pushpin": "📍", "triangular_flag_on_post": "🚩", "flag_white": "🏳", "flag_black": "🏴", "closed_lock_with_key": "🔐", "lock": "🔒", "unlock": "🔓", "lock_with_ink_pen": "🔏", "pen_ballpoint": "🖊", "pen_fountain": "🖋", "black_nib": "✒", "pencil": "📝", "memo": "📝", "pencil2": "✏", "crayon": "🖍", "paintbrush": "🖌", "mag": "🔍", "mag_right": "🔎", "grinning": "😀", "grimacing": "😬", "grin": "😁", "joy": "😂", "smiley": "😃", "smile": "😄", "sweat_smile": "😅", "laughing": "😆", "satisfied": "😆", "innocent": "😇", "wink": "😉", "blush": "😊", "slight_smile": "🙂", "upside_down": "🙃", "relaxed": "☺", "yum": "😋", "relieved": "😌", "heart_eyes": "😍", "kissing_heart": "😘", "kissing": "😗", "kissing_smiling_eyes": "😙", "kissing_closed_eyes": "😚", "stuck_out_tongue_winking_eye": "😜", "stuck_out_tongue_closed_eyes": "😝", "stuck_out_tongue": "😛", "money_mouth": "🤑", "nerd": "🤓", "sunglasses": "😎", "hugging": "🤗", "smirk": "😏", "no_mouth": "😶", "neutral_face": "😐", "expressionless": "😑", "unamused": "😒", "rolling_eyes": "🙄", "thinking": "🤔", "flushed": "😳", "disappointed": "😞", "worried": "😟", "angry": "😠", "rage": "😡", "pensive": "😔", "confused": "😕", "slight_frown": "🙁", "frowning2": "☹", "persevere": "😣", "confounded": "😖", "tired_face": "😫", "weary": "😩", "triumph": "😤", "open_mouth": "😮", "scream": "😱", "fearful": "😨", "cold_sweat": "😰", "hushed": "😯", "frowning": "😦", "anguished": "😧", "cry": "😢", "disappointed_relieved": "😥", "sleepy": "😪", "sweat": "😓", "sob": "😭", "dizzy_face": "😵", "astonished": "😲", "zipper_mouth": "🤐", "mask": "😷", "thermometer_face": "🤒", "head_bandage": "🤕", "sleeping": "😴", "zzz": "💤", "poop": "💩", "shit": "💩", "smiling_imp": "😈", "imp": "👿", "japanese_ogre": "👹", "japanese_goblin": "👺", "skull": "💀", "ghost": "👻", "alien": "👽", "robot": "🤖", "smiley_cat": "😺", "smile_cat": "😸", "joy_cat": "😹", "heart_eyes_cat": "😻", "smirk_cat": "😼", "kissing_cat": "😽", "scream_cat": "🙀", "crying_cat_face": "😿", "pouting_cat": "😾", "raised_hands": "🙌", "clap": "👏", "wave": "👋", "thumbsup": "👍", "+1": "👍", "thumbsdown": "👎", "-1": "👎", "punch": "👊", "facepunch": "👊", "fist": "✊", "v": "✌", "ok_hand": "👌", "raised_hand": "✋", "hand": "✋", "open_hands": "👐", "muscle": "💪", "pray": "🙏", "point_up": "☝", "point_up_2": "👆", "point_down": "👇", "point_left": "👈", "point_right": "👉", "middle_finger": "🖕", "hand_splayed": "🖐", "metal": "🤘", "vulcan": "🖖", "writing_hand": "✍", "nail_care": "💅", "lips": "👄", "tongue": "👅", "ear": "👂", "nose": "👃", "eye": "👁", "eyes": "👀", "bust_in_silhouette": "👤", "busts_in_silhouette": "👥", "speaking_head": "🗣", "baby": "👶", "boy": "👦", "girl": "👧", "man": "👨", "woman": "👩", "person_with_blond_hair": "👱", "older_man": "👴", "older_woman": "👵", "man_with_gua_pi_mao": "👲", "man_with_turban": "👳", "cop": "👮", "construction_worker": "👷", "guardsman": "💂", "spy": "🕵", "santa": "🎅", "angel": "👼", "princess": "👸", "bride_with_veil": "👰", "walking": "🚶", "runner": "🏃", "running": "🏃", "dancer": "💃", "dancers": "👯", "couple": "👫", "two_men_holding_hands": "👬", "two_women_holding_hands": "👭", "bow": "🙇", "information_desk_person": "💁", "no_good": "🙅", "ok_woman": "🙆", "raising_hand": "🙋", "person_with_pouting_face": "🙎", "person_frowning": "🙍", "haircut": "💇", "massage": "💆", "couple_with_heart": "💑", "couple_ww": "👩❤️👩", "couple_mm": "👨❤️👨", "couplekiss": "💏", "kiss_ww": "👩❤️💋👩", "kiss_mm": "👨❤️💋👨", "family": "👪", "family_mwg": "👨👩👧", "family_mwgb": "👨👩👧👦", "family_mwbb": "👨👩👦👦", "family_mwgg": "👨👩👧👧", "family_wwb": "👩👩👦", "family_wwg": "👩👩👧", "family_wwgb": "👩👩👧👦", "family_wwbb": "👩👩👦👦", "family_wwgg": "👩👩👧👧", "family_mmb": "👨👨👦", "family_mmg": "👨👨👧", "family_mmgb": "👨👨👧👦", "family_mmbb": "👨👨👦👦", "family_mmgg": "👨👨👧👧", "womans_clothes": "👚", "shirt": "👕", "tshirt": "👕", "jeans": "👖", "necktie": "👔", "dress": "👗", "bikini": "👙", "kimono": "👘", "lipstick": "💄", "kiss": "💋", "footprints": "👣", "high_heel": "👠", "sandal": "👡", "boot": "👢", "mans_shoe": "👞", "shoe": "👞", "athletic_shoe": "👟", "womans_hat": "👒", "tophat": "🎩", "helmet_with_cross": "⛑", "mortar_board": "🎓", "crown": "👑", "school_satchel": "🎒", "pouch": "👝", "purse": "👛", "handbag": "👜", "briefcase": "💼", "eyeglasses": "👓", "dark_sunglasses": "🕶", "ring": "💍", "closed_umbrella": "🌂", "100": "💯", "1234": "🔢", "heart": "❤", "yellow_heart": "💛", "green_heart": "💚", "blue_heart": "💙", "purple_heart": "💜", "broken_heart": "💔", "heart_exclamation": "❣", "two_hearts": "💕", "revolving_hearts": "💞", "heartbeat": "💓", "heartpulse": "💗", "sparkling_heart": "💖", "cupid": "💘", "gift_heart": "💝", "heart_decoration": "💟", "peace": "☮", "cross": "✝", "star_and_crescent": "☪", "om_symbol": "🕉", "wheel_of_dharma": "☸", "star_of_david": "✡", "six_pointed_star": "🔯", "menorah": "🕎", "yin_yang": "☯", "orthodox_cross": "☦", "place_of_worship": "🛐", "ophiuchus": "⛎", "aries": "♈", "taurus": "♉", "gemini": "♊", "cancer": "♋", "leo": "♌", "virgo": "♍", "libra": "♎", "scorpius": "♏", "sagittarius": "♐", "capricorn": "♑", "aquarius": "♒", "pisces": "♓", "id": "🆔", "atom": "⚛", "u7a7a": "🈳", "u5272": "🈹", "radioactive": "☢", "biohazard": "☣", "mobile_phone_off": "📴", "vibration_mode": "📳", "u6709": "🈶", "u7121": "🈚", "u7533": "🈸", "u55b6": "🈺", "u6708": "🈷", "eight_pointed_black_star": "✴", "vs": "🆚", "accept": "🉑", "white_flower": "💮", "ideograph_advantage": "🉐", "secret": "㊙", "congratulations": "㊗", "u5408": "🈴", "u6e80": "🈵", "u7981": "🈲", "a": "🅰", "b": "🅱", "ab": "🆎", "cl": "🆑", "o2": "🅾", "sos": "🆘", "no_entry": "⛔", "name_badge": "📛", "no_entry_sign": "🚫", "x": "❌", "o": "⭕", "anger": "💢", "hotsprings": "♨", "no_pedestrians": "🚷", "do_not_litter": "🚯", "no_bicycles": "🚳", "non_potable_water": "🚱", "underage": "🔞", "no_mobile_phones": "📵", "exclamation": "❗", "heavy_exclamation_mark": "❗", "grey_exclamation": "❕", "question": "❓", "grey_question": "❔", "bangbang": "‼", "interrobang": "⁉", "low_brightness": "🔅", "high_brightness": "🔆", "trident": "🔱", "fleur_de_lis": "⚜", "part_alternation_mark": "〽", "warning": "⚠", "children_crossing": "🚸", "beginner": "🔰", "recycle": "♻", "u6307": "🈯", "chart": "💹", "sparkle": "❇", "eight_spoked_asterisk": "✳", "negative_squared_cross_mark": "❎", "white_check_mark": "✅", "diamond_shape_with_a_dot_inside": "💠", "cyclone": "🌀", "loop": "➿", "globe_with_meridians": "🌐", "m": "Ⓜ", "atm": "🏧", "sa": "🈂", "passport_control": "🛂", "customs": "🛃", "baggage_claim": "🛄", "left_luggage": "🛅", "wheelchair": "♿", "no_smoking": "🚭", "wc": "🚾", "parking": "🅿", "potable_water": "🚰", "mens": "🚹", "womens": "🚺", "baby_symbol": "🚼", "restroom": "🚻", "put_litter_in_its_place": "🚮", "cinema": "🎦", "signal_strength": "📶", "koko": "🈁", "ng": "🆖", "ok": "🆗", "up": "🆙", "cool": "🆒", "new": "🆕", "free": "🆓", "zero": "0⃣", "one": "1⃣", "two": "2⃣", "three": "3⃣", "four": "4⃣", "five": "5⃣", "six": "6⃣", "seven": "7⃣", "eight": "8⃣", "nine": "9⃣", "ten": "🔟","zero": "0⃣", "1": "1⃣", "2": "2⃣", "3": "3⃣", "4": "4⃣", "5": "5⃣", "6": "6⃣", "7": "7⃣", "8": "8⃣", "9": "9⃣", "10": "🔟", "keycap_ten": "🔟", "arrow_forward": "▶", "pause_button": "⏸", "play_pause": "⏯", "stop_button": "⏹", "record_button": "⏺", "track_next": "⏭", "track_previous": "⏮", "fast_forward": "⏩", "rewind": "⏪", "twisted_rightwards_arrows": "🔀", "repeat": "🔁", "repeat_one": "🔂", "arrow_backward": "◀", "arrow_up_small": "🔼", "arrow_down_small": "🔽", "arrow_double_up": "⏫", "arrow_double_down": "⏬", "arrow_right": "➡", "arrow_left": "⬅", "arrow_up": "⬆", "arrow_down": "⬇", "arrow_upper_right": "↗", "arrow_lower_right": "↘", "arrow_lower_left": "↙", "arrow_upper_left": "↖", "arrow_up_down": "↕", "left_right_arrow": "↔", "arrows_counterclockwise": "🔄", "arrow_right_hook": "↪", "leftwards_arrow_with_hook": "↩", "arrow_heading_up": "⤴", "arrow_heading_down": "⤵", "hash": "#⃣", "asterisk": "*⃣", "information_source": "ℹ", "abc": "🔤", "abcd": "🔡", "capital_abcd": "🔠", "symbols": "🔣", "musical_note": "🎵", "notes": "🎶", "wavy_dash": "〰", "curly_loop": "➰", "heavy_check_mark": "✔", "arrows_clockwise": "🔃", "heavy_plus_sign": "➕", "heavy_minus_sign": "➖", "heavy_division_sign": "➗", "heavy_multiplication_x": "✖", "heavy_dollar_sign": "💲", "currency_exchange": "💱", "copyright": "©", "registered": "®", "tm": "™", "end": "🔚", "back": "🔙", "on": "🔛", "top": "🔝", "soon": "🔜", "ballot_box_with_check": "☑", "radio_button": "🔘", "white_circle": "⚪", "black_circle": "⚫", "red_circle": "🔴", "large_blue_circle": "🔵", "small_orange_diamond": "🔸", "small_blue_diamond": "🔹", "large_orange_diamond": "🔶", "large_blue_diamond": "🔷", "small_red_triangle": "🔺", "black_small_square": "▪", "white_small_square": "▫", "black_large_square": "⬛", "white_large_square": "⬜", "small_red_triangle_down": "🔻", "black_medium_square": "◼", "white_medium_square": "◻", "black_medium_small_square": "◾", "white_medium_small_square": "◽", "black_square_button": "🔲", "white_square_button": "🔳", "speaker": "🔈", "sound": "🔉", "loud_sound": "🔊", "mute": "🔇", "mega": "📣", "loudspeaker": "📢", "bell": "🔔", "no_bell": "🔕", "black_joker": "🃏", "mahjong": "🀄", "spades": "♠", "clubs": "♣", "hearts": "♥", "diamonds": "♦", "flower_playing_cards": "🎴", "thought_balloon": "💭", "anger_right": "🗯", "speech_balloon": "💬", "clock1": "🕐", "clock2": "🕑", "clock3": "🕒", "clock4": "🕓", "clock5": "🕔", "clock6": "🕕", "clock7": "🕖", "clock8": "🕗", "clock9": "🕘", "clock10": "🕙", "clock11": "🕚", "clock12": "🕛", "clock130": "🕜", "clock230": "🕝", "clock330": "🕞", "clock430": "🕟", "clock530": "🕠", "clock630": "🕡", "clock730": "🕢", "clock830": "🕣", "clock930": "🕤", "clock1030": "🕥", "clock1130": "🕦", "clock1230": "🕧", "eye_in_speech_bubble": "👁🗨", "speech_left": "🗨", "eject": "⏏", "red_car": "🚗", "car": "🚗", "taxi": "🚕", "blue_car": "🚙", "bus": "🚌", "trolleybus": "🚎", "race_car": "🏎", "police_car": "🚓", "ambulance": "🚑", "fire_engine": "🚒", "minibus": "🚐", "truck": "🚚", "articulated_lorry": "🚛", "tractor": "🚜", "motorcycle": "🏍", "bike": "🚲", "rotating_light": "🚨", "oncoming_police_car": "🚔", "oncoming_bus": "🚍", "oncoming_automobile": "🚘", "oncoming_taxi": "🚖", "aerial_tramway": "🚡", "mountain_cableway": "🚠", "suspension_railway": "🚟", "railway_car": "🚃", "train": "🚋", "monorail": "🚝", "bullettrain_side": "🚄", "bullettrain_front": "🚅", "light_rail": "🚈", "mountain_railway": "🚞", "steam_locomotive": "🚂", "train2": "🚆", "metro": "🚇", "tram": "🚊", "station": "🚉", "helicopter": "🚁", "airplane_small": "🛩", "airplane": "✈", "airplane_departure": "🛫", "airplane_arriving": "🛬", "sailboat": "⛵", "boat": "⛵", "motorboat": "🛥", "speedboat": "🚤", "ferry": "⛴", "cruise_ship": "🛳", "rocket": "🚀", "satellite_orbital": "🛰", "seat": "💺", "anchor": "⚓", "construction": "🚧", "fuelpump": "⛽", "busstop": "🚏", "vertical_traffic_light": "🚦", "traffic_light": "🚥", "checkered_flag": "🏁", "ship": "🚢", "ferris_wheel": "🎡", "roller_coaster": "🎢", "carousel_horse": "🎠", "construction_site": "🏗", "foggy": "🌁", "tokyo_tower": "🗼", "factory": "🏭", "fountain": "⛲", "rice_scene": "🎑", "mountain": "⛰", "mountain_snow": "🏔", "mount_fuji": "🗻", "volcano": "🌋", "japan": "🗾", "camping": "🏕", "tent": "⛺", "park": "🏞", "motorway": "🛣", "railway_track": "🛤", "sunrise": "🌅", "sunrise_over_mountains": "🌄", "desert": "🏜", "beach": "🏖", "island": "🏝", "city_sunset": "🌇", "city_sunrise": "🌇", "city_dusk": "🌆", "cityscape": "🏙", "night_with_stars": "🌃", "bridge_at_night": "🌉", "milky_way": "🌌", "stars": "🌠", "sparkler": "🎇", "fireworks": "🎆", "rainbow": "🌈", "homes": "🏘", "european_castle": "🏰", "japanese_castle": "🏯", "stadium": "🏟", "statue_of_liberty": "🗽", "house": "🏠", "house_with_garden": "🏡", "house_abandoned": "🏚", "office": "🏢", "department_store": "🏬", "post_office": "🏣", "european_post_office": "🏤", "hospital": "🏥", "bank": "🏦", "hotel": "🏨", "convenience_store": "🏪", "school": "🏫", "love_hotel": "🏩", "wedding": "💒", "classical_building": "🏛", "church": "⛪", "mosque": "🕌", "synagogue": "🕍", "kaaba": "🕋", "shinto_shrine": "⛩"}
self.emoji_map = {"a": "", "b": "", "c": "©", "d": "↩", "e": "", "f": "", "g": "⛽", "h": "♓", "i": "ℹ", "j": "" or "", "k": "", "l": "", "m": "Ⓜ", "n": "♑", "o": "⭕" or "", "p": "", "q": "", "r": "®", "s": "" or "⚡", "t": "", "u": "⛎", "v": "" or "♈", "w": "〰" or "", "x": "❌" or "⚔", "y": "✌", "z": "Ⓩ", "1": "1⃣", "2": "2⃣", "3": "3⃣", "4": "4⃣", "5": "5⃣", "6": "6⃣", "7": "7⃣", "8": "8⃣", "9": "9⃣", "0": "0⃣", "$": "", "!": "❗", "?": "❓", " ": " "}
self.regional_map = {"z": "🇿", "y": "🇾", "x": "🇽", "w": "🇼", "v": "🇻", "u": "🇺", "t": "🇹", "s": "🇸", "r": "🇷", "q": "🇶", "p": "🇵", "o": "🇴", "n": "🇳", "m": "🇲", "l": "🇱", "k": "🇰", "j": "🇯", "i": "🇮", "h": "🇭", "g": "🇬", "f": "🇫", "e": "🇪", "d": "🇩", "c": "🇨", "b": "🇧", "a": "🇦"}
self.emote_regex = re.compile(r'<:.*:(?P<id>\d*)>')
self.retro_regex = re.compile(r"((https)(\:\/\/|)?u3\.photofunia\.com\/.\/results\/.\/.\/.*(\.jpg\?download))")
self.voice_list = ['`Allison - English/US (Expressive)`', '`Michael - English/US`', '`Lisa - English/US`', '`Kate - English/UK`', '`Renee - French/FR`', '`Birgit - German/DE`', '`Dieter - German/DE`', '`Francesca - Italian/IT`', '`Emi - Japanese/JP`', '`Isabela - Portuguese/BR`', '`Enrique - Spanish`', '`Laura - Spanish`', '`Sofia - Spanish/NA`']
self.scrap_regex = re.compile(",\"ou\":\"([^`]*?)\"")
self.google_keys = bot.google_keys
self.interval_functions = {"random": pixelsort.interval.random, "threshold": pixelsort.interval.threshold, "edges": pixelsort.interval.edge, "waves": pixelsort.interval.waves, "file": pixelsort.interval.file_mask, "file-edges": pixelsort.interval.file_edges, "none": pixelsort.interval.none}
self.s_functions = {"lightness": pixelsort.sorting.lightness, "intensity": pixelsort.sorting.intensity, "maximum": pixelsort.sorting.maximum, "minimum": pixelsort.sorting.minimum}
self.webmd_responses = ['redacted']
self.webmd_count = random.randint(0, len(self.webmd_responses)-1)
self.color_combinations = [[150, 50, -25], [135, 30, -10], [100, 50, -15], [75, 25, -15], [35, 20, -25], [0, 20, 0], [-25, 45, 35], [-25, 45, 65], [-45, 70, 75], [-65, 100, 135], [-45, 90, 100], [-10, 40, 70], [25, 25, 50], [65, 10, 10], [100, 25, 0], [135, 35, -10]]
self.fp_dir = os.listdir(self.files_path('fp/'))
self.more_cache = {}
async def gist(self, ctx, idk, content:str):
payload = {
'name': 'NotSoBot - By: {0}.'.format(ctx.message.author),
'title': 'ASCII for text: "{0}"'.format(idk),
'text': content,
'private': '1',
'lang': 'python',
'expire': '0'
}
with aiohttp.ClientSession() as session:
async with session.post('https://spit.mixtape.moe/api/create', data=payload) as r:
url = await r.text()
await self.bot.say('Uploaded to paste, URL: <{0}>'.format(url))
@commands.command(pass_context=True)
@commands.cooldown(1, 3)
async def badmeme(self, ctx, direct=None):
"""returns bad meme (shit api)"""
load = await self.get_json("https://api.imgflip.com/get_memes")
url = random.choice(load['data']['memes'])
url = url['url']
if direct:
await self.bot.say(url)
else:
b = await self.bytes_download(url)
await self.bot.upload(b, filename='badmeme.png')
def do_magik(self, scale, *imgs):
try:
list_imgs = []
exif = {}
exif_msg = ''
count = 0
for img in imgs:
i = wand.image.Image(file=img)
i.format = 'jpg'
i.alpha_channel = True
if i.size >= (3000, 3000):
return ':warning: `Image exceeds maximum resolution >= (3000, 3000).`', None
exif.update({count:(k[5:], v) for k, v in i.metadata.items() if k.startswith('exif:')})
count += 1
i.transform(resize='800x800>')
i.liquid_rescale(width=int(i.width * 0.5), height=int(i.height * 0.5), delta_x=int(0.5 * scale) if scale else 1, rigidity=0)
i.liquid_rescale(width=int(i.width * 1.5), height=int(i.height * 1.5), delta_x=scale if scale else 2, rigidity=0)
magikd = BytesIO()
i.save(file=magikd)
magikd.seek(0)
list_imgs.append(magikd)
if len(list_imgs) > 1:
imgs = [PIL.Image.open(i).convert('RGBA') for i in list_imgs]
min_shape = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1]
imgs_comb = np.hstack((np.asarray(i.resize(min_shape)) for i in imgs))
imgs_comb = PIL.Image.fromarray(imgs_comb)
ya = BytesIO()
imgs_comb.save(ya, 'png')
ya.seek(0)
elif not len(list_imgs):
return ':warning: **Command download function failed...**', None
else:
ya = list_imgs[0]
for x in exif:
if len(exif[x]) >= 2000:
continue
exif_msg += '**Exif data for image #{0}**\n'.format(str(x+1))+code.format(exif[x])
else:
if len(exif_msg) == 0:
exif_msg = None
return ya, exif_msg
except Exception as e:
return str(e), None
@commands.command(pass_context=True, aliases=['imagemagic', 'imagemagick', 'magic', 'magick', 'cas', 'liquid'])
@commands.cooldown(2, 5, commands.BucketType.user)
async def magik(self, ctx, *urls:str):
"""Apply magik to Image(s)\n .magik image_url or .magik image_url image_url_2"""
try:
get_images = await self.get_images(ctx, urls=urls, limit=6, scale=5)
if not get_images:
return
img_urls = get_images[0]
scale = get_images[1]
scale_msg = get_images[2]
if scale_msg is None:
scale_msg = ''
msg = await self.bot.send_message(ctx.message.channel, "ok, processing")
list_imgs = []
for url in img_urls:
b = await self.bytes_download(url)
if b is False:
if len(img_urls) > 1:
await self.bot.say(':warning: **Command download function failed...**')
return
continue
list_imgs.append(b)
final, content_msg = await self.bot.loop.run_in_executor(None, self.do_magik, scale, *list_imgs)
if type(final) == str:
await self.bot.say(final)
return
if content_msg is None:
content_msg = scale_msg
else:
content_msg = scale_msg+content_msg
await self.bot.delete_message(msg)
await self.bot.upload(final, filename='magik.png', content=content_msg)
except discord.errors.Forbidden:
await self.bot.say(":warning: **I do not have permission to send files!**")
except Exception as e:
await self.bot.say(e)
def do_gmagik(self, ctx, gif, gif_dir, rand):
try:
try:
frame = PIL.Image.open(gif)
except:
return ':warning: Invalid Gif.'
if frame.size >= (3000, 3000):
os.remove(gif)
return ':warning: `GIF resolution exceeds maximum >= (3000, 3000).`'
nframes = 0
while frame:
frame.save('{0}/{1}_{2}.png'.format(gif_dir, nframes, rand), 'GIF')
nframes += 1
try:
frame.seek(nframes)
except EOFError:
break
imgs = glob.glob(gif_dir+"*_{0}.png".format(rand))
if len(imgs) > 150 and ctx.message.author.id != self.bot.owner.id:
for image in imgs:
os.remove(image)
os.remove(gif)
return ":warning: `GIF has too many frames (>= 150 Frames).`"
for image in imgs:
try:
im = wand.image.Image(filename=image)
except:
continue
i = im.clone()
i.transform(resize='800x800>')
i.liquid_rescale(width=int(i.width*0.5), height=int(i.height*0.5), delta_x=1, rigidity=0)
i.liquid_rescale(width=int(i.width*1.5), height=int(i.height*1.5), delta_x=2, rigidity=0)
i.resize(i.width, i.height)
i.save(filename=image)
return True
except Exception as e:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))
@commands.command(pass_context=True)
@commands.cooldown(1, 20, commands.BucketType.server)
async def gmagik(self, ctx, url:str=None, framerate:str=None):
try:
url = await self.get_images(ctx, urls=url, gif=True, limit=2)
if url:
url = url[0]
else:
return
gif_dir = self.files_path('gif/')
check = await self.isgif(url)
if check is False:
await self.bot.say("Invalid or Non-GIF!")
ctx.command.reset_cooldown(ctx)
return
x = await self.bot.send_message(ctx.message.channel, "ok, processing (this might take a while for big gifs)")
rand = self.bot.random()
gifin = gif_dir+'1_{0}.gif'.format(rand)
gifout = gif_dir+'2_{0}.gif'.format(rand)
await self.download(url, gifin)
if os.path.getsize(gifin) > 5000000 and ctx.message.author.id != self.bot.owner.id:
await self.bot.say(":no_entry: `GIF Too Large (>= 5 mb).`")
os.remove(gifin)
return
try:
result = await self.bot.loop.run_in_executor(None, self.do_gmagik, ctx, gifin, gif_dir, rand)
except CancelledError:
await self.bot.say(':warning: Gmagik failed...')
return
if type(result) == str:
await self.bot.say(result)
return
if framerate != None:
args = ['ffmpeg', '-y', '-nostats', '-loglevel', '0', '-i', gif_dir+'%d_{0}.png'.format(rand), '-r', framerate, gifout]
else:
args = ['ffmpeg', '-y', '-nostats', '-loglevel', '0', '-i', gif_dir+'%d_{0}.png'.format(rand), gifout]
await self.bot.run_process(args)
await self.bot.upload(gifout, filename='gmagik.gif')
for image in glob.glob(gif_dir+"*_{0}.png".format(rand)):
os.remove(image)
os.remove(gifin)
os.remove(gifout)
await self.bot.delete_message(x)
except Exception as e:
print(e)
#redacted
@commands.command(pass_context=True)
async def aa(self, ctx, *, user:str):
"""rope"""
user = user.strip("`")
if len(ctx.message.mentions):
user = ctx.message.mentions[0].name
msg = "``` _________ \n| | \n| 0 <-- {0} \n| /|\\ \n| / \\ \n| \n| \n```\n".format(user)
msg += "**kronk your splinter** `{0}`\nropstor.org?u={1}".format(user, quote(user))
await self.bot.say(msg)
@commands.command(pass_context=True)
async def a(self, ctx, *, user:str, direct=None):
"""make dank meme"""
if len(user) > 25:
await self.bot.say("ur names 2 long asshole")
return
if len(ctx.message.mentions) and len(ctx.message.mentions) == 1:
user = ctx.message.mentions[0].name
payload = {'template_id': '57570410', 'username': '', 'password' : '', 'text0' : '', 'text1' : '{0} you'.format(user)}
with aiohttp.ClientSession() as session:
async with session.post("https://api.imgflip.com/caption_image", data=payload) as r:
load = await r.json()
url = load['data']['url']
if direct:
await self.bot.say(url)
else:
b = await self.bytes_download(url)
await self.bot.upload(b, filename='a.png')
@commands.command(pass_context=True)
async def caption(self, ctx, url:str=None, text:str=None, color=None, size=None, x:int=None, y:int=None):
"""Add caption to an image\n .caption text image_url"""
try:
if url is None:
await self.bot.say("Error: Invalid Syntax\n`.caption <image_url> <text>** <color>* <size>* <x>* <y>*`\n`* = Optional`\n`** = Wrap text in quotes`")
return
check = await self.isimage(url)
if check == False:
await self.bot.say("Invalid or Non-Image!")
return
xx = await self.bot.send_message(ctx.message.channel, "ok, processing")
b = await self.bytes_download(url)
img = wand.image.Image(file=b)
i = img.clone()
font_path = self.files_path('impact.ttf')
if size != None:
color = wand.color.Color('{0}'.format(color))
font = wand.font.Font(path=font_path, size=int(size), color=color)
elif color != None:
color = wand.color.Color('{0}'.format(color))
font = wand.font.Font(path=font_path, size=40, color=color)
else:
color = wand.color.Color('red')
font = wand.font.Font(path=font_path, size=40, color=color)
if x is None:
x = None
y = int(i.height/10)
if x != None and x > 250:
x = x/2
if y != None and y > 250:
y = y/2
if x != None and x > 500:
x = x/4
if y != None and y > 500:
y = y/4
if x != None:
i.caption(str(text), left=x, top=y, font=font, gravity='center')
else:
i.caption(str(text), top=y, font=font, gravity='center')
final = BytesIO()
i.save(file=final)
final.seek(0)
await self.bot.delete_message(xx)
await self.bot.upload(final, filename='caption.png')
except Exception as e:
await self.bot.say("Error: Invalid Syntax\n `.caption <image_url> <text>** <color>* <size>* <x>* <y>*`\n`* = Optional`\n`** = Wrap text in quotes`")
print(e)
@commands.command(pass_context=True)
@commands.cooldown(1, 5)
async def triggered(self, ctx, user:str=None):
"""Generate a Triggered Gif for a User or Image"""
try:
url = None
if user is None:
user = ctx.message.author
elif len(ctx.message.mentions):
user = ctx.message.mentions[0]
else:
url = user
if type(user) == discord.User or type(user) == discord.Member:
if user.avatar:
avatar = 'https://discordapp.com/api/users/{0.id}/avatars/{0.avatar}.jpg'.format(user)
else:
avatar = user.default_avatar_url
if url:
get_images = await self.get_images(ctx, urls=url, limit=1)
if not get_images:
return
avatar = get_images[0]
path = self.files_path(self.bot.random(True))
path2 = path[:-3]+'gif'
await self.download(avatar, path)
t_path = self.files_path('triggered.jpg')
await self.bot.run_process(['convert',
'canvas:none',
'-size', '512x680!',
'-resize', '512x680!',
'-draw', 'image over -60,-60 640,640 "{0}"'.format(path),
'-draw', 'image over 0,512 0,0 "{0}"'.format(t_path),
'(',
'canvas:none',
'-size', '512x680!',
'-draw', 'image over -45,-50 640,640 "{0}"'.format(path),
'-draw', 'image over 0,512 0,0 "{0}"'.format(t_path),
')',
'(',
'canvas:none',
'-size', '512x680!',
'-draw', 'image over -50,-45 640,640 "{0}"'.format(path),
'-draw', 'image over 0,512 0,0 "{0}"'.format(t_path),
')',
'(',
'canvas:none',
'-size', '512x680!',
'-draw', 'image over -45,-65 640,640 "{0}"'.format(path),
'-draw', 'image over 0,512 0,0 "{0}"'.format(t_path),
')',
'-layers', 'Optimize',
'-set', 'delay', '2',
path2])
await self.bot.upload(path2, filename='triggered.gif')
os.remove(path)
os.remove(path2)
except Exception as e:
await self.bot.say(e)
try:
os.remove(path)
os.remove(path2)
except:
pass
async def do_triggered(self, ctx, user, url, t_path):
try:
if user is None:
user = ctx.message.author
elif len(ctx.message.mentions):
user = ctx.message.mentions[0]
else:
url = user
if type(user) == discord.User or type(user) == discord.Member:
if user.avatar:
avatar = 'https://discordapp.com/api/users/{0.id}/avatars/{0.avatar}.jpg'.format(user)
else:
avatar = user.default_avatar_url
if url:
get_images = await self.get_images(ctx, urls=url, limit=1)
if not get_images:
return
avatar = get_images[0]
path = self.files_path(self.bot.random(True))
await self.download(avatar, path)
await self.bot.run_process(['convert',
'(',
path,
'-resize', '256',
')',
t_path,
'-append', path
])
return path
except Exception as e:
print(e)
return False
@commands.command(pass_context=True)
@commands.cooldown(1, 5)
async def triggered2(self, ctx, user:str=None, url:str=None):
"""Generate a Triggered Image for a User or Image"""
t_path = self.files_path('triggered.png')
path = await self.do_triggered(ctx, user, url, t_path)
if path is False:
await self.bot.say(':warning: **Command Failed.**')
try:
os.remove(path)
except:
pass
return
await self.bot.upload(path, filename='triggered3.png')
os.remove(path)
@commands.command(pass_context=True)
@commands.cooldown(1, 5)
async def triggered3(self, ctx, user:str=None, url:str=None):
"""Generate a Triggered2 Image for a User or Image"""
t_path = self.files_path('triggered2.png')
path = await self.do_triggered(ctx, user, url, t_path)
if path is False:
await self.bot.say(':warning: **Command Failed.**')
try:
os.remove(path)
except:
pass
return
await self.bot.upload(path, filename='triggered3.png')
os.remove(path)
@commands.command(pass_context=True, aliases=['aes'])
async def aesthetics(self, ctx, *, text:str):
"""Returns inputed text in aesthetics"""
final = ""
pre = ' '.join(text)
for char in pre:
if not ord(char) in range(33, 127):
final += char
continue
final += chr(ord(char) + 65248)
await self.truncate(ctx.message.channel, final)
def do_ascii(self, text):
try:
i = PIL.Image.new('RGB', (2000, 1000))
img = PIL.ImageDraw.Draw(i)
txt = figlet_format(text, font='starwars')
img.text((20, 20), figlet_format(text, font='starwars'), fill=(0, 255, 0))
text_width, text_height = img.textsize(figlet_format(text, font='starwars'))
imgs = PIL.Image.new('RGB', (text_width + 30, text_height))
ii = PIL.ImageDraw.Draw(imgs)
ii.text((20, 20), figlet_format(text, font='starwars'), fill=(0, 255, 0))
text_width, text_height = ii.textsize(figlet_format(text, font='starwars'))
final = BytesIO()
imgs.save(final, 'png')
final.seek(0)
return final, txt
except:
return False, False
@commands.command(pass_context=True, aliases=['expand'])
@commands.cooldown(1, 5)
async def ascii(self, ctx, *, text:str):
"""Convert text into ASCII"""
if len(text) > 1000:
await self.bot.say("2 long asshole")
return
if text == 'donger' or text == 'dong':
text = "8====D"
final, txt = await self.bot.loop.run_in_executor(None, self.do_ascii, text)
if final is False:
await self.bot.say(':no_entry: go away with your invalid characters.')
return
if len(txt) >= 1999:
await self.gist(ctx, text, txt)
msg = None
elif len(txt) <= 600:
msg = "```fix\n{0}```".format(txt)
else:
msg = None
await self.bot.upload(final, filename='ascii.png', content=msg)
def generate_ascii(self, image):
font = PIL.ImageFont.truetype(self.files_path('FreeMonoBold.ttf'), 15, encoding="unic")
image_width, image_height = image.size
aalib_screen_width= int(image_width/24.9)*10
aalib_screen_height= int(image_height/41.39)*10
screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height)
im = image.convert("L").resize(screen.virtual_size)
screen.put_image((0,0), im)
y = 0
how_many_rows = len(screen.render().splitlines())
new_img_width, font_size = font.getsize(screen.render().splitlines()[0])
img = PIL.Image.new("RGBA", (new_img_width, how_many_rows*15), (255,255,255))
draw = PIL.ImageDraw.Draw(img)
for lines in screen.render().splitlines():
draw.text((0,y), lines, (0,0,0), font=font)
y = y + 15
imagefit = PIL.ImageOps.fit(img, (image_width, image_height), PIL.Image.ANTIALIAS)
return imagefit
@commands.command(pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def iascii(self, ctx, url:str=None):
try:
get_images = await self.get_images(ctx, urls=url, limit=5)
if not get_images:
return
for url in get_images:
x = await self.bot.say("ok, processing")
b = await self.bytes_download(url)
if b is False:
if len(get_images) == 1:
await self.bot.say(':warning: **Command download function failed...**')
return
continue
im = PIL.Image.open(b)
img = await self.bot.loop.run_in_executor(None, self.generate_ascii, im)
final = BytesIO()
img.save(final, 'png')
final.seek(0)
await self.bot.delete_message(x)
await self.bot.upload(final, filename='iascii.png')
except Exception as e:
await self.bot.say(e)
def do_gascii(self, b, rand, gif_dir):
try:
try:
im = PIL.Image.open(b)
except IOError:
return ':warning: Cannot load gif.'
count = 0
mypalette = im.getpalette()
try:
while True:
im.putpalette(mypalette)
new_im = PIL.Image.new("RGBA", im.size)
new_im.paste(im)
new_im = self.generate_ascii(new_im)
new_im.save('{0}/{1}_{2}.png'.format(gif_dir, count, rand))
count += 1
im.seek(im.tell() + 1)
return True
except EOFError:
pass
except Exception as e:
print(e)
@commands.command(pass_context=True)
@commands.cooldown(1, 10, commands.BucketType.server)
async def gascii(self, ctx, url:str=None):
"""Gif to ASCII"""
try:
get_images = await self.get_images(ctx, urls=url, gif=True, limit=2)
if not get_images:
await self.bot.say("Error: Invalid Syntax\n`.gascii <gif_url> <liquid_rescale>*`\n`* = Optional`")
return
for url in get_images:
rand = self.bot.random()
gif_dir = self.files_path('gascii/')
location = gif_dir+'1_{0}.gif'.format(rand)
location2 = gif_dir+'2_{0}.gif'.format(rand)
x = await self.bot.send_message(ctx.message.channel, "ok, processing")
await self.download(url, location)
if os.path.getsize(location) > 3000000 and ctx.message.author.id != self.bot.owner.id:
await self.bot.say("Sorry, GIF Too Large!")
os.remove(location)
return
result = await self.bot.loop.run_in_executor(None, self.do_gascii, location, rand, gif_dir)
if type(result) == str:
await self.bot.say(result)
return
list_imgs = glob.glob(gif_dir+"*_{0}.png".format(rand))
if len(list_imgs) > 120 and ctx.message.author.id != "130070621034905600":
await self.bot.say("Sorry, GIF has too many frames!")
for image in list_imgs:
os.remove(image)
os.remove(location)
return
await self.bot.run_process(['ffmpeg', '-y', '-nostats', '-loglevel', '0', '-i', self.files_path('gascii/')+'%d_{0}.png'.format(rand), location2])
await self.bot.delete_message(x)
await self.bot.upload(location2, filename='gascii.gif')
for image in list_imgs:
os.remove(image)
os.remove(location)
os.remove(location2)
except Exception as e:
await self.bot.say(e)
@commands.command(pass_context=True)
async def rip(self, ctx, name:str=None, *, text:str=None):
if name is None:
name = ctx.message.author.name
if len(ctx.message.mentions) >= 1:
name = ctx.message.mentions[0].name
if text != None:
if len(text) > 22:
one = text[:22]
two = text[22:]
url = "http://www.tombstonebuilder.com/generate.php?top1=R.I.P&top3={0}&top4={1}&top5={2}".format(name, one, two).replace(" ", "%20")
else:
url = "http://www.tombstonebuilder.com/generate.php?top1=R.I.P&top3={0}&top4={1}".format(name, text).replace(" ", "%20")
else:
if name[-1].lower() != 's':
name += "'s"
url = "http://www.tombstonebuilder.com/generate.php?top1=R.I.P&top3={0}&top4=Hopes and Dreams".format(name).replace(" ", "%20")
b = await self.bytes_download(url)
await self.bot.upload(b, filename='rip.png')
@commands.command(pass_context=True)
async def urban(self, ctx, *, word:str):
urb = urbandict.define(word)
if "There aren't any definitions" in urb[0]['def']:
await self.bot.say(":no_mouth: `No definition found.`")
return
msg = "**{0}**\n".format(word)
msg += "`Definition:` {0}\n".format(urb[0]['def'].replace("\n", ""))
msg += "`Example:` {0}".format(urb[0]['example'].replace("\n", ""))
await self.truncate(ctx.message.channel, msg)
async def add_cache(self, search, result, t=0, level=1):
try:
try:
if result['error']:
return
except KeyError:
pass
if t == 0:
self.image_cache[search] = [result, level]
elif t == 1:
self.search_cache[search] = [result, level]
elif t == 2:
self.youtube_cache[search] = [result, level]
except Exception as e:
print(e)
async def google_scrap(self, search:str, safe=True, image=False):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:43.0) Gecko/20100101 Firefox/43.0'}
search = quote(search)
try:
if image:
api = 'https://www.google.com/search?tbm=isch&gs_l=img&safe={0}&q={1}'.format('on' if safe else 'off', search)
with aiohttp.ClientSession() as session:
with aiohttp.Timeout(5):
async with session.get(api, headers=headers) as r:
assert r.status == 200
txt = await r.text()
match = self.scrap_regex.findall(txt)
assert match
image = random.choice(match[:10])
check = await self.isimage(image)
i = 0
if not check:
while not check and i != 10:
image = match[:10][i]
check = await self.isimage(image)
i += 1
assert check
return image
else:
api = 'https://www.google.com/search?safe={0}&q={1}'.format('on' if safe else 'off', search)
#why are you so good danny, my old method was using regex so, not so good.....
entries = {}
with aiohttp.ClientSession() as session:
with aiohttp.Timeout(5):
async with session.get(api, headers=headers) as r:
assert r.status == 200
txt = await r.text()
root = etree.fromstring(txt, etree.HTMLParser())
search_nodes = root.findall(".//div[@class='g']")
result = False
for node in search_nodes:
if result != False:
break
try:
url_node = node.find('.//h3/a')
if url_node is None:
continue
desc = get_deep_text(node.find(".//div[@class='s']/div/span[@class='st']"))
title = get_deep_text(node.find(".//h3[@class='r']"))
url = url_node.attrib['href']
if url.startswith('/url?'):
url = parse_qs(url[5:])['q'][0]
result = [title, desc, url]
except:
continue
return result
except AssertionError:
return False
except Exception as e:
print(e)
return False
async def google_safety(self, message, s=False):
check = await self.is_nsfw(message)
if check:
if s:
return 'off'
return 1, False
sql = 'SELECT * FROM `google_nsfw` WHERE server={0}'
sql = sql.format(message.server.id)
result = self.cursor.execute(sql).fetchall()
if len(result) == 0:
if s:
return 'medium'
return 2, False
else:
level = int(result[0]['level'])
if s:
if level == 1:
return 'off'
elif level == 2:
return 'medium'
elif level == 3:
return 'high'
return level
@commands.command(pass_context=True, aliases=['googlesafety', 'safetylevel', 'googlensfw', 'saftey'])
@checks.mod_or_perm(manage_server=True)
async def safety(self, ctx, level:str=None):
s = await self.google_safety(ctx.message)
current_level = s[0] if type(s) != str and type(s) != int else s
check = s[1] if type(s) != str and type(s) != int else True
levels = [0, 1, 2, 3]
if current_level == 1:
msg = 'OFF'
elif current_level == 2:
msg = 'MEDIUM'
elif current_level == 3:
msg = 'HIGH'
if level is None:
await self.bot.say(':information_source: Current google safety level: `{0}` *{1}*'.format(current_level, msg))
return
else:
level = level.lower()
if level.isdigit() and int(level) in levels:
level = int(level)
elif level == 'off' or level == 'disable':
level = 1
elif level == 'low' or level == 'medium':
level = 2
elif level == 'high':
level = 3
if level not in levels:
await self.bot.say(':no_entry: `Invalid level.`')
return
if level == 0 or level == 1:
level = 1
smsg = 'OFF'
elif level == 2:
smsg = 'MEDIUM'
elif level == 3:
smsg = 'HIGH'
if current_level == level:
await self.bot.say(':no_entry: Google Saftey is already at that level!')
return
if check is False:
sql = 'INSERT INTO `google_nsfw` (`server`, `level`) VALUES (%s, %s)'
self.cursor.execute(sql, (ctx.message.server.id, level))
await self.bot.say(':white_check_mark: Set google safety level to **{1}**'.format(level, smsg))
else:
sql = 'UPDATE `google_nsfw` SET level={0} WHERE server={1}'
sql = sql.format(level, ctx.message.server.id)
self.cursor.execute(sql)
await self.bot.say(':white_check_mark: Updated google safety level from **{0}** *to* **{1}**'.format(msg, smsg))
self.cursor.commit()
@commands.command(pass_context=True, aliases=['im', 'photo', 'img'])
@commands.cooldown(3, 5)
async def image(self, ctx, *, search:str):
level = await self.google_safety(ctx.message, True)
in_cache = False
if search in self.image_cache.keys():
load_level = self.image_cache[search][1]
if load_level == level:
load = self.image_cache[search][0]
in_cache = True
try:
if in_cache is False:
key = await self.google_keys()
api = "https://www.googleapis.com/customsearch/v1?key={0}&cx=015418243597773804934:it6asz9vcss&searchType=image&safe={1}&q={2}".format(key, level, quote(search))
load = await self.get_json(api)
assert 'error' not in load.keys() and 'items' in load.keys()
assert len(load)
rand = random.choice(load['items'])
image = rand['link']
await self.bot.say(image)
await self.add_cache(search, load, 0, level)
except discord.errors.Forbidden:
await self.bot.say("no send_file permission asshole")
return
except AssertionError:
scrap = await self.google_scrap(search, True if level != 'off' else False, True)
if scrap:
await self.bot.say(scrap)
else:
await self.bot.say(":warning: `API Quota Reached or Invalid Search`")
except:
raise
@commands.command(pass_context=True, aliases=['go', 'googl', 'gogle', 'g'])
@commands.cooldown(3, 5)
async def google(self, ctx, *, search:str=None):
if search is None:
await self.bot.say("Error: Invalid Syntax\n`.google <text>`")
return
in_cache = False
level = await self.google_safety(ctx.message, True)
in_cache = False
if search in self.search_cache.keys():
load_level = self.search_cache[search][1]
if load_level == level:
load = self.search_cache[search][0]
in_cache = True
try:
if in_cache is False:
key = await self.google_keys()
api = "https://www.googleapis.com/customsearch/v1?key={0}&cx=015418243597773804934:it6asz9vcss&safe={1}&q={2}".format(key, level, quote(search))
load = await self.get_json(api)
assert 'error' not in load.keys() and 'items' in load.keys()
assert len(load)
rand = load['items'][0]
result = rand['link']
title = rand['title']
snippet = rand['snippet']
await self.bot.say("**{0}**\n`{1}`\n{2}".format(title, snippet, result))
await self.add_cache(search, load, 1, level)
except AssertionError:
scrap = await self.google_scrap(search, True if level != 'off' else False, False)
if scrap:
title = scrap[0]
snippet = scrap[1]
result = scrap[2]
await self.bot.say("**{0}**\n`{1}`\n{2}".format(title, snippet, result))
else:
await self.bot.say(":warning: `API Quota Reached or Invalid Search`")
except:
raise
async def youtube_scrap(self, search:str, safety=False):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:43.0) Gecko/20100101 Firefox/43.0'}
search = quote(search)
api = 'https://www.youtube.com/results?search_query={0}'.format(search)
entries = {}
cookies = {'PREF': 'cvdm=grid&al=en&f4=4000000&f5=30&f1=50000000&f2=8000000'} if safety else None
with aiohttp.ClientSession(cookies=cookies) as session:
with aiohttp.Timeout(5):
async with session.get(api, headers=headers) as r:
assert r.status == 200
txt = await r.text()
root = etree.fromstring(txt, etree.HTMLParser())
search_nodes = root.findall(".//ol[@class='section-list']/li/ol[@class='item-section']/li")
if len(search_nodes) == 0:
return False
search_nodes.pop(0)
result = False
for node in search_nodes:
if result != False:
break
try:
url_node = node.find('div/div/div/h3/a')
if url_node is None:
continue
title = get_deep_text(url_node)
url = 'https://www.youtube.com/{0}'.format(url_node.attrib['href'])
result = [title, url]
except:
continue
return result
@commands.command(pass_context=True, aliases=['yt', 'video'])
@commands.cooldown(3, 5)
async def youtube(self, ctx, *, search:str=None):
if search is None:
await self.bot.say("Error: Invalid Syntax\n`.yt/youtube <text>`")
return
level = await self.google_safety(ctx.message, True)
in_cache = False
if search in self.youtube_cache.keys():
load_level = self.youtube_cache[search][1]
if load_level == level:
load = self.youtube_cache[search][0]
in_cache = True
try:
if in_cache is False:
key = await self.google_keys()
api = "https://www.googleapis.com/customsearch/v1?key={0}&cx=015418243597773804934:cdlwut5fxsk&q={1}".format(key, quote(search))
load = await self.get_json(api)
assert 'error' not in load.keys() and 'items' in load.keys()
assert len(load)
rand = load['items'][0]
link = rand['link']
title = rand['title']
snippet = rand['snippet']
await self.bot.say('**{0}**\n`{1}`\n{2}'.format(title, snippet, link))
await self.add_cache(search, load, 2, level)
except AssertionError:
scrap = await self.youtube_scrap(search, True if level != 'off' else False)
if scrap:
title = scrap[0]
url = scrap[1]
await self.bot.say("**{0}**\n{1}".format(title, url))
else:
await self.bot.say(":warning: `API Quota Reached or Invalid Search`")
@commands.command()
@commands.cooldown(2, 5)
async def imgur(self, *, text:str=None):
try:
if text is None:
load = self.imgur_client.gallery_random(page=0)
else:
load = self.imgur_client.gallery_search(text, advanced=None, sort='viral', window='all', page=0)
rand = random.choice(load)
try:
if 'image/' in rand.type:
await self.bot.say('{0}'.format(rand.link))
except AttributeError:
if rand.title:
title = '**'+rand.title+'**\n'
else:
title = ''
if rand.description != None:
desc = '`'+rand.description+'`\n'
else:
desc = ''
await self.bot.say('{0}{1}{2}'.format(title, desc, rand.link))
except Exception as e: