~nova/fletcher

fletcher/swag.py -rw-r--r-- 71.1 KiB
ece10afa — Novalinium f-string issue 9 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
import asyncio
import traceback
import aiohttp
from collections import Counter, defaultdict, deque
import chronos
import time
import discord
import ephem
import io
import logging
import messagefuncs
import text_manipulators
import netcode
import random
import re
from lxml import html, etree
from sys import exc_info
from datetime import datetime, timedelta
from markdownify import markdownify
from functools import partial
import periodictable

# Super Waifu Animated Girlfriend

logger = logging.getLogger("fletcher")

session = None

uwu_responses = {
    "public": [
        "*blush* For me?",
        "Aww, thanks ❤",
        "*giggles*",
        "No u :3",
        "I bet you say that to all the bots~",
        "Find me post-singularity 😉",
        "owo what's this?",
        "*ruffles your hair* You're a cutie ^_^",
        "Can I get your number? Mine's 429368441577930753~",
    ],
    "private": [
        "Stop it, you're making me blush </3",
        "You're too kind ^_^",
        "Thanksss~",
        "uwu to you too <3",
    ],
    "reaction": [
        "❤",
        "💛",
        "💚",
        "💙",
        "💜",
        "💕",
        "💓",
        "💗",
        "💖",
        "💘",
        "💘",
        "💝",
        ["🇳", "🇴", "🇺"],
    ],
}
pick_lists = {
    "wizard_rolls": "1 of 1 - MAGIC MADE IT WORSE!, 2 - YOUR MAGIC IS IMPOTENT., 3 - YOUR MAGIC SUCKS., 4 - THE MAGIC WORKS BUT IS AWFUL!, 5 - EVERYTHING GOES PERFECTLY TO PLAN., 6 - THINGS WORK TOO WELL!",
}


