summaryrefslogtreecommitdiff
path: root/main.py
blob: 37fe9661496f9e1dcc52c860478ac086a0a399c2 (plain)
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
#!/usr/bin/env python3
import pymongo
import discord
import asyncio
import threading
import logging

import parsedatetime
import datetime


TOKEN = "MjM5NzI3NzQ2Nzk0NzgyNzIw.Cu5BbA.z7bkO3Ncd_L80htVzREHYDsEGNk"
VERSION = "v0.1.0"

MODMIRROR = "266921381634113537"
MIRROR_IGNORE = ["237194769116168192"] # bot_spam

client = pymongo.MongoClient()
db = client.vainbot

cli = discord.Client()

@cli.event
async def on_ready():
    log.warning("Logged in as " + cli.user.name + " (" + str(cli.user.id) + ")")


async def get_user(id):
    now = datetime.datetime.utcnow()
    user = db.usercache.find_one({
        "id": id,
        "date": {"$gt": now - datetime.timedelta(minutes=30)}
    })
    if user:
        return user
    user = await cli.get_user_info(id)
    db.usercache.insert_one({
        "id": id,
        "mention": user.mention,
        "date": now
    })
    return await get_user(id)

async def search_teammates(server, channel, who, query, notify=True):
    cal = parsedatetime.Calendar()
    now = cal.parseDT("now")[0]

    if " for " in query or " until " in query:
        delimit = query.rfind("for")
        if delimit == -1:
            delimit = query.rfind("until")

        startstr = query[:delimit]
        endstr = query[delimit:]
    else:
        startstr = query
        endstr = "for 30 minutes"

    start = cal.parseDT(startstr)[0]
    end = cal.parseDT(endstr, sourceTime=start)[0]

    if notify:
        queueid = db.playwithme.insert_one({
            "player": who.id,
            "start": start,
            "end": end
        }).inserted_id

        playrole = [r for r in server.roles if r.name == "play"][0]
        await cli.send_message(channel, who.mention + " You have been put into the queue.")
        await asyncio.sleep((start-now).total_seconds())
        await cli.add_roles(who, playrole)
        await cli.send_message(channel, "%s You were given the 'play' role and will be in queue for %s minutes." % (who.mention, int((end-start).total_seconds() // 60)))

    players = []
    query = { "$or": [
            { "start": {
                    "$gte": start,
                    "$lte": end } },
            { "end": {
                    "$gte": start,
                    "$lte": end } },
            { "start": {"$lte": start},
                "end": {"$gte": end} },
            { "start": {"$gte": start},
                "end": {"$lte": end}
            } ] }
    for teammate in db.playwithme.find(query):
        mention = (await get_user(teammate["player"]))["mention"]
        if not mention in players and mention != who.mention:
            players += [mention]
    if len(players) > 0:
        await cli.send_message(channel, "%s %s want to play" % (who.mention, ", ".join(players)))
    else:
        if notify:
            await cli.send_message(channel, "%s Nobody wants to play. I'll notify you when somebody can." % (who.mention))
        else:
            await cli.send_message(channel, "%s Nobody wants to play." % (who.mention))

    if notify:
        await asyncio.sleep((end-start).total_seconds())
        await cli.remove_roles(who, playrole)
        db.playwithme.remove({"_id": queueid})
        await cli.send_message(channel, "%s You have been removed from the queue and were taken the play role." % (who.mention))

@cli.event
async def on_message_delete(message):
    if message.channel.id in MIRROR_IGNORE:
        return
    msgs = []
    mirror = cli.get_channel(MODMIRROR)
    msgs.append("--- deleted message " + message.author.name + message.channel.mention)
    ms = []
    async for m in cli.logs_from(message.channel, limit=4, before=message):
        ms.append(m)
    for m in reversed(ms):
        msgs.append(m.author.name + m.channel.mention + ": " + m.content)
    msgs.append(" > " + message.author.name + message.channel.mention + " ~~" + message.content + "~~")
    async for m in cli.logs_from(message.channel, limit=2, after=message):
        msgs.append(m.author.name + m.channel.mention + ": " + m.contet)
    msgs.append("---")
    text = "\n".join(msgs)
    await cli.send_message(mirror, text)

@cli.event
async def on_message_edit(before, message):
    if message.channel.id in MIRROR_IGNORE:
        return
    msgs = []
    mirror = cli.get_channel(MODMIRROR)
    msgs.append("--- edited message " + message.author.name + message.channel.mention)
    ms = []
    async for m in cli.logs_from(message.channel, limit=4, before=message):
        ms.append(m)
    for m in reversed(ms):
        msgs.append(m.author.name + m.channel.mention + ": " + m.content)
    msgs.append(" > " + message.author.name + message.channel.mention + " ~~" + before.content + "~~ " + message.content)
    async for m in cli.logs_from(message.channel, limit=2, after=message):
        msgs.append(m.author.name + m.channel.mention + ": " + m.contet)
    msgs.append("---")
    text = "\n".join(msgs)
    await cli.send_message(mirror, text)

@cli.event
async def on_message(message):
    msg = message.content.lower()
    if msg.startswith("?ping"):
        await cli.send_message(message.channel, "Pong!")

    if msg.startswith("?about"):
        await cli.send_message(message.channel, "Vainglory Discord bot " + VERSION + " written & hosted by shutterfly")

    if msg.startswith("?help"):
        await cli.send_message(message.channel, "Commands: ?help, ?ping, ?about")
        await cli.send_message(message.channel, "<play with me [now (default) | in (timespan) | at,from (time)] [for (timespan, default 30 minutes) | until (time)]> to find teammates.")
        await cli.send_message(message.channel, "<who can play [now (default) | in (timespan) | at,from (time)] [for (timespan, default 30 minutes) | until (time)]> to see who registered for notifications.")
        await cli.send_message(message.channel, "<don't play with me> to cancel.")

    if msg.startswith("play with me") or msg.startswith("who can play"):
        if msg.startswith("play with me"):
            when = message.content[len("play with me"):]
            notify = True
        else:
            when = message.content[len("who can play"):]
            notify = False
        await search_teammates(message.server, message.channel, message.author, when, notify)

    if msg.startswith("don't play with me") or msg.startswith("dont play with me"):
        db.playwithme.remove({"player": message.author.id})
        await cli.remove_roles(message.author, [r for r in message.server.roles if r.name == "play"][0])
        await cli.send_message(message.channel, "%s: Canceled all notifications and removed the 'play' role." % (message.author.mention))

if __name__ == '__main__':
    logging.basicConfig()
    log = logging.getLogger()
    log.setLevel(logging.INFO)
    cli.run(TOKEN)