This repository has been archived by the owner on Dec 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
352 lines (240 loc) · 11.3 KB
/
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
from models import Deletes, Autoclears, session
import discord
import asyncio
import aiohttp
import time
import sys
import os
import configparser
import json
import logging
from datetime import datetime
class OneLineExceptionFormatter(logging.Formatter):
def formatException(self, exc_info):
result = super().formatException(exc_info)
return repr(result)
def format(self, record):
result = super().format(record)
if record.exc_text:
result = result.replace("\n", "")
return result
handler = logging.StreamHandler()
formatter = OneLineExceptionFormatter(logging.BASIC_FORMAT)
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.setLevel(os.environ.get("LOGLEVEL", "INFO"))
logger.addHandler(handler)
class BotClient(discord.AutoShardedClient):
def __init__(self, *args, **kwargs):
super(BotClient, self).__init__(*args, **kwargs)
self.commands = {
'help' : self.help,
'info' : self.info,
'start' : self.autoclear,
'clear' : self.clear,
'purge' : self.purge,
'stop' : self.stop,
'rules' : self.rules,
}
self.config = configparser.SafeConfigParser()
self.config.read('config.ini')
self.dbl_token = self.config.get('DEFAULT', 'dbl_token')
async def on_ready(self):
logger.info('Logged in as')
logger.info(self.user.name)
logger.info(self.user.id)
logger.info(self.user.avatar)
logger.info('------------')
async def on_guild_remove(self, guild):
await self.send()
async def on_guild_join(self, guild):
await self.send()
async def send(self):
if not self.dbl_token:
return
guild_count = len(self.guilds)
csession = aiohttp.ClientSession()
dump = json.dumps({
'server_count': guild_count
})
head = {
'authorization': self.dbl_token,
'content-type' : 'application/json'
}
url = 'https://discordbots.org/api/bots/stats'
async with csession.post(url, data=dump, headers=head) as resp:
logger.info('returned {0.status} for {1}'.format(resp, dump))
await csession.close()
async def on_error(self, e, *a, **k):
session.rollback()
raise
async def on_message(self, message):
clears = session.query(Autoclears).filter(Autoclears.channel == message.channel.id).order_by(Autoclears.time)
for c in clears:
if c.user == message.author.id or c.user is None:
d = Deletes(time=time.time() + c.time, channel=message.channel.id, message=message.id)
session.add(d)
session.commit()
break
if message.author.bot or message.content is None or message.guild is None:
return
try:
if await self.get_cmd(message):
logger.info('Command: ' + message.content)
session.commit()
except discord.errors.Forbidden:
try:
await message.channel.send('No permissions to perform actions.')
except discord.errors.Forbidden:
logger.info('Twice Forbidden')
async def get_cmd(self, message):
prefix = 'autoclear '
command = None
if message.content == self.user.mention:
await self.commands['info'](message, '')
if message.content[0:len(prefix)] == prefix:
command = message.content.split(' ')[1]
stripped = (message.content + ' ').split(' ', 2)[-1].strip()
elif self.user.id in map(lambda x: x.id, message.mentions) and len(message.content.split(' ')) > 1:
command = message.content.split(' ')[1]
stripped = (message.content + ' ').split(' ', 2)[-1].strip()
if command is not None:
if command in self.commands.keys():
await self.commands[command](message, stripped)
return True
return False
async def help(self, message, stripped):
await message.channel.send(embed=discord.Embed(title='HELP', description='''
`autoclear start` - Start autoclearing the current channel. Accepts arguments:
\t* User mentions (users the clear applies to- if no mentions, will do all users)
\t* Duration (time in seconds that messages should remain for- defaults to 10s)
\tE.g `autoclear start @JellyWX#2946 5`
`autoclear clear` - Delete message history of specific users. Accepts arguments:
\t* User mention (user to clear history of)
`autoclear purge` - Delete message history. Accepts arguments:
\t* Limit (number of messages to delete)
`autoclear rules` - Check the autoclear rules for specified channels. Accepts arguments:
\t* Channel mention (channel to view rules of- defaults to current)
`autoclear stop` - Cancel autoclearing on current channel. Accepts arguments:
\t* User mentions (users to cancel autoclearing for- if no mentions, will do all users)
'''))
async def info(self, message, stripped):
await message.channel.send(embed=discord.Embed(title='INFO', description='''
Welcome to autoclear bot!
Help page: `autoclear help`
Prefixes: @ me or `autoclear`
Invite me to your guild: https://discordapp.com/oauth2/authorize?client_id=488060245739044896&scope=bot&permissions=93184
'''))
async def autoclear(self, message, stripped):
if not message.author.guild_permissions.manage_guild:
await message.channel.send('You must be a Manager to run this command')
return
seconds = 10
for item in stripped.split(' '): # determin a seconds argument
try:
seconds = float(item)
break
except ValueError:
continue
if seconds > 31557600:
await message.channel.send('Please specify a time less than a year')
elif message.mentions != []:
for mention in message.mentions:
s = session.query(Autoclears).filter_by(channel=message.channel.id, user=mention.id).first()
if s is None:
print('Creating a new autoclear')
a = Autoclears(channel=message.channel.id, time=seconds, user=mention.id)
session.add(a)
else:
print('Editing existing autoclear from {}s to {}s for {}'.format(s.time, seconds, message.author))
s.time = seconds
else:
s = session.query(Autoclears).filter_by(channel=message.channel.id, user=None).first()
if s is None:
print('Creating a new autoclear')
a = Autoclears(channel=message.channel.id, time=seconds)
session.add(a)
else:
print('Editing existing autoclear from {}s to {}s'.format(s.time, seconds))
s.time = seconds
async def rules(self, message, stripped):
if len(message.channel_mentions) > 0:
chan = message.channel_mentions[0]
else:
chan = message.channel
rules = session.query(Autoclears).filter(Autoclears.channel == chan.id)
strings = []
for r in rules:
if r.user is None:
strings.insert(0, '**GLOBAL**: {} seconds'.format(r.time))
else:
strings.append('*{}*: {} seconds'.format(message.guild.get_member(r.user), r.time))
if strings != []:
await message.channel.send(embed=discord.Embed(title='{} rules'.format(chan.name), description='\n'.join(strings)))
else:
await message.channel.send('No rules set for specified channel')
async def stop(self, message, stripped):
if not message.author.guild_permissions.manage_guild:
await message.channel.send('You must be a Manager to run this command')
elif message.mentions != []:
for mention in message.mentions:
s = session.query(Autoclears).filter_by(channel=message.channel.id, user=mention.id).first()
if s is None:
await message.channel.send('Couldn\'t find an autoclear for specified user `{}` in the current channel'.format(mention))
else:
session.query(Autoclears).filter_by(channel=message.channel.id, user=mention.id).delete(synchronize_session='fetch')
await message.channel.send('Cancelled autoclear for specified user `{}`'.format(mention))
else:
s = session.query(Autoclears).filter_by(channel=message.channel.id, user=None).first()
if s is None:
await message.channel.send('Couldn\'t find a global autoclear in the current channel')
else:
session.query(Autoclears).filter_by(channel=message.channel.id, user=None).delete(synchronize_session='fetch')
await message.channel.send('Cancelled global autoclear on current channel')
async def clear(self, message, stripped):
if not message.author.guild_permissions.manage_messages:
await message.channel.send('Admin is required to perform this command')
return
if len(message.mentions) == 0:
await message.channel.send('Please mention users you wish to clear')
return
delete_list = []
async for m in message.channel.history(limit=1000):
if time.time() - m.created_at.timestamp() >= 1209600 or len(delete_list) > 99:
break
if m.author in message.mentions:
delete_list.append(m)
await message.channel.delete_messages(delete_list)
async def purge(self, message, stripped):
if not message.author.guild_permissions.manage_messages:
await message.channel.send('Admin is required to perform this command')
return
if not stripped or not all(x in '0123456789' for x in stripped) or not 0 < int(stripped) <= 100:
await message.channel.send('Please specify a limit between 1 and 100')
return
await message.channel.purge(limit=int(stripped))
async def deletes(self):
await self.wait_until_ready()
while not self.is_closed():
try:
dels = []
for d in session.query(Deletes).filter(Deletes.time <= time.time()):
dels.append(d.map_id)
message = await self.get_channel(d.channel).get_message(d.message)
if message is None or message.pinned:
pass
else:
logger.info('{}: Attempting to auto-delete a message...'.format(datetime.utcnow().strftime('%H:%M:%S')))
try:
await message.delete()
except Exception as e:
logger.error('Ln 1049: {}'.format(e))
except Exception as e:
logger.error('deletes: {}'.format(e))
if len(dels) > 0:
session.query(Deletes).filter(Deletes.map_id.in_(dels)).delete(synchronize_session='fetch')
session.commit()
await asyncio.sleep(1)
client = BotClient()
client.loop.create_task(client.deletes())
client.run(client.config.get('DEFAULT', 'token'), max_messages=50)