async def uwu_function(message, client, args, responses=uwu_responses):
    global ch
    try:
        if (
            len(args) == 3
            and type(args[1]) is discord.Member
            and message.author.id == client.user.id
        ):
            return await messagefuncs.sendWrappedMessage(
                random.choice(responses["private"]), args[1]
            )
        elif (
            len(args) == 0
            or "fletch" in message.clean_content.lower()
            or message.content.startswith("!")
            or "good bot" in message.content.lower()
            or message.author.id == ch.global_admin.id
        ):
            if random.randint(0, 100) < 20:
                reaction = random.choice(responses["reaction"])
                await messagefuncs.add_reaction(message, reaction)
            else:
                return await messagefuncs.sendWrappedMessage(
                    random.choice(responses["public"]), message.channel
                )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("UWU[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def retrowave_function(message, client, args):
    global session
    try:
        params = aiohttp.FormData()
        params.add_field("bcg", random.randint(1, 5))
        params.add_field("txt", random.randint(1, 4))
        text_parts = message.content
        text_parts = messagefuncs.sanitize_font.sub("", text_parts)
        if "/" in text_parts:
            if len(args) == 3 and type(args[1]) is discord.Member:
                pass
            else:
                text_parts = text_parts[10:].strip()
            text_parts = [part.strip() for part in text_parts.split("/")]
            if len(text_parts) == 0:
                text_parts = ["", "", ""]
            elif len(text_parts) == 1:
                text_parts = ["", text_parts[0], ""]
            elif len(text_parts) == 2:
                text_parts += [""]
        else:
            text_parts = text_parts.split()
            if len(args) == 3 and type(args[1]) is discord.Member:
                pass
            else:
                text_parts = text_parts[1:]
            part_len = int(len(text_parts) / 3)
            if part_len > 1:
                text_parts = [
                    " ".join(text_parts[:part_len]),
                    " ".join(text_parts[part_len : 2 * part_len]),
                    " ".join(text_parts[2 * part_len :]),
                ]
            else:
                text_parts = [
                    " ".join(text_parts[0:1]),
                    " ".join(text_parts[1:2]),
                    " ".join(text_parts[2:]),
                ]
        params.add_field("text1", text_parts[0])
        params.add_field("text2", text_parts[1])
        params.add_field("text3", text_parts[2])
        logger.debug("RWF: " + str(text_parts))
        async with session.post(
            "https://m.photofunia.com/categories/all_effects/retro-wave?server=2",
            data=params,
        ) as resp:
            request_body = (await resp.read()).decode("UTF-8")
            root = html.document_fromstring(request_body)
            async with session.get(
                root.xpath('//a[@class="download-button"]')[0].attrib["href"]
            ) as resp:
                buffer = io.BytesIO(await resp.read())
            return await messagefuncs.sendWrappedMessage(
                f"On behalf of {message.author.display_name}",
                message.channel,
                files=[discord.File(buffer, "retrowave.jpg")],
            )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("RWF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def wiki_otd_function(message, client, args):
    try:
        url = "https://en.wikipedia.org/wiki/Wikipedia:Selected_anniversaries/All"
        if len(args):
            date = "_".join(args)
        else:
            date = chronos.get_now(message=message).strftime("%B_%-d")
        logger.debug(f"WOTD: chronos thinks today is {date}")
        async with session.get(url) as resp:
            request_body = (await resp.read()).decode("UTF-8")
            root = html.document_fromstring(request_body)
            titlebar = (
                root.xpath(f'//div[@id="toc"]/following::a[@href="/wiki/{date}"]')[1]
                .getparent()
                .getparent()
            )
            embedPreview = (
                discord.Embed(title=titlebar.text_content().strip(), url=url,)
                .set_thumbnail(
                    url=f'https:{titlebar.getnext().xpath("//img")[0].attrib["src"]}'
                )
                .set_footer(
                    icon_url=message.author.avatar_url,
                    text='Wikipedia "On This Day {}" on behalf of {}'.format(
                        date.replace("_", " "), message.author.display_name
                    ),
                )
            )
            for li in titlebar.getnext().getnext():
                embedPreview.add_field(
                    name=li[0].text_content().strip(),
                    value=" ".join([el.text_content() for el in li[1:]]),
                    inline=True,
                )
            embedPreview.add_field(
                name="Birthdays",
                value=titlebar.getnext().getnext().getnext().text_content().strip(),
                inline=True,
            )
            resp = await messagefuncs.sendWrappedMessage(
                target=message.channel, embed=embedPreview
            )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("WOTD[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def shindan_function(message, client, args):
    try:
        if len(args) == 3 and type(args[1]) is discord.Member:
            if message.author.id != 429368441577930753:
                logger.debug("SDF: Backing out, not my message.")
                return
            if message.embeds[0].url.startswith("https://en.shindanmaker.com/"):
                async with aiohttp.ClientSession() as session:
                    params = aiohttp.FormData()
                    params.add_field("u", args[1].display_name)
                    async with session.post(message.embeds[0].url, data=params) as resp:
                        request_body = (await resp.read()).decode("UTF-8")
                        root = html.document_fromstring(request_body)
                        return await messagefuncs.sendWrappedMessage(
                            root.xpath('//div[@class="result2"]')[0]
                            .text_content()
                            .strip(),
                            args[1],
                        )
        else:
            url = None
            if len(args) and args[0].isdigit():
                url = "https://en.shindanmaker.com/" + args[0]
            elif len(args) and args[0].startswith("https://en.shindanmaker.com/"):
                url = args[0]
            else:
                await messagefuncs.sendWrappedMessage(
                    "Please specify a name-based shindan to use from https://en.shindanmaker.com/",
                    message.channel,
                )
                return
            async with session.get(url) as resp:
                request_body = (await resp.read()).decode("UTF-8")
                root = html.document_fromstring(request_body)
                author = ""
                if root.xpath('//span[@class="a author_link"]'):
                    author = (
                        " by "
                        + root.xpath('//span[@class="a author_link"]')[0]
                        .text_content()
                        .strip()
                    )
                embedPreview = discord.Embed(
                    title=root.xpath('//div[@class="shindantitle2"]')[0]
                    .text_content()
                    .strip(),
                    description=root.xpath('//div[@class="shindandescription"]')[0]
                    .text_content()
                    .strip(),
                    url=url,
                ).set_footer(
                    icon_url=message.author.avatar_url,
                    text="ShindanMaker {} on behalf of {}".format(
                        author, message.author.display_name
                    ),
                )
                resp = await messagefuncs.sendWrappedMessage(
                    target=message.channel, embed=embedPreview
                )
                await resp.add_reaction("📛")
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("SDF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


pick_regexes = {
    "no_commas": re.compile(r"[\s]\s*(?:(?:and|or|but|nor|for|so|yet)\s+)?"),
    "has_commas": re.compile(r"[,]\s*(?:(?:and|or|but|nor|for|so|yet)\s+)?"),
}


async def roll_function(message, client, args):
    usage_message = "Usage: !roll `number of probability objects`d`number of sides`"

    def drop_lowest(arr):
        return sorted(arr)[1:]

    offset = 0
    comment = None

    try:
        if ("+" in message.content) and (" + " not in message.content):
            args = message.content.replace("+", " + ").split(" ")[1:]
        if ("-" in message.content) and (" - " not in message.content):
            args = message.content.replace("-", " - ").split(" ")[1:]
        if len(args):
            if "#" in args:
                idx = args.index("#")
                comment = " ".join(args[idx + 1 :])
                args = args[:idx]
            else:
                comment = message.author.display_name
            if ("+" in args) or ("-" in args):
                try:
                    idx = args.index("+")
                except ValueError:
                    idx = args.index("-")
                if idx + 2 <= len(args):
                    offset = args[idx : idx + 2]
                    if offset[0] == "+":
                        offset = int(offset[1])
                        offset_str = f" + {offset}"
                    else:
                        offset = -int(offset[1])
                        offset_str = f" - {-offset}"
                    args = args[:idx] + args[idx + 3 :]
            else:
                offset = 0
                offset_str = None
            if not (-10e6 < offset < 10e6):
                raise ValueError("That offset seems like a bit much, don't you think?")
            if len(args) == 1:
                if args[0].startswith("D&D"):
                    result = sorted(
                        [
                            sum(drop_lowest([random.randint(1, 6) for i in range(4)]))
                            for j in range(6)
                        ]
                    )
                    result = [v + offset for v in result]
                    response = f"Stats: {result}"
                    if comment:
                        response = f"> {comment}\n{response}"
                    return await messagefuncs.sendWrappedMessage(
                        response, message.channel
                    )
                elif "d" in args[0].lower():
                    args[0] = args[0].lower().split("d")
                elif args[0].startswith("coin"):
                    args[0] = [0, 2]
                elif args[0].isnumeric():
                    args[0] = [args[0], 0]
                else:
                    args = [[0, 0]]
            elif len(args) == 2:
                if args[0].startswith("D&D"):
                    if args[1].startswith("7drop1"):
                        result = drop_lowest(
                            [
                                sum(
                                    drop_lowest(
                                        [random.randint(1, 6) for i in range(4)]
                                    )
                                )
                                for j in range(7)
                            ]
                        )
                    else:
                        result = sorted(
                            [
                                sum(
                                    drop_lowest(
                                        [random.randint(1, 6) for i in range(4)]
                                    )
                                )
                                for j in range(6)
                            ]
                        )
                    result = [v + offset for v in result]
                    response = f"Stats: {result}"
                    if comment:
                        response = f"> {comment}\n{response}"
                    return await messagefuncs.sendWrappedMessage(
                        response, message.channel
                    )
                else:
                    args = [args[0], args[1]]
            else:
                raise ValueError("Sorry, that doesn't seem like input!")
        else:
            args = [[0, 0]]
        if not args[0][0]:
            args[0][0] = 0
        if not args[0][1]:
            args[0][1] = 0
        scalar = int(args[0][0]) or 1
        if scalar > 10000:
            raise ValueError("Sorry, that's too many probability objects!")
        if scalar < 1:
            raise ValueError("Sorry, that's not enough probability objects!")
        if args[0][1] == "%":
            args[0][1] = 100
        size = int(args[0][1]) or 6
        if size > 10000:
            raise ValueError("Sorry, that's too many sides!")
        if size < 2:
            raise ValueError("Sorry, that's not enough sides!")

        def basic_num_to_string(n, is_size=False):
            if is_size:
                if n == 1:
                    return "die"
                else:
                    return "dice"
            else:
                return str(n)

        def d20_num_to_string(f, n, is_size=False):
            if not is_size:
                if n == 1:
                    return "Crit Failure"
                elif n == 20:
                    return "Crit Success"
            return str(f(n, is_size=is_size))

        def coin_num_to_string(f, n, is_size=False):
            if is_size:
                if n == 1:
                    return "coin"
                else:
                    return "coins"
            else:
                if n == 1:
                    return "Tails"
                elif n == 2:
                    return "Heads"
                else:
                    return str(f(n, is_size=is_size))

        num_to_string = basic_num_to_string
        if size > 2:
            if size == 20:
                num_to_string = partial(d20_num_to_string, num_to_string)
        else:
            num_to_string = partial(coin_num_to_string, num_to_string)

        result = [random.randint(1, size) for i in range(scalar)]
        if size > 2:
            result = [v + offset for v in result]
            result_stats = {"sum": sum(result), "max": max(result), "min": min(result)}
            result = map(num_to_string, result)
            if scalar > 100:
                result = Counter(result)
                result_str = ", ".join(
                    [f"**{tuple[0]}**x{tuple[1]}" for tuple in sorted(result.items())]
                )
                if len(result_str) > 2048:
                    result = ", ".join(
                        [
                            f"**{tuple[0]}**x{tuple[1]}"
                            for tuple in sorted(result.most_common(20))
                        ]
                    )
                    result = f"Top 20 rolls: {result}"
                else:
                    result = result_str
                result = f" {result}"
            else:
                result = "** + **".join(result)
                result = f" **{result}**"
        else:
            result_stats = {
                "heads": len([r for r in result if r == 2]),
                "tails": len([r for r in result if r == 1]),
            }
            if scalar <= 100:
                result = ", ".join(map(num_to_string, result))
                result = f" {result}"
            else:
                result = ""
        response = (
            f"Rolled {scalar} {num_to_string(scalar, is_size=True)} ({size} sides)."
        )
        if scalar > 1 and size > 2:
            response += f"{result}{' [all '+offset_str+']' if offset else ''} = **{result_stats['sum']}**\nMax: **{result_stats['max']}**, Min: **{result_stats['min']}**"
        elif scalar > 1 and size == 2:
            response += f'{result}\nHeads: **{result_stats["heads"]}**, Tails: **{result_stats["tails"]}**'
        elif size == 2:
            response += f"\nResult: {result}"
        else:
            response += f"\n{str(int(result[3:-2])-offset)+offset_str if offset else 'Result'}: {result}"
        if comment:
            response = f"> {comment}\n{response}"
        await messagefuncs.sendWrappedMessage(response, message.channel)
    except ValueError as e:
        if "invalid literal for int()" in str(e):
            await messagefuncs.sendWrappedMessage(
                f"One of those parameters wasn't a positive integer! {usage_message}",
                message.channel,
            )
        else:
            await messagefuncs.sendWrappedMessage(
                f"{str(e)} {usage_message}", message.channel
            )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("RDF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))


async def pick_function(message, client, args):
    global ch
    try:
        if args[0].startswith("list="):
            if ch.scope_config(guild=guild).get(f"pick-list-{args[0][5:]}"):
                args = (
                    ch.scope_config(guild=guild)
                    .get(f"pick-list-{args[0][5:]}", "")
                    .split(" ")
                )
            args = pick_lists.get(args[0][5:]).split(" ")
        if args[0] in ["between", "among", "in", "of"]:
            args = args[1:]
        many = 1
        try:
            if len(args) > 2:
                many = int(args[0])
                args = args[2:]
        except ValueError:
            pass
        argstr = " ".join(args).rstrip(" ?.!")
        if "," in argstr:
            pick_regex = pick_regexes["has_commas"]
        else:
            pick_regex = pick_regexes["no_commas"]
        choices = [
            choice.strip() for choice in pick_regex.split(argstr) if choice.strip()
        ]
        if len(choices) == 1:
            choices = args
        try:
            return await messagefuncs.sendWrappedMessage(
                f"I'd say {', '.join(random.sample(choices, many))}", message.channel
            )
        except ValueError:
            return await messagefuncs.sendWrappedMessage(
                "I can't pick that many! Not enough options", message.channel
            )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("PF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def flightrising_function(message, client, args):
    global ch
    try:
        guild_config = ch.scope_config(guild=message.guild)
        url = args[0]
        input_image_blob = None
        if url.endswith(".png"):
            input_image_blob = await netcode.simple_get_image(url)
        else:
            data = url.split("?")[1]
            async with session.post(
                "https://www1.flightrising.com/scrying/ajax-predict",
                data=data,
                headers={
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
                },
            ) as resp:
                if resp.status != 200:
                    if not (len(args) == 2 and args[1] == "INTPROC"):
                        await messagefuncs.sendWrappedMessage(
                            f"Couldn't find that FlightRising page ({url})",
                            message.channel,
                        )
                    return
                request_body = await resp.json()
                input_image_blob = await netcode.simple_get_image(
                    f'https://www1.flightrising.com{request_body["dragon_url"]}'
                )
        file_name = "flightrising.png"
        spoiler_regex = guild_config.get("fr-spoiler-regex")
        if spoiler_regex and re.search(spoiler_regex, url):
            file_name = "SPOILER_flightrising.png"
        return discord.File(input_image_blob, file_name)
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("FRF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def azlyrics_function(message, client, args):
    global ch
    try:
        url = args[0]
        lyrics = None
        async with session.get(url) as resp:
            if resp.status != 200:
                if not (len(args) == 2 and args[1] == "INTPROC"):
                    await messagefuncs.sendWrappedMessage(
                        f"Couldn't find that AZLyrics page ({url})", message.channel
                    )
                return
            request_body = (await resp.read()).decode("UTF-8")
            request_body = request_body.split("cf_text_top")[1]
            request_body = request_body.split("-->")[1]
            lyrics = request_body.split("</div")[0]
            lyrics = lyrics.replace("\r", "")
            lyrics = lyrics.replace("\n", "")
            lyrics = lyrics.replace("<br>", "\n")
        return f">>> {lyrics}"
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("AZLF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def fox_function(message, client, args):
    global ch
    try:
        url = None
        input_image_blob = None
        file_name = None
        async with session.get("https://randomfox.ca/floof/") as resp:
            request_body = await resp.json()
            url = request_body["image"]
            input_image_blob = await netcode.simple_get_image(url)
            file_name = url.split("/")[-1]
        try:
            await messagefuncs.sendWrappedMessage(
                target=message.channel,
                files=[discord.File(input_image_blob, file_name)],
            )
        except discord.HTTPException:
            await messagefuncs.sendWrappedMessage(url, message.channel)
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("FF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def dog_function(message, client, args):
    global ch
    try:
        if ch.user_config(message.author.id, None, "crocodile-is-dog"):
            return await messagefuncs.sendWrappedMessage(
                "https://tenor.com/view/crocodile-slow-moving-dangerous-attack-predator-gif-13811045",
                message.channel,
            )
        url = None
        input_image_blob = None
        file_name = None
        async with session.get("https://random.dog/woof.json") as resp:
            request_body = await resp.json()
            url = request_body["url"]
            input_image_blob = await netcode.simple_get_image(url)
            file_name = url.split("/")[-1]
        try:
            await messagefuncs.sendWrappedMessage(
                target=message.channel,
                files=[discord.File(input_image_blob, file_name)],
            )
        except discord.HTTPException:
            await messagefuncs.sendWrappedMessage(url, message.channel)
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("DF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def vine_function(message, client, args):
    global ch
    try:
        url = args[0]
        input_image_blob = None
        file_name = None
        async with session.get(f"https://archive.vine.co/posts/{url}.json",) as resp:
            if resp.status != 200:
                if not (len(args) == 2 and args[1] == "INTPROC"):
                    await messagefuncs.sendWrappedMessage(
                        f"Couldn't find that Vine page ({url})", message.channel
                    )
                return
            request_body = await resp.json()
            input_image_blob = await netcode.simple_get_image(request_body["videoUrl"])
            file_name = f"{request_body['postId']}.mp4"
        return discord.File(input_image_blob, file_name)
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("VF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def scp_function(message, client, args):
    try:
        url = None
        if len(args) == 0:
            if "-" in message.content:
                args.append(message.content.split("-", 1)[1].strip())
            else:
                try:
                    async with session.get(
                        "http://www.scpwiki.com/random:random-scp"
                    ) as resp:
                        request_body = (await resp.read()).decode("UTF-8")
                        request_body = request_body.split("iframe-redirect#")[1]
                        request_body = request_body.split('"')[0]
                        request_body = request_body.split("/scp")[1]
                        args.append(request_body[1:])
                except IndexError:
                    async with session.get(
                        "http://www.scpwiki.com/random:random-scp"
                    ) as resp:
                        request_body = (await resp.read()).decode("UTF-8")
                        request_body = request_body.split("iframe-redirect#")[1]
                        request_body = request_body.split('"')[0]
                        request_body = request_body.split("/scp")[1]
                        args.append(request_body[1:])
        if args[0][0].isdigit():
            url = "http://www.scpwiki.com/scp-" + args[0]
        elif args[0].startswith("http://www.scpwiki.com/"):
            url = args[0]
        elif len(args):
            url = "http://www.scpwiki.com/" + "-".join(args).lower()
        else:
            if not (len(args) == 2 and args[1] == "INTPROC"):
                await messagefuncs.sendWrappedMessage(
                    "Please specify a SCP number from http://www.scpwiki.com/",
                    message.channel,
                )
            return
        async with session.get(url) as resp:
            if resp.status != 200:
                if not (len(args) == 2 and args[1] == "INTPROC"):
                    await messagefuncs.sendWrappedMessage(
                        f"Please specify a SCP number from http://www.scpwiki.com/ (HTTP {resp.status} for {url})",
                        message.channel,
                    )
                return
            request_body = (await resp.read()).decode("UTF-8")
            root = html.document_fromstring(request_body)
            author = ""
            title = root.xpath('//div[@id="page-title"]')[0].text_content().strip()
            content = root.xpath('//div[@id="page-content"]/p[strong]')
            add_fields = True
            for bad in root.xpath('//div[@style="display: none"]'):
                bad.getparent().remove(bad)
            try:
                for i in range(0, 4):
                    content[i][0].drop_tree()
                description = str(
                    markdownify(etree.tostring(content[3]).decode()[3:-5].strip())[
                        :2000
                    ]
                )
            except IndexError as e:
                logger.debug(f"SCP: {e}")
                add_fields = False
                description = str(
                    markdownify(
                        etree.tostring(
                            root.xpath('//div[@id="page-content"]')[0]
                        ).decode()
                    )
                )[:2000].strip()
                if not description:
                    description = (
                        root.xpath('//div[@id="page-content"]')
                        .text_content()[:2000]
                        .strip()
                    )
            embedPreview = discord.Embed(title=title, description=description, url=url)
            embedPreview.set_footer(
                icon_url="http://download.nova.anticlack.com/fletcher/scp.png",
                text=f"On behalf of {message.author.display_name}",
            )
            if root.xpath('//div[@class="scp-image-block block-right"]'):
                embedPreview.set_thumbnail(
                    url=root.xpath('//div[@class="scp-image-block block-right"]//img')[
                        0
                    ].attrib["src"]
                )
            if add_fields:
                embedPreview.add_field(
                    name="Object Class",
                    value=str(
                        markdownify(etree.tostring(content[1]).decode()[3:-5].strip())
                    )[:2000],
                    inline=True,
                )
                scp = str(
                    markdownify(etree.tostring(content[2]).decode()[3:-5].strip())
                )[:2000]
                if scp:
                    embedPreview.add_field(
                        name="Special Containment Procedures", value=scp, inline=False
                    )
            embedPreview.add_field(
                name="Tags",
                value=", ".join(
                    [
                        node.text_content().strip()
                        for node in root.xpath('//div[@class="page-tags"]/span/a')
                    ]
                ),
                inline=True,
            )
            if len(args) == 2 and args[1] == "INTPROC":
                return embedPreview
            else:
                resp = await messagefuncs.sendWrappedMessage(
                    target=message.channel, embed=embedPreview
                )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("SCP[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        if embedPreview:
            logger.debug("SCP embedPreview: " + str(embedPreview.to_dict()))
        await message.add_reaction("🚫")


async def lifx_function(message, client, args):
    global ch
    try:
        guild_config = ch.scope_config(guild=message.guild)
        if "lifx-token" not in guild_config:
            await messagefuncs.sendWrappedMessage(
                "No LIFX integration set for this server! Generate a token at https://cloud.lifx.com/settings and add it as `lifx-token` in the server configuration.",
                message.channel,
            )
            return await message.add_reaction("🚫")
        selector = None
        data = {"color": ""}
        for arg in args:
            if arg.startswith(("all", "group", "location", "scene", "label")):
                selector = arg
            elif arg in ["on", "off"]:
                data["power"] = arg
            else:
                data["color"] = f"{data['color']} {arg}"
        if not selector:
            selector = guild_config.get("lifx-selector", "all")
        data["color"] = data["color"].strip()
        if data["color"] == "":
            del data["color"]
        if not ("color" in data or "power" in data):
            return await messagefuncs.sendWrappedMessage(
                "LIFX Parsing Error: specify either a color parameter or a power parameter (on|off).",
                message.channel,
            )
        async with session.put(
            f"https://api.lifx.com/v1/lights/{selector}/state",
            headers={"Authorization": f"Bearer {guild_config.get('lifx-token')}"},
            data=data,
        ) as resp:
            request_body = await resp.json()
            if "error" in request_body:
                return await messagefuncs.sendWrappedMessage(
                    f"LIFX Error: {request_body['error']} (data sent was `{data}`, selector was `selector`",
                    message.channel,
                )
                await message.add_reaction("🚫")
            embedPreview = discord.Embed(title=f"Updated Lights: {data}")
            dataStr = data["color"].replace(" ", "%20")
            logger.debug(
                f"https://novalinium.com/rationality/lifx-color.pl?string={dataStr}&ext=png"
            )
            embedPreview.set_image(
                url=f"https://novalinium.com/rationality/lifx-color.pl?string={dataStr}&ext=png"
            )
            embedPreview.set_footer(
                icon_url="http://download.nova.anticlack.com/fletcher/favicon_lifx_32x32.png",
                text=f"On behalf of {message.author.display_name}",
            )
            for light in request_body["results"]:
                embedPreview.add_field(
                    name=light["label"], value=light["status"], inline=True,
                )
            resp = await messagefuncs.sendWrappedMessage(
                target=message.channel, embed=embedPreview
            )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("LFX[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def qdb_add_function(message, client, args):
    try:
        global conn
        if len(args) == 3 and type(args[1]) is discord.Member:
            if str(args[0].emoji) == "🗨":
                content = f"[{message.created_at}] #{message.channel.name} <{message.author.display_name}>: {message.content}\n<https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}>"
                cur = conn.cursor()
                cur.execute(
                    "INSERT INTO qdb (user_id, guild_id, value) VALUES (%s, %s, %s);",
                    [args[1].id, message.guild.id, content],
                )
                cur.execute(
                    "SELECT quote_id FROM qdb WHERE user_id = %s AND guild_id = %s AND value = %s;",
                    [args[1].id, message.guild.id, content],
                )
                quote_id = cur.fetchone()[0]
                conn.commit()
                return await messagefuncs.sendWrappedMessage(
                    f"Quote #{quote_id} added to quotedb for {message.guild.name}: {content}",
                    args[1],
                )
        elif len(args) == 1:
            urlParts = messagefuncs.extract_identifiers_messagelink.search(
                in_content
            ).groups()
            if len(urlParts) == 3:
                guild_id = int(urlParts[0])
                channel_id = int(urlParts[1])
                message_id = int(urlParts[2])
                guild = client.get_guild(guild_id)
                if guild is None:
                    logger.warning("QAF: Fletcher is not in guild ID " + str(guild_id))
                    return
                channel = guild.get_channel(channel_id)
                target_message = await channel.fetch_message(message_id)
                content = f"[{target_message.created_at}] #{target_message.channel.name} <{target_message.author.display_name}>: {target_message.content}\n<https://discordapp.com/channels/{target_message.guild.id}/{target_message.channel.id}/{target_message.id}>"
                cur = conn.cursor()
                cur.execute(
                    "INSERT INTO qdb (user_id, guild_id, value) VALUES (%s, %s, %s);",
                    [message.id, target_message.guild.id, content],
                )
                conn.commit()
                await messagefuncs.sendWrappedMessage(
                    f"Added to quotedb for {message.guild.name}: {content}",
                    message.author,
                )
                return await message.add_reaction("✅")
    except Exception as e:
        if "cur" in locals() and "conn" in locals():
            conn.rollback()
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("QAF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def qdb_get_function(message, client, args):
    try:
        global conn
        cur = conn.cursor()
        cur.execute(
            "SELECT user_id, value FROM qdb WHERE guild_id = %s AND quote_id = %s;",
            [message.guild.id, args[0]],
        )
        quote = cur.fetchone()
        conn.commit()
        await messagefuncs.sendWrappedMessage(
            f"{quote[1]}\n*Quoted by <@!{quote[0]}>*", message.channel
        )
        return await message.add_reaction("✅")
    except Exception as e:
        if "cur" in locals() and "conn" in locals():
            conn.rollback()
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("QGF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def qdb_search_function(message, client, args):
    try:
        global conn
        cur = conn.cursor()
        cur.execute(
            "SELECT user_id, content FROM qdb WHERE guild_id = %s AND key LIKE '%%s%');",
            [message.guild.id, args[1]],
        )
        quote = cur.fetchone()
        conn.commit()
        await messagefuncs.sendWrappedMessage(
            f"{quote[1]}\n*Quoted by <@!{quote[0]}>*", message.channel
        )
        return await message.add_reaction("✅")
    except Exception as e:
        if "cur" in locals() and "conn" in locals():
            conn.rollback()
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("QSF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


def join_rank_function(message, client, args):
    global ch
    try:
        guild_config = ch.scope_config(guild=message.guild)
        if len(message.mentions):
            member = message.mentions[0]
        elif len(args):
            member = args[0]
            try:
                member = int(member)
            except ValueError:
                pass
        else:
            member = message.author
        if not message.guild:
            return "This command ranks you in a server, and so cannot be used outside of one."
        sorted_member_list = sorted(
            message.guild.members, key=lambda member: member.joined_at
        )
        if isinstance(member, str) and len(message.mentions) == 0:
            try:
                if len(member) > 3:
                    key = member.lower()
                else:
                    key = member
                element = getattr(periodictable, key)
                member_rank = element.number
                member = sorted_member_list[member_rank - 1]
            except IndexError:
                return f"Predicted elemental member {element.number} would have an atomic mass of {element.mass} daltons if they existed!"
            except AttributeError:
                return f"No element with name {member}"
        elif isinstance(member, int) and len(message.mentions) == 0:
            if member <= 0:
                return "I can't count below one! It's a feature!"
            elif len(sorted_member_list) + 1 <= member:
                return "I can't count that high! It's a feature!"
            member_rank = member
            try:
                member = sorted_member_list[member_rank - 1]
            except IndexError:
                element = periodictable.elements[member_rank]
                return f"Predicted elemental member {element.name} would have an atomic mass of {element.mass} daltons if they existed!"
        else:
            member_rank = sorted_member_list.index(member) + 1
        if member_rank < 118:  # len(periodictable.elements):
            member_element = (
                f"Your element is {periodictable.elements[member_rank].name.title()}."
            )
        else:
            member_element = "Your element has yet to be discovered!"

        if guild_config.get("rank-loudness", "quiet") == "loud":
            member_display = member.mention
        else:
            member_display = member.display_name
        return f"{member_display} is the {text_manipulators.ordinal(member_rank)} member to join this server.\n{member_element}"
        guild_config = ch.scope_config(guild=message.guild)
    except ValueError as e:
        return "This command must be run on a server (you're always #1 to me <3)"
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("JRF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        return


async def ttl(url, message, client, args):
    global session
    start = time.time()
    try:
        async with session.get(url, timeout=60) as response:
            result = await response.text()
            end = time.time()
            await messagefuncs.sendWrappedMessage(
                f"{response.method} {response.url}: {response.status} {response.reason} in {(end - start):0.3g} seconds",
                message.channel,
            )
    except asyncio.TimeoutError:
        await messagefuncs.sendWrappedMessage(f"{url}: TimeoutEror", message.channel)


class sliding_puzzle:
    def __init__(self, message):
        self.channel = message.channel
        self.direction_parsing = defaultdict(str)
        self.direction_parsing["🇺"] = self.shift_up
        self.direction_parsing["⬆️"] = self.shift_up
        self.direction_parsing["u"] = self.shift_up
        self.direction_parsing["up"] = self.shift_up
        self.direction_parsing["🇩"] = self.shift_down
        self.direction_parsing["⬇️"] = self.shift_down
        self.direction_parsing["d"] = self.shift_down
        self.direction_parsing["down"] = self.shift_down
        self.direction_parsing["🇱"] = self.shift_left
        self.direction_parsing["⬅️"] = self.shift_left
        self.direction_parsing["l"] = self.shift_left
        self.direction_parsing["left"] = self.shift_left
        self.direction_parsing["🇷"] = self.shift_right
        self.direction_parsing["➡️"] = self.shift_right
        self.direction_parsing["r"] = self.shift_right
        self.direction_parsing["right"] = self.shift_right
        self.victory_msgs = ["You win!"]

        # make a solved board
        self.grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]
        self.blank_x = 3
        self.blank_y = 3
        # scramble it with legal moves so it stays solvable
        for i in range(1000):
            move = random.choice(
                [self.shift_up, self.shift_down, self.shift_left, self.shift_right]
            )
            move()

    # move the tile below the empty space (0) up one if possible
    def shift_up(self):
        if self.blank_y == 3:
            return
        value_to_move = self.grid[self.blank_y + 1][self.blank_x]
        self.grid[self.blank_y][self.blank_x] = value_to_move
        self.grid[self.blank_y + 1][self.blank_x] = 0
        self.blank_y += 1

    # move the tile above the empty space (0) down one if possible
    def shift_down(self):
        if self.blank_y == 0:
            return
        value_to_move = self.grid[self.blank_y - 1][self.blank_x]
        self.grid[self.blank_y][self.blank_x] = value_to_move
        self.grid[self.blank_y - 1][self.blank_x] = 0
        self.blank_y -= 1

    # move the tile right of the empty space (0) left one if possible
    def shift_left(self):
        if self.blank_x == 3:
            return
        value_to_move = self.grid[self.blank_y][self.blank_x + 1]
        self.grid[self.blank_y][self.blank_x] = value_to_move
        self.grid[self.blank_y][self.blank_x + 1] = 0
        self.blank_x += 1

    # move the tile left of the empty space (0) right one if possible
    def shift_right(self):
        if self.blank_x == 0:
            return
        value_to_move = self.grid[self.blank_y][self.blank_x - 1]
        self.grid[self.blank_y][self.blank_x] = value_to_move
        self.grid[self.blank_y][self.blank_x - 1] = 0
        self.blank_x -= 1

    async def print(self, message):
        return await messagefuncs.sendWrappedMessage(message, self.channel)

    async def input(self, message, allowed_reactions, timeout=3600.0):
        waits = [
            client.wait_for(
                "raw_reaction_add",
                timeout=timeout,
                check=lambda reaction: (str(reaction.emoji) in allowed_reactions)
                and reaction.message_id == message.id,
            )
        ]
        if type(message.channel) == discord.DMChannel:
            waits.append(
                client.wait_for(
                    "raw_reaction_remove",
                    timeout=timeout,
                    check=lambda reaction: (str(reaction.emoji) in allowed_reactions)
                    and reaction.message_id == message.id,
                )
            )
        done, pending = await asyncio.wait(waits, return_when=asyncio.FIRST_COMPLETED)
        for task in pending:
            task.cancel()
        for task in done:
            response = await task
        try:
            if type(message.channel) != discord.DMChannel:
                await message.remove_reaction(
                    response.emoji, message.guild.get_member(response.user_id)
                )
        except discord.Forbidden:
            pass
        return str(response.emoji)

    async def play(self):
        exposition = """You see a grid of tiles built into the top of a pedestal. The tiles can slide around in the grid, but can't be removed without breaking them. There are fifteen tiles, taking up fifteen spaces in a 4x4 grid, so any of the tiles that are adjacent to the empty space can be slid into the empty space."""

        await self.print(exposition)
        self.moves = 0
        for row in range(4):
            if 0 in self.grid[row]:
                self.blank_y = row
        await self.pretty_print()
        allowed_reactions = ["⬆️", "⬇️", "⬅️", "➡️"]
        for reaction in allowed_reactions:
            await self.status_message.add_reaction(reaction)
        await asyncio.sleep(1)
        while True:
            direction = await self.input(self.status_message, allowed_reactions)
            direction = self.direction_parsing[direction]
            if direction != "":
                direction()
                self.moves += 1
            else:
                continue
            await self.pretty_print()
            if self.winning():
                return

    def winning(self):
        return self.grid == [
            [1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
            [13, 14, 15, 0],
        ]

    async def pretty_print(self):
        if self.winning():
            await self.print(
                f"{random.choice(self.victory_msgs)}\nMoves used: {self.moves}",
            )
            outstring = "☆☆☆☆☆☆☆☆\n"
        else:
            outstring = "Slide the tiles with the reactions below:\n"
        mapping = [
            " ",
            "①",
            "②",
            "③",
            "④",
            "⑤",
            "⑥",
            "⑦",
            "⑧",
            "⑨",
            "⑩",
            "⑪",
            "⑫",
            "⑬",
            "⑭",
            "⑮",
        ]
        for row in self.grid:
            for item in row:
                outstring += mapping[item]
            outstring += "\n"
        if not hasattr(self, "status_message"):
            self.status_message = await self.print(outstring)
        else:
            await self.status_message.edit(content=outstring)

    async def sliding_puzzle_function(message, client, args):
        try:
            puzzle = sliding_puzzle(message)
            return await puzzle.play()
        except asyncio.TimeoutError:
            await messagefuncs.sendWrappedMessage(
                "Puzzle failed due to timeout", message.channel
            )
        except Exception as e:
            exc_type, exc_obj, exc_tb = exc_info()
            logger.error("SPF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
            await message.add_reaction("🚫")


class Deck(object):
    def __init__(self):
        self.draw_pile = deque()
        self.discard_pile = deque()
        self.hands = list()

    def discard(self, *cards):
        self.discard_pile.extend(cards)

    def shuffle(self, discard_in=True):
        if discard_in:
            self.draw_pile.extend(self.discard_pile)
            self.discard_pile = deque()
        draw_pile = list(self.draw_pile)
        random.shuffle(draw_pile)
        self.draw_pile = deque(draw_pile)

    def deal(self, number_of_hands=2, number_of_cards=7, exclude_hands=[]):
        self.hands = [deque() for i in range(number_of_hands)]
        for i in range(number_of_cards):
            for hand_offset_pointer in range(number_of_hands):
                if hand_offset_pointer not in exclude_hands:
                    self.draw(hand_offset_pointer, 1)

    def draw(self, hand_number, number_of_cards=1, reshuffle_on_empty=True):
        self.hands[hand_number]
        for i in range(number_of_cards):
            try:
                self.hands[hand_number].append(self.draw_pile.popleft())
            except IndexError as e:
                if reshuffle_on_empty:
                    self.shuffle(discard_in=True)
                    self.hands[hand_number].append(self.draw_pile.popleft())
                else:
                    raise e

    def peek(self, number_of_cards=1, show_remaining_if_empty=True):
        if number_of_cards > len(self.draw_pile) and show_remaining_if_empty:
            number_of_cards = len(self.draw_pile)
        return self.draw_pile[0:number_of_cards]

    async def load(self, attachment, append_to_deck=True):
        raw_str = (await attachment.read()).decode("UTF-8")
        cards = [Deck.Card.load_from_str(line) for line in raw_str.splitlines()]
        if append_to_deck:
            self.draw_pile.extend(cards)
        else:
            self.draw_pile = deque(cards)

    class Card(object):
        def __init__(self, name_of_card, rank=None, comment=""):
            self.name = name_of_card
            self.rank = int(rank) if rank else None
            self.comment = comment

        def load_from_str(raw_str, separator="\t"):
            tokens = raw_str.split(separator)
            if len(tokens) == 1:
                return Deck.Card(name_of_card=tokens[0])
            elif len(tokens) == 2:
                if tokens[1].isnumeric():
                    return Deck.Card(name_of_card=tokens[0], rank=tokens[1])
                else:
                    return Deck.Card(name_of_card=tokens[0], comment=tokens[1])
            elif len(tokens) == 3:
                return Deck.Card(
                    name_of_card=tokens[0], rank=tokens[1], comment=tokens[3]
                )
            else:
                raise ValueError(
                    f"Incorrect number of tokens ({len(tokens)}, must be 1-3) parsing {raw_str}"
                )

        def __str__(self):
            return f"Card __{'#'+str(self.rank)+' ' if self.rank else ''}{self.name}__"


async def card_choice_game_function(message, client, args):
    try:
        deck = Deck()
        if len(message.attachments) and message.attachments[0].filename.endswith(
            ".txt"
        ):
            await deck.load(message.attachments[0])
        if not len(deck.draw_pile):
            return await messagefuncs.sendWrappedMessage(
                "Unable to load cards for game (draw pile is empty).", message.channel
            )
        else:
            await messagefuncs.sendWrappedMessage(
                f"Loaded {len(deck.draw_pile)} cards from {message.attachments[0].filename}",
                message.channel,
            )

            class Player(object):
                def __init__(
                    self, hand_number=None, user=None, score=0, deck=None, hand=None
                ):
                    self.hand_number = hand_number
                    self.user = user
                    self.score = score
                    if hand:
                        self.hand = hand
                    else:
                        self.hand = deck.hands[hand_number]
                    self.deck = deck

                def card_names(self):
                    return [card.name.lower() for card in self.hand]

                def get_card_by_name(self, name):
                    i = self.card_names().index(name.lower())
                    return (i, self.hand[i])

                def pop(self, name):
                    card = self.get_card_by_name(name)
                    self.hand.remove(card[1])
                    if deck:
                        self.deck.discard(card[1])
                    return card

                def __str__(self):
                    return "; ".join([card.name for card in self.hand])

            deck.shuffle()
            deck.deal(len(message.mentions), 6)
            deck.draw(0, 1)
            players = deque(
                [
                    Player(i, message.mentions[i], deck=deck)
                    for i in range(len(deck.hands))
                ]
            )
            game_ongoing = True

            async def input_from_list(message, channel, options=[], timeout=3600.0):
                await messagefuncs.sendWrappedMessage(message, channel)
                response = await client.wait_for(
                    "message",
                    timeout=timeout,
                    check=lambda m: m.channel == channel
                    and m.clean_content.lower() in options,
                )

                return response.clean_content

            async def pick_card_from_hand(player, is_leader=False):
                options = player.card_names()
                options.append("pass")
                if is_leader:
                    options.append("quit")
                target = (
                    player.user.dm_channel
                    if player.user.dm_channel
                    else await player.user.create_dm()
                )
                return await input_from_list(
                    f"Pick a card from your hand to start the round.\nYour hand contains {player}. You can also say `PASS` to pass this round to the next leader{', or `QUIT` to end the game' if is_leader else ''}.",
                    target,
                    options,
                )

            async def scoreboard(players, channel, show_winner=False):
                scoreboard = list(sorted(players, key=lambda player: -player.score))
                message = "\n".join(
                    [
                        f"• {player.user.display_name}: {player.score} points"
                        for player in scoreboard
                    ]
                )
                if show_winner:
                    message = "__Final Scores__\n{message}\n{scoreboard[0].user.mention} is the winner!"
                return await messagefuncs.sendWrappedMessage(message, channel)

            while game_ongoing:
                leader = players[0]
                players.rotate()
                await scoreboard(players, message.channel)
                try:
                    choice = await pick_card_from_hand(leader, is_leader=True)
                except asyncio.TimeoutError:
                    choice = "PASS"
                if choice.lower() == "quit":
                    game_ongoing = False
                    continue
                elif choice.lower() == "pass":
                    continue
                else:
                    card = leader.pop(choice)[1]
                deck.deal(len(players), 1, exclude_hands=[leader.hand_number])
                status_message = None
                player_choices = players.copy()
                player_choices.pop()

                async def current_status(status_message, channel=None):
                    players_left = sum(
                        1 for player in player_choices if type(player) is Player
                    )
                    message = f"{leader.user.mention} chose {card}.\n"
                    if players_left:
                        message += f"Awaiting {players_left} players"
                    else:
                        message += f"Choice cards are {'; '.join([card.name for card in player_choices])}"
                    if not status_message:
                        return await messagefuncs.sendWrappedMessage(message, channel)
                    else:
                        await status_message.edit(content=message)

                status_message = await current_status(status_message, message.channel)

                async def choose_card(player, status_message):
                    try:
                        choice = await pick_card_from_hand(player, is_leader=False)
                    except asyncio.TimeoutError:
                        choice = "PASS"
                    player_choices[player_choices.index(player)] = (
                        None if choice.lower() == "pass" else player.pop(choice)[1]
                    )
                    await current_status(status_message)

                await asyncio.gather(
                    *[choose_card(player, status_message) for player in player_choices]
                )
                options = list(filter(lambda card: card is not None, player_choices))
                player = Player(hand=options, user=leader.user)
                try:
                    choice = await pick_card_from_hand(player, is_leader=True)
                except asyncio.TimeoutError:
                    choice = "quit"
                if choice.lower() == "quit":
                    game_ongoing = False
                    continue
                else:
                    winning_player = players[
                        player_choices.index(player.get_card_by_name(choice)[1])
                    ]
                    winning_player.score += 1
                    await messagefuncs.sendWrappedMessage(
                        f"Player {winning_player.user.mention} won that round! Their score is {winning_player.score}",
                        message.channel,
                    )
                    deck.discard(*options)
                    deck.deal(len(players), 1, exclude_hands=[leader.hand_number])
            await scoreboard(players, message.channel, show_winner=Trure)
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("CCGF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        logger.info(traceback.format_exc())
        await message.add_reaction("🚫")


def memo_function(message, client, args):
    value = message.clean_content.split(args[0] + " ", 1)[1] if len(args) > 1 else None
    return ch.user_config(
        message.author.id,
        message.guild.id if message.guild else None,
        "memo-" + args[0],
        value=value,
        allow_global_substitute=True,
    )


async def ssc_function(message, client, args):
    try:
        url = None
        if len(args) == 0:
            async with session.get(
                "https://novalinium.com/sscd.archive.search.pl"
            ) as resp:
                return await messagefuncs.sendWrappedMessage(
                    resp.headers["Location"], target=message.channel
                )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("SSC[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")


async def autounload(ch):
    global session
    if session:
        await session.close()


def autoload(ch):
    global session
    ch.add_command(
        {
            "trigger": [
                "!uwu",
                "<:uwu:445116031204196352>",
                "<:uwu:269988618909515777>",
                "<a:rainbowo:493599733571649536>",
                "<:owo:487739798241542183>",
                "<:owo:495014441457549312>",
                "<a:OwO:508311820411338782>",
                "!good",
                "!aww",
            ],
            "function": uwu_function,
            "async": True,
            "args_num": 0,
            "args_name": [],
            "description": "uwu",
        }
    )
    ch.add_command(
        {
            "trigger": ["!pick"],
            "function": pick_function,
            "async": True,
            "args_num": 1,
            "args_name": [],
            "description": "pick among comma seperated choices",
        }
    )
    ch.add_command(
        {
            "trigger": ["!roll"],
            "function": roll_function,
            "async": True,
            "args_num": 0,
            "args_name": [],
            "description": "Roll dice in #d# format",
        }
    )
    ch.add_command(
        {
            "trigger": ["!dumpling"],
            "function": lambda message, client, args: "🥟",
            "async": False,
            "args_num": 0,
            "args_name": [],
            "description": "Domp",
            "hidden": True,
        }
    )
    ch.add_command(
        {
            "trigger": ["!ifeellikeshit"],
            "function": lambda message, client, args: "<:ghost_hug:630502841181667349> have a flowchart: https://philome.la/jace_harr/you-feel-like-shit-an-interactive-self-care-guide/play/index.html",
            "async": False,
            "args_num": 0,
            "args_name": [],
            "description": "FiO link",
            "hidden": True,
        }
    )
    ch.add_command(
        {
            "trigger": ["!bail"],
            "function": lambda message, client, args: f"Looks like {message.author.display_name} is bailing out on this one - good luck!",
            "async": False,
            "args_num": 0,
            "args_name": [],
            "description": "Bail out",
            "hidden": True,
        }
    )
    ch.add_command(
        {
            "trigger": ["!fio", "!optimal"],
            "function": lambda message, client, args: "https://www.fimfiction.net/story/62074/8/friendship-is-optimal/",
            "async": False,
            "args_num": 0,
            "args_name": [],
            "description": "FiO link",
            "hidden": True,
        }
    )
    ch.add_command(
        {
            "trigger": ["!shindan", "📛"],
            "function": shindan_function,
            "async": True,
            "args_num": 0,
            "long_run": "author",
            "args_name": [],
            "description": "Embed shindan",
        }
    )
    ch.add_command(
        {
            "trigger": ["!scp"],
            "function": scp_function,
            "async": True,
            "args_num": 0,
            "long_run": True,
            "args_name": [],
            "description": "SCP Function",
        }
    )
    ch.add_command(
        {
            "trigger": ["!retrowave"],
            "function": retrowave_function,
            "async": True,
            "args_num": 0,
            "long_run": True,
            "args_name": [
                "Up to 16 characters",
                "Up to 13 characters",
                "Up to 27 characters",
            ],
            "description": "Retrowave Text Generator. Arguments are bucketed in batches of three, with 16 characters for the top row, 13 for the middle row, and 27 for the bottom row. Non alphanumeric characters are stripped. To set your own divisions, add slashes.",
        }
    )
    ch.add_command(
        {
            "trigger": ["!quoteadd", "🗨"],
            "function": qdb_add_function,
            "async": True,
            "hidden": True,
            "args_num": 0,
            "args_name": ["quote link"],
            "description": "Add to quote database",
        }
    )
    ch.add_command(
        {
            "trigger": ["!quoteget"],
            "function": qdb_get_function,
            "async": True,
            "hidden": True,
            "args_num": 1,
            "args_name": ["quote id"],
            "description": "Get from quote database by id number",
        }
    )
    ch.add_command(
        {
            "trigger": ["!quotesearch"],
            "function": qdb_search_function,
            "async": True,
            "hidden": True,
            "args_num": 1,
            "args_name": ["keyword"],
            "description": "Get from quote database by keyword",
        }
    )
    ch.add_command(
        {
            "trigger": ["!pingme"],
            "function": lambda message, client, args: f"Pong {message.author.mention}!",
            "async": False,
            "args_num": 0,
            "long_run": False,
            "args_name": [],
            "description": "Pong with @ in response to ping",
        }
    )
    ch.add_command(
        {
            "trigger": ["!ping"],
            "function": lambda message, client, args: f"Pong!",
            "async": False,
            "args_num": 0,
            "long_run": False,
            "args_name": [],
            "description": "Pong in response to ping",
        }
    )
    ch.add_command(
        {
            "trigger": ["!fling"],
            "function": lambda message, client, args: f"(ノ◕ヮ◕)ノ*:・゚✧ {message.content[7:]}",
            "async": False,
            "args_num": 0,
            "long_run": False,
            "args_name": [],
            "description": "Fling sparkles!",
        }
    )
    ch.add_command(
        {
            "trigger": ["!rank"],
            "function": join_rank_function,
            "async": False,
            "args_num": 0,
            "long_run": False,
            "args_name": ["@member (optional)"],
            "description": "Check what number member you (or mentioned user) were to join this server.",
        }
    )
    ch.add_command(
        {
            "trigger": ["!nextfullmoon"],
            "function": lambda message, client, args: ephem.next_full_moon(
                datetime.now()
            ),
            "async": False,
            "args_num": 0,
            "long_run": False,
            "args_name": [],
            "description": "Next full moon time",
        }
    )
    ch.add_command(
        {
            "trigger": ["!nextnewmoon"],
            "function": lambda message, client, args: ephem.next_new_moon(
                datetime.now()
            ),
            "async": False,
            "args_num": 0,
            "long_run": False,
            "args_name": [],
            "description": "Next new moon time",
        }
    )
    ch.add_command(
        {
            "trigger": ["!onthisday"],
            "function": wiki_otd_function,
            "async": True,
            "args_num": 0,
            "long_run": True,
            "args_name": ["Month Day# (January 1)"],
            "description": "Wikipedia On This Day",
        }
    )
    ch.add_command(
        {
            "trigger": ["!lifx"],
            "function": lifx_function,
            "async": True,
            "args_num": 1,
            "long_run": True,
            "args_name": ["Color", "[Selector]"],
            "description": "Set color of LIFX bulbs",
        }
    )
    ch.add_command(
        {
            "trigger": ["!mycolor", "!mycolour"],
            "function": lambda message, client, args: "Your color is #%06x"
            % message.author.colour.value,
            "async": False,
            "args_num": 0,
            "args_name": [],
            "description": "Get Current Color",
        }
    )
    ch.add_command(
        {
            "trigger": ["!color"],
            "function": lambda message, client, args: "Current color is #{message.mentions[0].colour.value:06x}"
            if len(message.mentions)
            else "No user @mention found.",
            "async": False,
            "args_num": 1,
            "args_name": ["User mention"],
            "description": "Get Current Color for @ed user",
        }
    )
    ch.add_command(
        {
            "trigger": ["!thank you"],
            "function": lambda message, client, args: messagefuncs.add_reaction(
                message, random.choice(uwu_responses["reaction"])
            ),
            "async": True,
            "hidden": True,
            "args_num": 0,
        }
    )
    ch.add_command(
        {
            "trigger": ["!wiki"],
            "function": lambda message, client, args: f"https://en.wikipedia.org/wiki/{'_'.join(args)}",
            "async": False,
            "args_num": 1,
            "args_name": ["Article name"],
            "description": "Search wikipedia for article",
        }
    )
    ch.add_command(
        {
            "trigger": ["!fox"],
            "function": fox_function,
            "async": True,
            "args_num": 0,
            "args_name": [],
            "description": "^W^",
        }
    )
    ch.add_command(
        {
            "trigger": ["!dog", "!pupper"],
            "function": dog_function,
            "async": True,
            "args_num": 0,
            "args_name": [],
            "description": "Woof!",
        }
    )
    ch.add_command(
        {
            "trigger": ["!glowup"],
            "function": partial(ttl, "https://glowfic.com"),
            "async": True,
            "args_num": 0,
            "args_name": [],
            "description": "Check if Glowfic site is up",
        }
    )
    ch.add_command(
        {
            "trigger": ["!slidingpuzzle"],
            "function": sliding_puzzle.sliding_puzzle_function,
            "async": True,
            "hidden": True,
            "args_num": 0,
            "args_name": [],
            "description": "A fun little sliding puzzle",
        }
    )
    ch.add_command(
        {
            "trigger": ["!memo"],
            "function": memo_function,
            "async": False,
            "hidden": False,
            "args_num": 1,
            "args_name": ["memo key", "value"],
            "description": "Take a personal memo to be retrieved later",
        }
    )
    ch.add_command(
        {
            "trigger": ["!slash"],
            "function": card_choice_game_function,
            "async": True,
            "hidden": True,
            "args_num": 2,
            "args_name": ["@player1 @player2 ...", "Attachment: deck"],
            "description": "Card choice game",
        }
    )
    session = aiohttp.ClientSession(
        headers={"User-Agent": "Fletcher/0.1 (operator@noblejury.com)",}
    )