@L11K/

Guard

Python

Stufff

fork
loading
Files
  • main.py
  • .gitignore
  • bot.db
  • bot.sh
  • config.json
  • DMs.txt
  • README.md
  • requirements.txt
  • User.py
  • Utils.py
  • Visualize.py
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
"""
Bouncer
Written by aquova, 2018-2019
https://github.com/aquova/bouncer
"""

import discord, json, sqlite3, datetime, asyncio, os, subprocess, sys
import Utils
from User import User

from flask import Flask
from threading import Thread

app = Flask('Server Royal Guard')


@app.route('/')
def hello_world():
    return 'beep DIO'


def start_server():
    app.run(host='0.0.0.0', port=8080)


t = Thread(target=start_server)
t.start()

# Reading values from config file
with open('config.json') as config_file:
    cfg = json.load(config_file)

# The first entry in validInputChannels is the one DMs are sent
validInputChannels = cfg['channels']['listening']
# Channel to save notes/warns/etc
logChannel = (cfg['channels']['log'])
# Channel to save system logs - leaves, bans, joins, etc
systemLog = (cfg['channels']['syslog'])
ServerID = os.environ.get("SERVERID")
validRoles = cfg['roles']

sendBanDM = (cfg['DM']['ban'].upper() == "ON")
sendWarnDM = (cfg['DM']['warn'].upper() == "ON")

client = discord.Client()

# Notes on database structure:
# Most of the columns are self explanitory
# num column is the category of the infraction
# 0: Ban
# >0: The number of the warning
# -1: Note
# -2: Kick
# -3: Unban

sqlconn = sqlite3.connect('bot.db')
sqlconn.execute(
    "CREATE TABLE IF NOT EXISTS badeggs (dbid INT PRIMARY KEY, id INT, username TEXT, num INT, date DATE, message TEXT, staff TEXT, post INT);"
)
sqlconn.execute("CREATE TABLE IF NOT EXISTS blocks (id TEXT);")
sqlconn.execute(
    "CREATE TABLE IF NOT EXISTS staffLogs (staff TEXT PRIMARY KEY, bans INT, warns INT);"
)
sqlconn.execute(
    "CREATE TABLE IF NOT EXISTS monthLogs (month TEXT PRIMARY KEY, bans INT, warns INT);"
)
sqlconn.commit()
sqlconn.close()

warnThreshold = 3
reviewThreshold = 6  # In months

# Containers to store needed information in memory
recentBans = {}
blockList = []
ignoredUsers = ["91911303181897728"]
ignoredChannels = [
    "362803288405704705", "546108637110730759", "546108608178421790"
]

helpInfo = {
    '$WARN': '`$warn USER reason`',
    '$BAN': '`$ban USER reason`',
    '$UNBAN': '`$unban USER reason`',
    '$KICK': '`$kick USER reason`',
    '$SEARCH': '`$search USER`',
    '$NOTE': '`$note USER message',
    '$REMOVE': '`$remove USER',
    '$BLOCK': '`$block USER`',
    '$UNBLOCK': '`$unblock USER',
    '$REPLY': '`$reply USER`'
}


# This is basically a makeshift enum
class LogTypes:
    UNBAN = -3
    KICK = -2
    NOTE = -1
    BAN = 0
    WARN = 1


