@L11K/

Feature Requests Bot

Python

No description

fork
loading
Files
  • main.py
  • static
  • templates
  • LICENCE
  • requests.db
  • requirements.txt
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
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
import discord
import asyncio
import pygsheets
import datetime
import re
import time
import aiohttp
import async_timeout
import json
import sys
import sqlite3
import aiohttp_jinja2
import jinja2
import logging
import os
import random
import base64
import html
from oauth2client.service_account import ServiceAccountCredentials
from aiohttp_session import setup, get_session
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from aiohttp import web

# settings
GAME_MODES = ["mode1", "mode2", "mode3"]

WEBSITE_TITLE = "Demo Feature Requests"
WEBSITE_TITLE_SINGULAR = (
    "Demo Feature Request"
)  # for example "request" instead of "requests"
WEBSITE_DESCRIPTION = "The feature requests website for demoing this discord bot/website. Submit your own fake feature requests here!"

client = discord.Client()

# json_data = json.loads(os.environ.get("GOOGLE_SERVICE_FILE"))
# gs = pygsheets.authorize(
#     credentials=ServiceAccountCredentials.from_json_keyfile_dict(
#         json_data,
#         [
#             "https://www.googleapis.com/auth/spreadsheets",
#             "https://www.googleapis.com/auth/drive",
#         ],
#     )
# )

# ss = gs.open("Demo Feature Requests")
# allS = ss.worksheet_by_title("All")
# openS = ss.worksheet_by_title("Open")
# rejS = ss.worksheet_by_title("Rejected")
# doneS = ss.worksheet_by_title("Implemented")
# planS = ss.worksheet_by_title("Planned")
# stats = ss.worksheet_by_title("Stats")

newpattern = re.compile(
    r"\*?\*?Title[\*,:, ]*(.*?) ?\n\*?\*?Game mode[\*,:, ]*(.*?) ?\n\*?\*?Description[\*,:, ]*([\s\S]*)"
)
commentpattern = re.compile(r"^(\d{18})[^>].*?([^\s:-][\s\S]*)")

conn = sqlite3.connect("requests.db")
c = conn.cursor()

logger = logging.getLogger("logger")
logger.setLevel(logging.DEBUG)
f = logging.Formatter(
    "%(asctime)s - %(funcName)s - %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S"
)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(f)
# fh = logging.FileHandler("logs/%s.log" % str(datetime.datetime.now())) # disabling file logger here for security since logs in this repl can be freely accessed
# fh.setLevel(logging.DEBUG)
# fh.setFormatter(f)
logger.addHandler(ch)
# logger.addHandler(fh)

encoder = json.JSONEncoder()

verifying = []


def isAdmin(member):
    """this function returns true/false depending on if member is admin"""
    global mateuszdrwal
    return member == mateuszdrwal


async def perm(reaction):
    """This function returns true if an admin has reacted with 'reaction', else false"""
    global guild
    async for user in reaction.users():
        try:
            member = guild.get_member(user.id)
            if isAdmin(member):
                return True
        except:
            pass
    return False


async def updateSheet():
    """this function updates the spreadsheet with the current data from the database"""
    global c

    for sheet, criteria in [
        (openS, " WHERE status = 0 AND disabled = 0"),
        (planS, " WHERE status = 1 AND disabled = 0"),
        (rejS, " WHERE status = 2 AND disabled = 0"),
        (doneS, " WHERE status = 3 AND disabled = 0"),
        (allS, " WHERE disabled = 0"),
    ]:

        c.execute("SELECT * FROM requests" + criteria)
        entries = c.fetchall()

        newVals = []

        for entry in entries:
            if entry[8] == 0:
                status = "Open"
            if entry[8] == 1:
                status = "Planned"
            if entry[8] == 2:
                status = "Rejected"
            if entry[8] == 3:
                status = "Implemented"
            if entry[8] == 4:
                status = "Not applicable anymore"

            c.execute("SELECT * FROM responses WHERE mid = :mid", {"mid": entry[9]})
            responses = c.fetchall()

            newVals.append(
                [
                    datetime.datetime.fromtimestamp(entry[0]).strftime(
                        "%Y-%m-%d %H:%M:%S UTC"
                    ),
                    entry[1],
                    entry[3],
                    entry[14],
                    entry[5],
                    entry[6] - entry[7],
                    entry[6],
                    entry[7],
                    status,
                    "\n\n".join(resp[2] for resp in responses),
                    entry[9],
                    entry[10],
                ]
            )

            await asyncio.sleep(0.01)

        newVals.sort(key=lambda r: int(r[5]))
        newVals.reverse()
        newVals.insert(
            0,
            [
                "Time Submitted",
                "Member",
                "Title",
                "Mode",
                "Description",
                "Points",
                "Upvotes",
                "Downvotes",
                "Status",
                "Developer Response",
                "Message ID",
                "Member ID",
            ],
        )

        cells = []
        for i, row in enumerate(newVals):
            for j, val in enumerate(row):
                cells.append(pygsheets.Cell((i + 1, j + 1), str(val)))

        sheet.clear((len(newVals) + 1, 1))
        sheet.update_cells(cell_list=cells)

    cells = []
    cells.append(pygsheets.Cell("B8"))
    cells[-1].value = "Last updated at: %s" % datetime.datetime.utcnow().strftime(
        "%Y-%m-%d %H:%M:%S UTC"
    )
    stats.update_cells(cell_list=cells)


