-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdiscord_app.py
178 lines (137 loc) · 5.6 KB
/
discord_app.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
import asyncio # util functions
from typing import Optional
import discord
from discord.ext import commands
import logging # receives logs from discord.py
from datetime import datetime
from steam import steamid
logging.basicConfig(level=logging.INFO)
import aiohttp # for querying api
import io
# for adding users to database
from motor.motor_asyncio import AsyncIOMotorClient as MongoClient
import pymongo.errors
# fetches popflash profiles
import popflash_api as pf
import os
import dotenv
dotenv.load_dotenv()
import sys
if len(sys.argv)>1 and sys.argv[1] == 'testing':
logging.info('Running in testing mode')
SERVER = "http://localhost:7355"
else:
SERVER = "https://api.sandb.ga"
client = commands.Bot(commands.when_mentioned_or('!'), help_command=None)
@client.event
async def on_command_error(ctx, error):
if isinstance(error, discord.ext.commands.CommandNotFound):
return
emb = discord.Embed(
colour=discord.Colour.red(),
title=type(error).__name__,
description=str(getattr(error, 'original', error))
)
await ctx.send(embed=emb)
class DBHandler:
def __init__(self):
self.client = MongoClient(os.getenv("MONGO_URI"))
self.db = self.client[os.getenv("MONGO_DB")]
self.users = self.db['user_links']
self._idx = asyncio.ensure_future(self.users.create_index("discord_id", unique=True))
@property
def ready(self):
return self._idx.done()
db = DBHandler()
@client.listen()
async def on_message(message: discord.Message):
if not (isinstance(message.channel, discord.DMChannel) and '/user' in message.content):
return
assert db.ready
popflash_id = message.content.split('/')[-1].strip()
if not popflash_id.isnumeric():
return await message.channel.send("It didn't look like you sent a popflash user link. Send a message of the form 'https://popflash.site/user/1610522'")
def to_user():
profile = pf.get_profile(popflash_id)
return {
'discord_name': str(message.author),
'discord_id': message.author.id,
'popflash_id': popflash_id,
'steam_id': int(steamid.steam64_from_url(profile["steam_profile"])),
'register_date': datetime.now(),
'v': profile['v'],
}
user = await asyncio.get_event_loop().run_in_executor(None, to_user)
logging.info(str(user))
try:
await db.users.insert_one(user)
except pymongo.errors.DuplicateKeyError:
return await message.channel.send("You are already registered :)")
await message.channel.send("Registered! Thank you")
@client.command()
async def register(ctx, match):
"Add a match to the database and show the resulting Elo changes."
logging.info(ctx.message.content)
async with aiohttp.ClientSession() as session:
async with session.post(SERVER+'/submit_match', json={'match_url': match}) as resp:
if resp.status != 200:
logging.warning(await resp.text())
return await ctx.send('Failed to process match: ' + (await resp.text())[:1000])
resp = await resp.json()
print(resp)
embed = discord.Embed(
title='Match Report',
url='https://pop.robey.xyz',
description='10-man played at {}'.format(resp['time']),
).set_thumbnail(url=resp['image']) \
.add_field(name=resp['team1status'], value=resp['team1stats']) \
.add_field(name=resp['team2status'], value=resp['team2stats'])
await ctx.send(embed=embed)
@client.command()
async def stats(ctx, match):
"Show the popflash statistics for a match."
logging.info(ctx.message.content)
match_url = "https://popflash.site/match/" + match.split('/')[-1]
image_command = ["wkhtmltoimage",
"-f", "png",
"--width", "990",
"--disable-smart-width",
"--crop-h", "1106",
"--crop-w", "990",
"--crop-x", "0",
"--crop-y", "142",
"--cookie", "connect.sid", os.getenv('POPFLASH_SID'),
match_url, "-"]
process = await asyncio.create_subprocess_exec(*image_command,
stdout=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
await ctx.send(file=discord.File(io.BytesIO(stdout), 'match_stats.png'))
@client.command()
async def pop(ctx, match):
"Equivalent to !register + !stats"
asyncio.ensure_future(ctx.invoke(register, match))
asyncio.ensure_future(ctx.invoke(stats, match))
@client.command()
async def balance(ctx, chan: Optional[discord.VoiceChannel] = None, *players: discord.User):
if chan:
players = [u for u in chan.members if u not in players]
users = [
u['popflash_id'] for u in await db.users.find(
{'discord_id': {'$in': [p.id for p in players]}},
projection=['discord_id', 'popflash_id']
).to_list(None)
]
if len(users) < len(players):
asyncio.ensure_future(ctx.send("Some players don't have popflash."))
async with aiohttp.ClientSession() as session:
async with session.post(
SERVER+'/v2/balance',
json={'team1': [str(u) for u in users], 'team2':[]}
) as resp:
data = await resp.json()
emb = discord.Embed(colour=0xe3c28f)
emb.add_field(name=f"Team 1 ({data['t1rating']})", value=data['team1'])
emb.add_field(name=f"Team 2 ({data['t2rating']})", value=data['team2'])
await ctx.send(embed=emb)
if __name__ == '__main__':
client.run(os.getenv("DISCORD_TOKEN"))