# Searches the database for the specified user, given a message
# m: Discord message object
async def userSearch(m):
    try:
        user = User(m, recentBans)
    except User.MessageError:
        await client.send_message(
            m.channel,
            "I wasn't able to find a user anywhere based on that message. `$search USER`"
        )
        return

    searchResults = user.search()
    try:
        username = user.getName(recentBans)
        if searchResults == []:
            await client.send_message(
                m.channel,
                "User {} was not found in the database\n".format(username))
            return
    except User.MessageError:
        await client.send_message(
            m.channel,
            "That user was not found in the database or the server\n")
        return

    out = "User {} was found with the following infractions \n".format(
        username)
    for index, item in enumerate(searchResults):
        out += "{}. ".format(index + 1)
        if item[1] == LogTypes.BAN:
            out += "\n [{}] \n **{}** has been Banned \n **By** {} \n **Reason**: {}\n---".format(
                Utils.formatTime(item[2]), item[0], item[4], item[3])
        elif item[1] == LogTypes.NOTE:
            out += "\n [{}] **{}** - Note by {} - {}\n".format(
                Utils.formatTime(item[2]), item[0], item[4], item[3])
        elif item[1] == LogTypes.KICK:
            out += "\n [{}] \n **{}** has been Kicked \n By {} \n **Reason**: {}\n".format(
                Utils.formatTime(item[2]), item[0], item[4], item[3])
        elif item[1] == LogTypes.UNBAN:
            out += "\n [{}] \n **{}** has been Unbanned \n **By** {} \n **Reason**: {}\n -".format(
                Utils.formatTime(item[2]), item[0], item[4], item[3])
        else:
            out += "\n [{}] \n **{}** - \n **Warning** ``#{}`` \n **By** ``{}`` \n **Reason**: ``{}``\n".format(
                Utils.formatTime(item[2]), item[0], item[1], item[4], item[3])

        if item[1] >= warnThreshold:
            out += "They have received {} warnings, it is recommended that they be banned.\n".format(
                warnThreshold)
    await client.send_message(m.channel, out)