class fakemember:
    pass


async def updateRequest(message):
    """this function updates a requests database entry using the current information from the discord message"""
    upvotes = 0
    downvotes = 0
    status = (
        0
    )  # 0: open, 1: in-progress, 2: rejected, 3: resolved, 4: Not applicable anymore

    c.execute("SELECT * FROM votes WHERE mid = :mid", {"mid": message.id})
    fetched = c.fetchall()
    uped = [vote[1] for vote in fetched if vote[2] and vote[4]]
    downed = [vote[1] for vote in fetched if vote[3] and vote[5]]
    c.execute("SELECT * FROM requests WHERE mid = :mid", {"mid": message.id})
    fetched = c.fetchall()
    try:
        webStatus = bool(fetched[0][13])
        lastStatus = fetched[0][8]
    except Exception as e:
        logger.debug(message)
        logger.debug(message.content)
        raise e

    if len(message.mentions) == 0:
        member = fakemember()
        member.id = fetched[0][10]
        member.name = "".join(fetched[0][1].split("#")[:-1])
        member.discriminator = int(fetched[0][1].split("#")[-1])
        message.mentions.append(member)

    for reaction in message.reactions:
        if reaction.emoji == "\u26d4":  # :no_entry: , ⛔
            if await perm(reaction):
                c.execute(
                    "UPDATE requests SET disabled = 1 WHERE mid = :mid",
                    {"mid": message.id},
                )
                conn.commit()
                return

        elif reaction.emoji == "\U0001f5d3":  # :calendar_spiral:, 🗓
            if await perm(reaction) and status < 1 and not webStatus:
                status = 1
        elif reaction.emoji == "\u274c":  # :x:, ❌
            if await perm(reaction) and status < 2 and not webStatus:
                status = 2
        elif reaction.emoji == "\u2705":  # :white_check_mark:, ✅
            if await perm(reaction) and status < 3 and not webStatus:
                status = 3

        elif reaction.emoji == "\U0001f44e":  # :thumbsdown:, 👎
            async for user in reaction.users():

                if reaction.message.author.bot:
                    if reaction.message.mentions[0].id == user.id:
                        continue

                if user in [reaction.message.author, client.user]:
                    continue

                c.execute(
                    "SELECT * FROM votes WHERE mid = :mid AND uid = :uid",
                    {"mid": message.id, "uid": user.id},
                )
                fetched = c.fetchall()
                if fetched != []:
                    if fetched[0][3] != 1 or fetched[0][5] != 1:
                        c.execute(
                            "UPDATE votes SET down = 1, downDiscord = 1 WHERE :mid = :mid AND uid = :uid",
                            {"mid": message.id, "uid": user.id},
                        )
                else:
                    c.execute(
                        "INSERT INTO votes VALUES (:mid, :uid, 0, 1, 0, 1)",
                        {"mid": message.id, "uid": user.id},
                    )

                conn.commit()

                try:
                    downed.remove(user.id)
                except ValueError:
                    pass

        elif reaction.emoji in [
            "\U0001f44d",
            "\U0001F60D",
            "\u2764",
            "\u261D",
            "\U0001F446",
            "\U0001F44C",
            "\U0001F4AF",
            u"\N{WHITE HEAVY CHECK MARK}",
        ]:  # whole array of "upvote" emojis. this was necessary since people kept forgetting that the only emoji that was counted was :thumbsup:.
            async for user in reaction.users():
                if reaction.message.author.bot:
                    if reaction.message.mentions[0].id == user.id:
                        continue

                if user in [reaction.message.author, client.user]:
                    continue

                c.execute(
                    "SELECT * FROM votes WHERE mid = :mid AND uid = :uid",
                    {"mid": message.id, "uid": user.id},
                )
                fetched = c.fetchall()
                if fetched != []:
                    if fetched[0][2] != 1 or fetched[0][4] != 1:
                        c.execute(
                            "UPDATE votes SET up = 1, upDiscord = 1 WHERE :mid = :mid AND uid = :uid",
                            {"mid": message.id, "uid": user.id},
                        )
                else:
                    c.execute(
                        "INSERT INTO votes VALUES (:mid, :uid, 1, 0, 1, 0)",
                        {"mid": message.id, "uid": user.id},
                    )

                conn.commit()

                try:
                    uped.remove(user.id)
                except ValueError:
                    pass

    for user in uped:
        c.execute(
            "UPDATE votes SET up = 0, upDiscord = 0 WHERE mid = :mid AND uid = :uid",
            {"mid": message.id, "uid": user},
        )
    for user in downed:
        c.execute(
            "UPDATE votes SET down = 0, downDiscord = 0 WHERE mid = :mid AND uid = :uid",
            {"mid": message.id, "uid": user},
        )
    conn.commit()

    c.execute(
        "SELECT count(*) FROM votes WHERE up = 1 AND mid = :mid", {"mid": message.id}
    )
    upvotes = c.fetchall()[0][0]
    c.execute(
        "SELECT count(*) FROM votes WHERE down = 1 AND mid = :mid", {"mid": message.id}
    )
    downvotes = c.fetchall()[0][0]

    devresp = []
    c.execute("SELECT * FROM responses WHERE mid = :mid", {"mid": message.id})
    for response in c.fetchall():
        devresp.append(
            str(jinja2.escape("%s:\n%s" % (response[3], response[2]))).replace(
                "\n", "<br/>"
            )
        )
    devresp = "<br/><br/>".join(devresp)

    c.execute(
        "UPDATE requests SET up = :up, down = :down, status = :status, devresp = :devresp WHERE mid = :mid",
        {
            "mid": message.id,
            "up": upvotes,
            "down": downvotes,
            "status": status if not webStatus else lastStatus,
            "devresp": devresp,
            "author": "%s#%s" % (message.author.name, message.author.discriminator)
            if not message.author.bot
            else "%s#%s"
            % (message.mentions[0].name, message.mentions[0].discriminator),
        },
    )

    conn.commit()


