-
Notifications
You must be signed in to change notification settings - Fork 2
/
handle.py
245 lines (212 loc) · 9.18 KB
/
handle.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
# The MIT License (MIT)
# Copyright (c) 2017 Levak Borok <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import discord
import asyncio
import datetime
class Handle:
def __init__(self, bot, message=None, member=None, channel=None):
self.bot = bot
self.member = member
self.channel = channel
self.message = message
if self.message:
self.member = self.message.author
self.channel = self.message.channel
self.team = None
if self.member and self.member.id != bot.client.user.id:
try:
db, error, _ = bot.find_cup_db(self.member.guild, captain=self.member.id)
if not error:
self.team = db['captains'][self.member.id].team
else:
print('WARNING: {} (member: {})'.format(error, self.member.id))
except KeyError:
print('WARNING: Could not find team for {}'.format(self.member.id))
pass
## Override pickle serialization
def __getstate__(self):
state = dict(self.__dict__)
# We cannot serialize Discord.Message because of WeakSet
# thus, remove them
state['bot'] = None
state['_msg_ch'] = self.message.channel.id \
if self.message \
and self.message.channel \
else self.channel.id \
if self.channel else None
state['_msg_id'] = self.message.id \
if self.message else None
state['_msg_am'] = self.message.author.id \
if self.message \
and self.message.author \
else self.member.id \
if self.member else None
state['message'] = None
state['member'] = None
state['channel'] = None
state['team'] = None
return state
## Once the bot is ready, restore the message
async def resume(self, guild, bot):
channel = guild.get_channel(self._msg_ch) \
if self._msg_ch else None
try:
message = await channel.fetch_message(self._msg_id) \
if channel and self._msg_id else None
except:
print('WARNING: Could not find message id {}'.format(self._msg_id))
message = None
member = guild.get_member(self._msg_am) \
if self._msg_am else None
if message:
self.__init__(bot, message=message)
elif channel and member:
self.__init__(bot, channel=channel, member=member)
def clone(self):
h = Handle(self.bot)
h.member = self.member
h.channel = self.channel
h.message = self.message
h.team = self.team
return h
async def reply(self, msg):
if self.member:
return await self.send('{} {}'.format(self.member.mention, msg))
else:
return await self.send(msg)
async def react(self, reaction, err_count=0):
if not self.message:
return None
try:
return await self.message.add_reaction(reaction)
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.react(reaction, err_count=err_count)
async def unreact(self, reaction, user, err_count=0):
if not self.message:
return None
try:
print('removing reaction {} from {}'.format(reaction, str(user)))
return await self.message.remove_reaction(reaction, user)
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.unreact(reaction, user, err_count=err_count)
async def send(self, msg, err_count=0):
try:
return await self.channel.send(content=msg)
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.send(msg, err_count=err_count)
async def send_file(self, file, name, msg, err_count=0):
try:
return await self.channel.send(file=discord.File(fp=file, filename=name), content=msg)
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.send_file(file, name, msg, err_count=err_count)
async def edit(self, msg, err_count=0):
try:
return await self.message.edit(content=msg)
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.edit(msg, err_count=err_count)
async def embed(self, title, msg, color, fields=[], err_count=0):
try:
embed = discord.Embed(title=title,
type='rich',
description=msg,
timestamp=datetime.datetime.utcnow(),
color=color)
for field in fields:
embed.add_field(name=field['name'], value=field['value'], inline=False)
return await self.channel.send(embed=embed)
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.embed(title, msg, color, fields=fields, err_count=err_count)
async def edit_embed(self, title, msg, color, fields=[], err_count=0):
try:
embed = discord.Embed(title=title,
type='rich',
description=msg,
timestamp=datetime.datetime.utcnow(),
color=color)
for field in fields:
embed.add_field(name=field['name'], value=field['value'], inline=False)
return await self.message.edit(embed=embed)
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.edit_embed(title, msg, color, fields=fields, err_count=err_count)
async def delete(self, err_count=0):
try:
return await self.message.delete()
except discord.errors.HTTPException as e:
print('WARNING: HTTPexception: {}'.format(str(e)))
err_count += 1
if err_count > 5:
return
await asyncio.sleep(10)
return await self.delete(err_count=err_count)
async def broadcast(self, bcast_id, msg):
if not self.bot.is_broadcast_enabled(self.channel.guild):
return
channels = []
try:
channels = self.bot.config['guilds'][self.channel.guild.name]['rooms'][bcast_id]
except:
print('WARNING: No broadcast configuration for "{}"'.format(bcast_id))
pass
for channel_name in channels:
channel = discord.utils.get(self.channel.guild.channels, name=channel_name)
if channel:
try:
await channel.send(content=msg)
except:
print('WARNING: No permission to write in "{}"'.format(channel_name))
pass
else:
print ('WARNING: Missing channel {}'.format(channel_name))