# Note a warn or ban for a user
# m: Discord message object
async def logUser(m, state):
    try:
        user = User(m, recentBans)
    except User.MessageError:
        if state == LogTypes.NOTE:
            await client.send_message(
                m.channel,
                "I wasn't able to understand that message: `$note USER`")
        else:
            await client.send_message(
                m.channel,
                "I wasn't able to understand that message: `$log USER`")
        return

    sqlconn = sqlite3.connect('bot.db')
    if state == LogTypes.WARN:
        count = sqlconn.execute(
            "SELECT COUNT(*) FROM badeggs WHERE id=? AND num > 0",
            [user.id]).fetchone()[0] + 1
    else:
        count = state
    globalcount = sqlconn.execute("SELECT COUNT(*) FROM badeggs").fetchone()[0]
    currentTime = datetime.datetime.utcnow()

    try:
        username = user.getName(recentBans)
    except User.MessageError:
        username = "ID: " + str(user.id)
        await client.send_message(
            m.channel,
            "I wasn't able to find a username for that user, but whatever, I'll do it anyway."
        )

    mes = Utils.parseMessage(m.content, username)
    if len(m.attachments) != 0:
        for item in m.attachments:
            mes += '\n{}'.format(item['url'])

    if mes == "":
        await client.send_message(
            m.channel, "Please give a reason for why you want to log them.")
        return

    params = [
        globalcount + 1, user.id, username, count, currentTime, mes,
        m.author.name
    ]

    # Generate message for log channel
    import Visualize
    u = user.getMember()
    ServerBanList = await client.get_bans(m.server)
    if state == LogTypes.BAN:
      if u != None:    
        if user in ServerBanList:
            await client.send_message(
                m.channel,
                "__{}__ Seems to be already banned, check your ban list.".
                format(params[2]))
            return
        logMessage = "[{}] \n **{}** has been Banned \n **By**: {} \n **Reason**: {}\n".format(
            Utils.formatTime(currentTime), params[2], m.author.name, mes)
        Visualize.updateCache(sqlconn, m.author.name, (1, 0),
                              Utils.formatTime(currentTime))
    elif state == LogTypes.WARN:
        logMessage = "[{}] \n **{}** - Warning #{} By: {} - {}\n".format(
            Utils.formatTime(currentTime), params[2], count, m.author.name,
            mes)
        Visualize.updateCache(sqlconn, m.author.name, (0, 1),
                              Utils.formatTime(currentTime))
    elif state == LogTypes.KICK:
        #u = user.getMember()
        if u != None:
            logMessage = "[{}] \n **{}** has been Kicked \n **By**: {} \n**Reason**: {}\n".format(
                Utils.formatTime(currentTime), params[2], m.author.name, mes)
        else:
            if u == None:
                await client.send_message(
                    m.channel,
                    "Sorry, but they need to be in the server for me to kick them"
                )
                return
    elif state == LogTypes.UNBAN:
        ServerBanList = await client.get_bans(m.server)
        if u != None:
            if user in ServerBanList:
                await client.unban(u)
                return await client.send_message(m.channel, "[{}] \n **{}** has been Unbanned \n **By**: {} **Reason**: {}\n".format(
            Utils.formatTime(currentTime), params[2], m.author.name, mes))

            else:    
                if user not in ServerBanList:
                    await client.send_message(
                        m.channel,
                        "**__{}__** doesn't seem to be banned, check the ban list."
                        .format(params[2]))
                    return
                    
        logMessage = "[{}] \n **{}** has been Unbanned \n **By**: {} **Reason**: {}\n".format(
            Utils.formatTime(currentTime), params[2], m.author.name, mes)
        Visualize.updateCache(sqlconn, m.author.name, (-1, 0),
                              Utils.formatTime(currentTime))

    else:
        logMessage = "Note made for {}".format(username)

    await client.send_message(m.channel, logMessage)

    # Send ban recommendation, if needed
    if (count >= warnThreshold):
        await client.send_message(
            m.channel,
            "This user has received {} warnings or more. It is recommended that they be banned."
            .format(warnThreshold))

    logMesID = 0
    if state != LogTypes.NOTE:
        # Send message to log channel
        try:
            logMes = await client.send_message(
                client.get_channel(logChannel), logMessage)
            logMesID = logMes.id
        except discord.errors.InvalidArgument:
            await client.send_message(
                m.channel,
                "The logging channel has not been set up in `config.json`. In order to have a visual record, please specify a channel ID."
            )

        # Send a DM to the user
        try:
            u = user.getMember()
            if u != None:
                if state == LogTypes.BAN and sendBanDM:
                    await client.send_message(
                        u, "Hi there! You've been banned for : ```{}```".
                        format(mes))
                if user not in ServerBanList:
                    #await client.ban(u)

                elif state == LogTypes.WARN and sendWarnDM:
                    await client.send_message(
                        u,
                        "Hi there! You received warning ``#{}`` for : ```{}```"
                        .format(count, mes))
                elif state == LogTypes.KICK and sendBanDM:
                    await client.send_message(
                        u, "Hi there! You've been kicked for : ```{}```".
                        format(mes))
                    #await client.kick(u)

        # I don't know if any of these are ever getting tripped
        except discord.errors.HTTPException as e:
            await client.send_message(
                m.channel,
                "ERROR: While attempting to DM, there was an unexpected error. Tell L-11 this: ```js\n{}```"
                .format(e))
        except discord.errors.Forbidden:
            await client.send_message(
                m.channel,
                "ERROR: I am not allowed to DM the user. It is likely that they are not accepting DM's from me."
            )
        except discord.errors.NotFound:
            await client.send_message(
                m.channel,
                "ERROR: I was unable to find the user to DM. I'm unsure how this can be the case, unless their account was deleted."
            )

    # Update database
    params.append(logMesID)
    sqlconn.execute(
        "INSERT INTO badeggs (dbid, id, username, num, date, message, staff, post) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        params)
    sqlconn.commit()
    sqlconn.close()


# Removes last database entry for specified user
# m: Discord message object
async def removeError(m):
    try:
        user = User(m, recentBans)
    except User.MessageError:
        await client.send_message(
            m.channel,
            "I wasn't able to understand that message: `$remove USER`")
        return

    # Needed for multi-word usernames
    try:
        username = user.getName(recentBans)
    except User.MessageError:
        username = str(user.id)

    mes = Utils.parseMessage(m.content, username)
    if mes == "":
        mes = 0

    try:
        index = int(mes) - 1
    except IndexError:
        index = -1
    except ValueError:
        await client.send_message(
            m.channel,
            "I don't know what `{}` is but I'm pretty sure it's not a number.".
            format(m.content.split(" ")[2]))
        return

    # Find most recent entry in database for specified user
    sqlconn = sqlite3.connect('bot.db')
    searchResults = sqlconn.execute(
        "SELECT dbid, username, num, date, message, staff, post FROM badeggs WHERE id=?",
        [user.id]).fetchall()

    if searchResults == []:
        await client.send_message(m.channel,
                                  "I couldn't find that user in the database")
    elif (index > len(searchResults) - 1) or index < -1:
        await client.send_message(
            m.channel,
            "I can't remove item number {}, there aren't that many for this user"
            .format(index + 1))
    else:
        item = searchResults[index]
        sqlconn.execute(
            "REPLACE INTO badeggs (dbid, id, username, num, date, message, staff, post) VALUES (?, NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
            [item[0]])

        import Visualize
        out = "The following log was deleted:\n"
        if item[2] == LogTypes.BAN:
            out += "[{}] \n **{}** has been Banned \n **By** {} \n **Reason**: {}\n".format(
                Utils.formatTime(item[3]), item[1], item[5], item[4])
            Visualize.updateCache(sqlconn, item[5], (-1, 0),
                                  Utils.formatTime(item[3]))
        elif item[2] == LogTypes.NOTE:
            out += "[{}] \n **{}** - Note by {} - {}\n".format(
                Utils.formatTime(item[3]), item[1], item[5], item[4])
        elif item[2] == LogTypes.UNBAN:
            out += "[{}] \n **{}** has been Unbanned \n **By** {} \n **Reason**: {}\n".format(
                Utils.formatTime(item[3]), item[1], item[5], item[4])
            Visualize.updateCache(sqlconn, item[5], (1, 0),
                                  Utils.formatTime(item[3]))
        elif item[2] == LogTypes.KICK:
            out += "[{}] \n **{}** has been Kicked \n **By** {} \n **Reason**: {}\n".format(
                Utils.formatTime(item[3]), item[1], item[5], item[4])
        else:
            out += "[{}] \n **{}** - Warning ``#{}``\n **By** {} - {}\n".format(
                Utils.formatTime(item[3]), item[1], item[2], item[5], item[4])
            Visualize.updateCache(sqlconn, item[5], (0, -1),
                                  Utils.formatTime(item[3]))
        await client.send_message(m.channel, out)

        # Search logging channel for matching post, and remove it
        if item[6] != 0:
            async for m in client.logs_from(client.get_channel(logChannel)):
                if str(m.id) == str(item[6]):
                    await client.delete_message(m)
                    break
    sqlconn.commit()
    sqlconn.close()


# Prevents DM from a specific user from being forwarded
# message: Discord message object
# block: Boolean, true for block, false for unblock
async def blockUser(m, block):
    global blockList
    try:
        user = User(m, recentBans)
    except User.MessageError:
        await client.send_message(
            m.channel,
            "I wasn't able to understand that message: `$block USER`")
        return

    sqlconn = sqlite3.connect('bot.db')
    if block:
        if user.id in blockList:
            await client.send_message(
                m.channel, "Um... That user was already blocked...")
        else:
            sqlconn.execute("INSERT INTO blocks (id) VALUES (?)", [user.id])
            blockList.append(user.id)
            await client.send_message(
                m.channel,
                "I have now blocked {}. Their messages will no longer display in chat, but they will be logged for later review."
                .format(user.id))
    else:
        if user.id not in blockList:
            await client.send_message(m.channel,
                                      "That user hasn't been blocked...")
        else:
            sqlconn.execute("DELETE FROM blocks WHERE id=?", [user.id])
            blockList.remove(user.id)
            await client.send_message(
                m.channel,
                "I have now unblocked {}. You will once again be able to hear their dumb bullshit in chat."
                .format(user.id))
    sqlconn.commit()
    sqlconn.close()


# Sends a private message to the specified user
async def reply(m):
    try:
        user = User(m, recentBans)
    except User.MessageError:
        await client.send_message(
            m.channel,
            "I wasn't able to understand that message: `$reply USER`")
        return

    u = user.getMember()
    if u == None:
        await client.send_message(
            m.channel,
            "Sorry, but they need to be in the server for me to message them")
        return
    try:
        ts = m.timestamp.strftime('%Y-%m-%d %H:%M:%S')
        uname = "{}#{}".format(u.name, u.discriminator)
        with open("DMs.txt", 'a', encoding='utf-8') as openFile:
            openFile.write("{} - {} sent a DM to {}: {}\n".format(
                ts, m.author.name, uname, Utils.removeCommand(m.content)))
        await client.send_message(
            u, "A message from the Server staff: {}".format(
                Utils.removeCommand(m.content)))
        await client.send_message(m.channel,
                                  "Message sent to {}.".format(uname))

    # I don't know if any of these are ever getting tripped
    except discord.errors.HTTPException as e:
        await client.send_message(
            m.channel,
            "ERROR: While attempting to DM, there was an unexpected error. Tell L-11 this: {}"
            .format(e))
    except discord.errors.Forbidden:
        await client.send_message(
            m.channel,
            "ERROR: I am not allowed to DM the user. It is likely that they are not accepting DM's from me."
        )
    except discord.errors.NotFound:
        await client.send_message(
            m.channel,
            "ERROR: I was unable to find the user to DM. I'm unsure how this can be the case, unless their account was deleted"
        )


async def notebook(m):
    sqlconn = sqlite3.connect('bot.db')
    allNotes = sqlconn.execute("SELECT * FROM badeggs WHERE num=-1").fetchall()
    sqlconn.commit()
    sqlconn.close()

    out = "You asked for it...\n"
    for item in allNotes:
        note = "[{}] **{}** - Note by {} - {}\n".format(
            Utils.formatTime(item[4]), item[2], item[6], item[5])
        if len(note) + len(out) < 2000:
            out += note
        else:
            await client.send_message(m.channel, out)
            out = note
    await client.send_message(m.channel, out)


# Posts the usernames of all users whose oldest logs are older than reviewThreshold
async def userReview(channel):
    # There's probably a clever way to have these first two arrays merged
    usernames = []
    ids = []
    tooNew = []
    sqlconn = sqlite3.connect("bot.db")
    # Reverse order so newest logs are checked/eliminated first
    allLogs = sqlconn.execute(
        "SELECT id, username, date, num FROM badeggs WHERE num > -1").fetchall(
        )[::-1]

    now = datetime.datetime.now()
    for log in allLogs:
        # Don't want to list users who have been banned
        if log[3] == 0:
            tooNew.append(log[0])
        if log[0] not in ids and log[0] not in tooNew:
            day = log[2].split(" ")[0]
            dateval = datetime.datetime.strptime(day, "%Y-%m-%d")
            testDate = dateval + datetime.timedelta(days=30 * reviewThreshold)
            if testDate < now:
                ids.append(log[0])
                usernames.append(log[1])
            else:
                tooNew.append(log[0])

    sqlconn.close()

    mes = "These users had their most recent log greater than {} months ago.\n".format(
        reviewThreshold)
    mes2 = "No logs found"
    # Reverse order so oldest are first
    for user in usernames[::-1]:
        # This gets past Discord's 2000 char limit
        if len(mes) + len(user) + 2 < 2000:
            mes += "`{}`, ".format(user)
        else:
            await client.send_message(channel, mes)
            mes = "`{}`, ".format(user)

    await client.send_message(channel, mes)


@client.event
async def on_ready():
    global blockList
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)

    sqlconn = sqlite3.connect('bot.db')
    blockDB = sqlconn.execute("SELECT * FROM blocks").fetchall()
    blockList = [x[0] for x in blockDB]
    sqlconn.close()

    game_object = discord.Game(
        name="Your every conversation, just like master.", type=3)
    await client.change_presence(
        game=game_object, status=discord.Status('dnd'))