async def analyzeMessage(message, force=False, new=False):
    """this function analyzes a message to check if it contains a request or comment. if it does it updates it."""
    comment = re.findall(commentpattern, message.content)
    results = re.findall(newpattern, message.clean_content)

    if comment != [] and message.author not in guild.members:
        return
    if comment != [] and isAdmin(message.author):
        comment = comment[0]
        id = int(comment[0])

        c.execute("SELECT * FROM requests WHERE mid = :mid", {"mid": id})

        if c.fetchall() != []:
            c.execute(
                "SELECT * FROM responses WHERE rmid = :rmid", {"rmid": message.id}
            )

            if c.fetchall() == []:
                c.execute(
                    "INSERT INTO responses VALUES (:mid, :rmid, :resp, :author)",
                    {
                        "mid": id,
                        "rmid": message.id,
                        "resp": comment[1],
                        "author": message.author.name,
                    },
                )
                conn.commit()
                await message.add_reaction(u"\N{WHITE HEAVY CHECK MARK}")
            else:
                c.execute(
                    "UPDATE responses SET response = :resp WHERE mid = :mid AND rmid = :rmid",
                    {"mid": id, "rmid": message.id, "resp": comment[1]},
                )

            await updateRequest(await requestChannel.get_message(id))
        return

    if (
        force or (message.author == client.user and results != [])
    ) and message.id not in [466682006718251039]:
        await updateRequest(message)
        return

    if results == [] or message.id == 403337281068466197:
        return

    c.execute("SELECT * FROM requests WHERE mid = :mid", {"mid": message.id})
    fetched = c.fetchall()

    if results[0][1].lower() not in GAME_MODES:
        if new:
            await requestChannel.send(
                "That mode is incorrect. please edit your message to make sure that the mode is either %s. You know it worked when i react with \U0001f44d and \U0001f44e"
                % (", ".join(GAME_MODES[:-1]) + " or " + GAME_MODES[-1])
            )
        return

    if fetched != []:
        c.execute(
            """UPDATE requests SET
        title = :title,
        mode = :mode,
        description = :description,
        up = 0,
        down = 0
        WHERE mid = :mid""",
            {
                "title": html.escape(results[0][0]),
                "mode": html.escape(results[0][1].lower()),
                "description": html.escape(results[0][2]),
                "mid": message.id,
            },
        )
    else:
        c.execute(
            """INSERT INTO requests VALUES (
        :time,
        :author,
        "",
        :title,
        "",
        :description,
        0,
        0,
        0,
        :mid,
        :uid,
        "",
        0,
        0,
        :mode
        )""",
            {
                "time": message.created_at.timestamp(),
                "author": html.escape(
                    "%s#%s" % (message.author.name, message.author.discriminator)
                ),
                "title": html.escape(results[0][0]),
                "mode": html.escape(results[0][1].lower()),
                "description": html.escape(results[0][2]),
                "mid": message.id,
                "uid": message.author.id,
            },
        )
        logger.info("new suggestion: %s" % results[0][0])
        await message.add_reaction("\U0001F44D")
        await message.add_reaction("\U0001F44E")

    conn.commit()

    await updateRequest(message)