"""@client.event
async def on_member_update(before, after):
    if before.nick != after.nick:
        if after.nick == None:
            mes = "**{}#{}** has reset their username".format(after.name, after.discriminator)
        else:
            new = after.nick
            mes = "**{}#{}** is now known as `{}`".format(after.name, after.discriminator, after.nick)
        await client.send_message(client.get_channel(systemLog), mes)
    elif before.roles != after.roles:
        if len(before.roles) > len(after.roles):
            missing = [r for r in before.roles if r not in after.roles]
            mes = "**{}#{}** had the role `{}` removed.".format(after.name, after.discriminator, missing[0])
        else:
            newRoles = [r for r in after.roles if r not in before.roles]
            mes = "**{}#{}** had the role `{}` added.".format(after.name, after.discriminator, newRoles[0])
        await client.send_message(client.get_channel(systemLog), mes)"""


@client.event
async def on_member_ban(member):
    global recentBans
    recentBans[member.id] = "{}#{}".format(member.name, member.discriminator)
    mes = "{}#{} has been banned.".format(member.name, member.discriminator)
    await client.send_message(client.get_channel(logChannel), mes)


#@client.event
#async def on_member_unban(member):
#    mes = "{}#{} has been unbanned.".format(member.name, member.discriminator)
#    await client.send_message(client.get_channel(logChannel), mes)