async def loop():
    """main loop"""
    global requestChannel, guild, conn, c
    await client.wait_until_ready()
    await asyncio.sleep(1)

    async for message in requestChannel.history(limit=None, reverse=True):
        await analyzeMessage(message)

    logger.info("initial update done")

    while True:

        c.execute("SELECT * FROM requests")
        for request in c.fetchall():
            try:
                message = await requestChannel.get_message(request[9])
            except discord.NotFound:
                c.execute("DELETE FROM requests WHERE mid = :mid", {"mid": request[9]})
                c.execute("DELETE FROM votes WHERE mid = :mid", {"mid": request[9]})
                c.execute("DELETE FROM responses WHERE mid = :mid", {"mid": request[9]})
                conn.commit()
                logger.info("removed request %s" % request[3])
                continue
            await analyzeMessage(message, True)

        try:
            # await updateSheet()
            await asyncio.sleep(600)
        except Exception as error:
            logger.debug(error)
            # gs = pygsheets.authorize(service_file="key.json")

            # ss = gs.open("Demo Feature Requests")
            # allS = ss.worksheet_by_title("All")
            # openS = ss.worksheet_by_title("Open")
            # rejS = ss.worksheet_by_title("Rejected")
            # doneS = ss.worksheet_by_title("Implemented")
            # planS = ss.worksheet_by_title("Planned")
            # stats = ss.worksheet_by_title("Stats")


@client.event
async def on_reaction_add(reaction, user):
    if not client.is_ready():
        await client.wait_until_ready()
        await asyncio.sleep(5)
    if reaction.message.channel == requestChannel:
        await analyzeMessage(reaction.message)


@client.event
async def on_reaction_remove(reaction, user):
    if not client.is_ready():
        await client.wait_until_ready()
        await asyncio.sleep(5)
    if reaction.message.channel == requestChannel:
        await analyzeMessage(reaction.message)


@client.event
async def on_reaction_clear(message, reactions):
    if not client.is_ready():
        await client.wait_until_ready()
        await asyncio.sleep(5)
    if message.channel == requestChannel:
        await analyzeMessage(message)


@client.event
async def on_message(message):

    if message.author == client.user:
        return

    if not client.is_ready():
        await client.wait_until_ready()
        await asyncio.sleep(5)
    if message.channel == requestChannel:
        await analyzeMessage(message, new=True)


@client.event
async def on_message_edit(before, message):
    if not client.is_ready():
        await client.wait_until_ready()
        await asyncio.sleep(5)
    if message.channel == requestChannel:
        await analyzeMessage(message)