@client.event
async def on_member_remove(member):
    # I know they aren't banned, but still we may want to log someone after they leave
    global recentBans
    recentBans[member.id] = "{}#{}".format(member.name, member.discriminator)
    mes = "**{}#{}** has left".format(member.name, member.discriminator)
    await client.send_message(client.get_channel(systemLog), mes)


@client.event
async def on_message_delete(message):
    if message.author.bot is False or message.author.id not in ignoredUsers:
        mes = "**{}#{}** Deleted in <#{}>: ```{}```".format(
            message.author.name, message.author.discriminator,
            message.channel.id, message.content)
        if message.attachments != []:
            for item in message.attachments:
                mes += '\n' + item['url']
        if message.channel.id not in ignoredChannels:
            await client.send_message(client.get_channel(systemLog), mes)


@client.event
async def on_message_edit(before, after):
    # This is to prevent embeding of content from triggering the log
    if before.content == after.content:
        return

    try:
        if len(before.content) + len(after.content) > 200:
            mes1 = "\n **{}#{}** modified in <#{}>: ```{}```".format(
                before.author.name, before.author.discriminator,
                before.channel.id, before.content)
            mes2 = "\n To `{}` \n".format(after.content)
            if before.attachments != []:
                for item in before.attachments:
                    mes1 += '\n' + item['url']
            if after.attachments != []:
                for item in after.attachments:
                    mes2 += '\n' + item['url']
            await client.send_message(client.get_channel(systemLog), mes1)
            await client.send_message(client.get_channel(systemLog), mes2)
        else:
            mes = "\n **{}#{}** modified in <#{}>: ```{}``` \n To `{}` \n".format(
                before.author.name, before.author.discriminator,
                before.channel.id, before.content, after.content)
            if after.attachments != []:
                for item in after.attachments:
                    mes += '\n' + item['url']
            await client.send_message(client.get_channel(systemLog), mes)
    except discord.errors.HTTPException as e:
        print(
            "Unknown error with editing message. This message was unable to post for this reason: {}\n"
            .format(e))