async def get(url, headers=None):
    global http
    while True:
        try:
            with async_timeout.timeout(30):
                async with http.get(url, headers=headers) as response:
                    return await response.text()
        except aiohttp.client_exceptions.ServerDisconnectedError:
            pass
        except asyncio.TimeoutError:
            pass
        except Exception as e:
            raise e


async def post(url, data=None, headers=None):
    global http
    while True:
        try:
            with async_timeout.timeout(30):
                async with http.post(url, data=data, headers=headers) as response:
                    return await response.json()
        except aiohttp.client_exceptions.ServerDisconnectedError:
            pass
        except asyncio.TimeoutError:
            pass
        except Exception as e:
            raise e


@client.event
async def on_ready():
    global requestChannel, guild, mateuszdrwal

    logger.debug(client.user.name)
    logger.debug(client.user.id)

    requestChannel = client.get_channel(439586718681792552)
    mateuszdrwal = client.get_user(140504440930041856)
    guild = client.get_guild(437048931827056642)

    await client.change_presence(
        activity=discord.Activity(
            name="with Repl.it", type=discord.ActivityType.streaming
        )
    )

    logger.info("discord.py initialized")


async def errorCatcher(task):
    try:
        await task
    except Exception as e:
        pass  # handle main loop excepions here


@client.event
async def on_error(event, *args, **kwargs):
    pass  # handle discord.py exceptions here


async def startup():
    global http, conn, c
    http = aiohttp.ClientSession()

    conn = sqlite3.connect("requests.db")
    c = conn.cursor()


client.loop.create_task(startup())
client.loop.create_task(errorCatcher(loop()))
client.loop.create_task(client.start(os.environ.get("BOT_TOKEN")))


routes = web.RouteTableDef()
app = web.Application(loop=client.loop)
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader("./templates"))


def ip(request):
    return request.remote


def who(session, request):
    return (
        "%s (%s)" % (session["username"], ip(request))
        if "username" in session
        else ip(request)
    )


@routes.get("/")
@aiohttp_jinja2.template("home.html")
async def home(request):
    session = await get_session(request)

    if (
        "username" not in session
        and request.query.get("r", None) != None
        and "Discordbot" not in request.headers.get("user-agent")
    ):
        return web.HTTPFound(
            "https://discordapp.com/api/oauth2/authorize?client_id=513773153902919722&redirect_uri=https%3A%2F%2Fdemorequests.mateuszdrwal.com%2Fauth%3Fr%3D1&response_type=code&scope=identify"
        )

    return {
        "error": request.query.get("error", None),
        "success": request.query.get("success", None),
        "desc": WEBSITE_DESCRIPTION,
        "author": "",
        "title": WEBSITE_TITLE,
        "submit": request.query.get("r", None),
        **session,
    }


@routes.get("/request/{requestid}")
@aiohttp_jinja2.template("home.html")
async def request(request):
    session = await get_session(request)

    c.execute(
        "SELECT * FROM requests WHERE mid = :mid",
        {"mid": request.match_info.get("requestid")},
    )
    fetched = c.fetchall()
    if len(fetched) != 0:
        desc = fetched[0][5]
        author = fetched[0][1]
        title = fetched[0][3] + WEBSITE_TITLE_SINGULAR

    if (
        "username" not in session
        and request.query.get("r", None) != None
        and "Discordbot" not in request.headers.get("user-agent")
    ):
        return web.HTTPFound(
            "https://discordapp.com/api/oauth2/authorize?client_id=513773153902919722&redirect_uri=https%3A%2F%2Fdemorequests.mateuszdrwal.com%2Fauth&response_type=code&scope=identify"
        )

    return {
        "error": None,
        "success": None,
        "desc": desc,
        "author": author,
        "title": title,
        "submit": None,
        **session,
    }


@routes.get("/api/requests")
async def rawrequests(request):
    session = await get_session(request)

    if request.query.get("request", "null") == "null":
        c.execute("SELECT * FROM requests WHERE disabled = 0")
    else:
        c.execute(
            "SELECT * FROM requests WHERE mid = :mid", {"mid": request.query["request"]}
        )

    fetched = c.fetchall()

    requests = {
        request[9]: {
            "date": datetime.date.fromtimestamp(request[0]).isoformat(),
            "time": datetime.datetime.fromtimestamp(request[0]).isoformat(),
            "author": request[1],
            "sugtype": request[2],
            "title": request[3],
            "category": request[4],
            "description": request[5],
            "up": request[6],
            "down": request[7],
            "status": [
                "Open",
                "Planned",
                "Rejected",
                "Implemented",
                "Not applicable anymore",
            ][request[8]],
            "statusCode": request[8],
            "mid": str(request[9]),
            "vote": {"up": 0, "down": 0, "upDiscord": 0, "downDiscord": 0},
            "devresp": request[11],
            "self": int(request[10]) == int(session.get("id", 0)),
            "timestamp": request[0],
            "mode": request[14],
        }
        for request in fetched
    }

    if "username" in session:
        c.execute("SELECT * FROM votes WHERE uid = :uid", {"uid": session["id"]})
        fetched = c.fetchall()
        for vote in fetched:
            if vote[0] not in requests:
                continue
            requests[vote[0]]["vote"]["up"] = vote[2]
            requests[vote[0]]["vote"]["down"] = vote[3]
            requests[vote[0]]["vote"]["upDiscord"] = vote[4]
            requests[vote[0]]["vote"]["downDiscord"] = vote[5]

    return web.Response(text=encoder.encode(requests))


@routes.get("/login")
async def login(request):
    return web.HTTPFound(
        "https://discordapp.com/api/oauth2/authorize?client_id=513773153902919722&redirect_uri=https%3A%2F%2Fdemorequests.mateuszdrwal.com%2Fauth&response_type=code&scope=identify"
    )


@routes.get("/auth")
async def auth(request):
    try:
        if "code" not in request.query:
            return web.HTTPFound("/")

        redirect = "https://demorequests.mateuszdrwal.com/auth"
        if request.query.get("r") != None:
            redirect += "?r=1"

        data = {
            "client_id": os.environ.get("CLIENT_ID"),
            "client_secret": os.environ.get("CLIENT_SECRET"),
            "grant_type": "authorization_code",
            "code": request.query["code"],
            "redirect_uri": redirect,
        }
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        response = await post("https://discordapp.com/api/oauth2/token", data, headers)
        assert "access_token" in response
        response = json.loads(
            await get(
                "https://discordapp.com/api/users/@me",
                {"Authorization": "Bearer %s" % response["access_token"]},
            )
        )
        assert "username" in response
        session = await get_session(request)
        session["username"] = response["username"]
        session["id"] = response["id"]
        session["avatar"] = "https://cdn.discordapp.com/avatars/%s/%s.png?size=32" % (
            response["id"],
            response["avatar"],
        )

        member = guild.get_member(int(response["id"]))
        if member != None and isAdmin(member):
            session["admin"] = True
            logger.info("admin %s logged in" % response["username"])
        else:
            session["admin"] = False
            logger.info("%s logged in" % response["username"])
        return (
            web.HTTPFound("/")
            if request.query.get("r") == None
            else web.HTTPFound("/?r=1")
        )
    except AssertionError:
        logger.warn(
            "error when logging in %s. queries: %s discord api response: %s"
            % (who(session, request), request.query, response)
        )
        return web.HTTPFound(
            "/?error=An+error+has+occurred+while+trying+to+log+in.+Please+try+again.+If+the+issue+persists+please+PM+me%2C+mateuszdrwal%239960"
        )


@routes.get("/logout")
async def logout(request):
    session = await get_session(request)
    if "username" in session:
        logger.info("%s logging out" % session["username"])
    else:
        logger.warn("%s logging out without being logged in" % who(session, request))
    session.invalidate()
    return web.HTTPFound("/")


@routes.get("/spreadsheet")
async def spreadsheet(request):
    return web.HTTPFound(
        "https://docs.google.com/spreadsheets/d/1zfvvJw3wOBEZX3Rn2Xmzq66z6IZ8DH_IU-p9vISo5R0/edit?usp=sharing"
    )