#@client.event
#async def on_member_join(member):
#mes = "**{}#{}** has joined".format(member.name, member.discriminator)
#await client.send_message(client.get_channel(systemLog), mes)
"""@client.event
async def on_voice_state_update(before, after):
    if (after.voice.voice_channel == None):
        mes = "**{}#{}** has left voice channel {}".format(after.name, after.discriminator, before.voice.voice_channel.name)
        await client.send_message(client.get_channel(systemLog), mes)
    elif (before.voice.voice_channel == None):
        mes = "**{}#{}** has joined voice channel {}".format(after.name, after.discriminator, after.voice.voice_channel.name)
        await client.send_message(client.get_channel(systemLog), mes)"""


@client.event
async def on_message(message):
    global validInputChannels
    global logChannel
    if message.author.id == client.user.id:
        return
    try:
        # If they sent a private DM to bouncer
        if message.channel.is_private:
            # Regardless of blocklist or not, log their messages
            ts = message.timestamp.strftime('%Y-%m-%d %H:%M:%S')

            mes = "**{}#{}** (ID: {}): {}".format(
                message.author.name, message.author.discriminator,
                message.author.id, message.content)
            if message.attachments != []:
                for item in message.attachments:
                    mes += '\n' + item['url']

            with open("DMs.txt", 'a', encoding='utf-8') as openFile:
                openFile.write("{} - {}\n".format(ts, mes))
            await client.send_message(
                client.get_channel(validInputChannels[0]), mes)

        # Temporarily notify if UB3R-BOT has removed something on its word censor
        #elif (message.author.id == "85614143951892480" and message.channel.id == "233039273207529472") and ("Word Censor Triggered" in message.content):
        #await client.send_message(client.get_channel(validInputChannels[0]), "Uh oh, looks like the censor might've been tripped.")

        # If a user pings bouncer
        elif client.user in message.mentions:
            mes = "**{}#{}** (ID: {}) pinged me in <#{}>: {}".format(
                message.author.name, message.author.discriminator,
                message.author.id, message.channel.id, message.content)
            if message.attachments != []:
                for item in message.attachments:
                    mes += '\n' + item['url']
            mes += "\nhttps://discordapp.com/channels/{}/{}/{}".format(
                message.server.id, message.channel.id, message.id)
            await client.send_message(
                client.get_channel(validInputChannels[0]), mes)

        # If they have privledges to access bouncer functions
        elif (message.channel.id in validInputChannels) and Utils.checkRoles(
                message.author, validRoles):
            if len(message.content.split(" ")) == 1:
                if message.content.upper() == "$HELP":
                    helpMes = "Issue a warning: `$warn USER message`\nLog a ban: `$ban USER reason`\nLog an unbanning: `$unban USER reason`\nLog a kick: `$kick USER reason`\nSearch for a user: `$search USER`\nCreate a note about a user: `$note USER message`\nShow all notes: `$notebook`\nRemove a user's last log: `$remove USER index(optional)`\nStop a user from sending DMs to us: `$block/$unblock USERID`\nReply to a user in DMs: `$reply USERID`\nPlot warn/ban stats: `$graph`\nReview which users have old logs: `$review`\nDMing users when they are banned is `{}`\nDMing users when they are warned is `{}`".format(
                        sendBanDM, sendWarnDM)
                    await client.send_message(message.channel, helpMes)
                elif message.content.upper() == "$NOTEBOOK":
                    await notebook(message)
                elif message.content.upper() in helpInfo.keys():
                    await client.send_message(
                        message.channel, helpInfo[message.content.upper()])
                elif message.content.upper(
                ) == "$UPDATE" and message.author.id == "91911303181897728":
                    await client.send_message(message.channel,
                                              "Updating and restarting...")
                    subprocess.call("git pull", shell=True)
                    sys.exit()
                elif message.content.upper() == "$GRAPH":
                    import Visualize  # Import here to avoid debugger crashing from matplotlib issue
                    Visualize.genUserPlot()
                    Visualize.genMonthlyPlot()
                    await client.send_file(
                        message.channel, fp='./user_plot.png')
                    await client.send_file(
                        message.channel, fp='./month_plot.png')
                elif message.content.upper() == "$REVIEW":
                    await userReview(message.channel)
                return

            if message.content.startswith("$search"):
                await userSearch(message)
            elif message.content.startswith("$warn"):
                await logUser(message, LogTypes.WARN)
            elif message.content.startswith("$ban"):
                await logUser(message, LogTypes.BAN)
            elif message.content.startswith("$kick"):
                #if userSearch != None:
                await logUser(message, LogTypes.KICK)
            elif message.content.startswith("$unban"):
                await logUser(message, LogTypes.UNBAN)
            elif message.content.startswith("$remove"):
                await removeError(message)
            elif message.content.startswith("$block"):
                await blockUser(message, True)
            elif message.content.startswith("$unblock"):
                await blockUser(message, False)
            elif message.content.startswith("$reply"):
                await reply(message)
            elif message.content.startswith("$note"):
                await logUser(message, LogTypes.NOTE)

    except discord.errors.HTTPException:
        pass


#Runs the bot
token = os.environ.get("TOKEN")
client.run(token)