@routes.post("/api/vote")
async def vote(request):
    try:
        session = await get_session(request)
        if session.get("username") == None:
            return web.HTTPFound("/login")  # redirect if not logged in
        assert (
            "id" in request.query
            and "target" in request.query
            and "up" in request.query
        )  # all queries are present
        assert (
            len(request.query["id"]) == 18
            and request.query["target"] in ["0", "1"]
            and request.query["up"] in ["0", "1"]
        )  # query data is valid
        c.execute(
            "SELECT * FROM requests WHERE mid = :mid", {"mid": request.query["id"]}
        )
        fetched = c.fetchall()
        assert fetched != []  # request exists
        assert int(fetched[0][10]) != int(session["id"])  # not voting on yourself
        c.execute(
            "SELECT * FROM votes WHERE mid = :mid AND uid = :uid",
            {"mid": request.query["id"], "uid": session["id"]},
        )
        fetched = c.fetchall()
        if fetched != []:
            if int(request.query["up"]):
                assert not fetched[0][4]  # not voted on discord
            else:
                assert not fetched[0][5]  # not voted on discord

        if fetched == []:
            if int(request.query["up"]):
                c.execute(
                    "INSERT INTO votes VALUES (:mid, :uid, :target, 0, 0, 0)",
                    {
                        "target": int(request.query["target"]),
                        "mid": request.query["id"],
                        "uid": session["id"],
                    },
                )
            else:
                c.execute(
                    "INSERT INTO votes VALUES (:mid, :uid, 0, :target, 0, 0)",
                    {
                        "target": int(request.query["target"]),
                        "mid": request.query["id"],
                        "uid": session["id"],
                    },
                )
        else:
            if int(request.query["up"]):
                c.execute(
                    "UPDATE votes SET up = :target WHERE mid = :mid AND uid = :uid",
                    {
                        "target": int(request.query["target"]),
                        "mid": request.query["id"],
                        "uid": session["id"],
                    },
                )
            else:
                c.execute(
                    "UPDATE votes SET down = :target WHERE mid = :mid AND uid = :uid",
                    {
                        "target": int(request.query["target"]),
                        "mid": request.query["id"],
                        "uid": session["id"],
                    },
                )
        conn.commit()
        await updateRequest(await requestChannel.get_message(request.query["id"]))
        logger.info(
            "%s %svoted %s setting %svote"
            % (
                session["username"],
                "" if int(request.query["target"]) else "un",
                request.query["id"],
                "up" if int(request.query["up"]) else "down",
            )
        )
        return web.Response(text="OK")
    except (AssertionError, ValueError):
        logger.warning("%s is being suspicious" % who(session, request))
        return web.HTTPBadRequest()


@routes.post("/api/newrequest")
async def newrequest(request):
    data = await request.post()
    session = await get_session(request)
    try:
        assert "title" in data and "mode" in data and "description" in data
        assert len(data["title"]) <= 100 and len(data["description"]) <= 1500
        assert data["mode"] in GAME_MODES
        assert "username" in session
    except AssertionError:
        logger.warning("%s is being suspicious with data:" % who(session, request))
        logger.debug(data)
        logger.debug(session)
        return web.HTTPBadRequest()

    try:
        assert client.get_user(int(session["id"])) != None
    except AssertionError:
        logger.info(
            "%s tried making a request without being in the discord"
            % who(session, request)
        )
        return web.HTTPFound(
            "/?error=You%20are%20trying%20to%20create%20a%20request%20with%20a%20discord%20account%20that%20is%20not%20in%20the%20Replit%20discord.%20Please%20make%20sure%20you%20are%20logged%20on%20to%20the%20correct%20discord%20account%20or%20join%20the%20Replit%20discord."
        )

    user = client.get_user(int(session["id"]))
    message = await requestChannel.send(
        "New request submitted from website by %s:\n\n**Title**: %s\n**Game mode**: %s\n**Description**: %s"
        % (user.mention, data["title"], data["mode"], data["description"])
    )
    await message.add_reaction("\U0001F44D")
    await message.add_reaction("\U0001F44E")
    c.execute(
        "INSERT INTO requests VALUES (:created, :author, '', :title, '', :description, 0, 0, 0, :mid, :uid, '', 0, 0, :mode)",
        {
            "created": time.time(),
            "author": "%s#%s" % (user.name, user.discriminator),
            "title": html.escape(data["title"]),
            "mode": html.escape(data["mode"]),
            "description": html.escape(data["description"]),
            "mid": message.id,
            "uid": user.id,
        },
    )
    conn.commit()
    await analyzeMessage(message)
    logger.info(
        '%s created a request titled "%s"' % (session["username"], data["title"])
    )
    return web.HTTPFound("/?success=Request%20created%21")


@routes.post("/api/devresp")
async def devresp(request):
    data = await request.post()
    session = await get_session(request)
    try:
        assert "id" in data and "devresp" in data
        assert len(data["id"]) == 18
        assert "username" in session
        assert session["admin"]
        assert data["devresp"] != ""
        int(data["id"])
        c.execute("SELECT * FROM requests WHERE mid = :mid", {"mid": data["id"]})
        assert c.fetchall() != []
    except AssertionError:
        logger.warning("%s is being suspicious with data:" % who(session, request))
        logger.debug(data)
        return web.HTTPBadRequest()
    except ValueError:
        logger.warning("%s is being suspicious with data:" % who(session, request))
        logger.debug(data)
        return web.HTTPBadRequest()

    c.execute(
        "INSERT INTO responses VALUES (:mid, 0, :resp, :author)",
        {"mid": data["id"], "resp": data["devresp"], "author": session["username"]},
    )
    conn.commit()
    await updateRequest(await requestChannel.get_message(data["id"]))
    logger.info("%s responded to %s" % (session["username"], data["id"]))
    return web.Response(text="OK")


@routes.post("/api/remove")
async def remove(request):
    session = await get_session(request)
    try:
        assert "id" in request.query
        assert len(request.query["id"]) == 18
        int(request.query["id"])
        assert "username" in session
        assert session["admin"]
    except (AssertionError, ValueError):
        logger.warning("%s is being suspicious" % who(session, request))
        return web.HTTPBadRequest()

    c.execute(
        "UPDATE requests SET disabled = 1 WHERE mid = :mid",
        {"mid": request.query["id"]},
    )
    conn.commit()
    logger.info("%s removed %s" % (session["username"], request.query["id"]))
    return web.Response(text="OK")


@routes.post("/api/status")
async def status(request):
    session = await get_session(request)
    try:
        assert "id" in request.query and "target" in request.query
        assert len(request.query["id"]) == 18
        int(request.query["id"])
        assert "username" in session
        assert session["admin"]
        int(request.query["target"])
        assert 0 <= int(request.query["target"]) < 5
    except (AssertionError, ValueError):
        logger.warning("%s is being suspicious" % who(session, request))
        return web.HTTPBadRequest()

    c.execute(
        "UPDATE requests SET status = :status, webStatus = :webStatus WHERE mid = :mid",
        {
            "status": request.query["target"],
            "webStatus": 1 if int(request.query["target"]) != 0 else 0,
            "mid": request.query["id"],
        },
    )
    conn.commit()
    logger.info(
        "%s updated status of %s to %s"
        % (
            session["username"],
            request.query["id"],
            ["Open", "Planned", "Rejected", "Implemented", "Not applicable anymore"][
                int(request.query["target"])
            ],
        )
    )
    return web.Response(text="OK")


@routes.post("/api/mode")
async def mode(request):
    session = await get_session(request)
    try:
        assert "id" in request.query and "target" in request.query
        assert len(request.query["id"]) == 18
        int(request.query["id"])
        assert "username" in session
        assert session["admin"]
        assert request.query["target"] in GAME_MODES
    except (AssertionError, ValueError):
        logger.warning("%s is being suspicious" % who(session, request))
        return web.HTTPBadRequest()

    c.execute(
        "UPDATE requests SET mode = :mode WHERE mid = :mid",
        {"mode": request.query["target"], "mid": request.query["id"]},
    )
    conn.commit()
    logger.info(
        "%s updated mode of %s to %s"
        % (session["username"], request.query["id"], request.query["target"])
    )
    return web.Response(text="OK")


@routes.get("/robots.txt")
async def robots(request):
    return web.Response(
        text="""
User-agent: *
Disallow: /api/
Disallow: /login
Disallow: /logout
Disallow: /auth

Allow: /api/requests
Sitemap: https://demorequests.mateuszdrwal.com/sitemap.txt 
"""
    )


@routes.get("/sitemap.txt")
async def siteamp(request):

    c.execute("SELECT * FROM requests WHERE disabled = 0")
    fetched = c.fetchall()

    string = "\n".join(
        "https://demorequests.mateuszdrwal.com/request/%s" % request[9]
        for request in fetched
    )

    return web.Response(text=string)


from cryptography import fernet

cookiekey = os.environ.get("COOKIE_KEY").encode()

app.router.add_static("/static", "static")
setup(app, EncryptedCookieStorage(base64.b64decode(cookiekey)))
app.add_routes(routes)
web.run_app(app, port=50000)