Repository navigation
Expand file tree
/
Copy pathAradiaCore.py
More file actions
313 lines (267 loc) · 11 KB
/
Copy pathAradiaCore.py
File metadata and controls
313 lines (267 loc) · 11 KB
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
import os
import psutil
import discord
import logging
import asyncio
from random import randint
from functools import wraps
from collections import namedtuple
try:
import ujson as json
except ImportError:
import json
Context = namedtuple("Context", "msg guild server channel author embed")
class Colours:
"""
To use:
>>> print(Colours.HEADER + 'boop' + Colours.ENDC)
"""
HEADER = '\033[95m' # Pink
OKBLUE = '\033[94m' # Blue
OKGREEN = '\033[92m' # Green!
WARNING = '\033[93m' # Red
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
Colors = Colours
class AradiaCore(discord.Client):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._messages = []
self.config = self.json.load_json('config.json')
try:
self.prefix = self.config['prefix']
except KeyError:
print('No prefix found... using "!"')
self.prefix = '!'
try:
self.autoDelete = self.config['autoRemove']
except KeyError:
self.autoDelete = False
self.uploadchannel = None
if self.config["uploadchannel"]:
try:
int(self.config["uploadchannel"])
except ValueError:
raise ValueError('Upload guild must be a ID')
self.logger = logging.getLogger('discord') # Discord Logging
self.logger.setLevel(logging.INFO)
self.handler = logging.FileHandler(filename=os.path.join('logs', 'discord.log'), encoding='utf-8',
mode='w')
self.handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
self.logger.addHandler(self.handler)
self.internalLogger = logging.getLogger('discord') # Discord Logging
self.internalLogger.setLevel(logging.INFO)
self.internalHandler = logging.FileHandler(filename=os.path.join('logs', 'aradiaCore.log'), encoding='utf-8',
mode='w')
self.internalHandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
self.internalLogger.addHandler(self.handler)
# utils
@staticmethod
def debug(string):
"""
Allows you to log special stuff to the console as well as to the log.
"""
print(Colours.WARNING + string + Colours.ENDC)
async def upload(self, image):
"""
Uploads to a defined guild
returns the URL.
"""
dest = self.config['uploadchannel']
if not dest:
raise EnvironmentError('guild ID not selected. Please enter a upload guild id in config.json')
msg = await self.send_file(self.uploadchannel, fp=image)
return msg.attachments[0]['url']
async def cmd_stats(self, msg):
"""
Inbuilt command,
Shows you stats of your bot.
[Prefix]stats
"""
toreturn = 'AradiaCore v3.5\n'
toreturn += '------------\n'
toreturn += 'Total guilds: {}\n'.format(len(self.guilds))
toreturn += '------------\n'
process = psutil.Process(os.getpid())
mem = process.memory_info().rss
mem = float(mem) / 1048576
cpu = str(psutil.cpu_percent(interval=None)) + '%'
toreturn += ':floppy_disk: | Memory usage: {}MB\n'.format(str(mem))
toreturn += ':diamond_shape_with_a_dot_inside: | CPU usage: ' + cpu + '\n'
return toreturn
async def say(self, message, *, file=None, embed=None, tts=None, expire=0, dest=None):
"""
Sends a message, tries to use the global context first but does have a `dest` fall back
"""
if not dest:
dest = self.context.channel
message = message if message else ''
if file:
msg = await self.send_file(dest, fp=file, content=message)
else:
msg = await self.send_message(dest, message, embed=embed, tts=tts)
if expire:
asyncio.ensure_future(self.del_after(expire, msg))
return msg
async def del_after(self, time, message):
await asyncio.sleep(time)
await self.delete_message(message)
async def on_ready(self):
toreturn = '{}\n'.format(self.user.name)
toreturn += '------------\n'
toreturn += 'Total guilds: {}\n'.format(len(self.guilds))
toreturn += '------------\n'
toreturn += 'Prefix: {}\n'.format(self.config['prefix'])
toreturn += 'Running AradiaCore Version 0.7 - Public Alpha'
print(toreturn)
self.uploadchannel = discord.utils.get(self.get_all_channels(), id=self.config["uploadchannel"])
async def on_message(self, msg):
if msg.author.bot:
return
if msg.guild is None:
return
if not msg.content.startswith(self.prefix):
return
message_content = msg.content.strip()
command, *args = message_content.split()
command = command[len(self.prefix):].lower().strip()
handler = getattr(self, 'cmd_%s' % command, None)
if not handler:
return
res = None
# Global Context
# Holds info on current event.
# Holds: Current message
# -Message server
# -Message guild
# -Message author
# -Message embeds
self.context = Context(**{'msg': msg,
'guild': msg.guild,
'server': msg.guild,
'channel': msg.channel,
'author': msg.author,
'embed': msg.embeds})
try:
res = await handler(self.context)
except discord.errors.Forbidden:
# If we cant talk, show message in console.
print(
'[Error] Forbidden to talk in guild {}({}/{}({}))'.format(msg.guild.id, msg.guild.name, msg.server.name,
msg.server.id))
try:
# PM user, if we cant, just ignore.
await self.send_message(msg.author, 'I cannot send a message in {}'.format(msg.guild.name))
except discord.errors.Forbidden:
print('Couldnt send forbidden message ;-; ')
sent = None
if res:
try:
if not isinstance(res, str):
sent = res
else:
sent = await self.send_message(msg.channel, res)
except discord.errors.Forbidden:
sent = await self.send_message(msg.author, 'I do not have permissions to run {} in {}({})'.format(
handler.__name__[4:], msg.server.name, msg.guild.name))
self._messages.append((msg, sent))
return
async def on_message_delete(self, msg):
if self.autoDelete:
chmsg = [x for x in self._messages if x[0].id == msg.id]
if chmsg:
orig, sent = chmsg[0]
try:
await self.delete_message(sent)
except discord.errors.NotFound:
pass
except discord.errors.Forbidden:
pass
del self._messages[self._messages.index(chmsg[0])]
self.debug('Removed {} from messages list'.format(sent.id))
async def on_server_remove(self, s):
self.debug('Left {}! Current total: {}'.format(s.name, len(self.guilds)))
async def on_server_join(self, s):
self.debug('Joined {}! Current total: {}'.format(s.name, len(self.guilds)))
def boot(self):
print('Booting...')
try:
config = self.json.load_json('config.json')
except FileNotFoundError:
raise ValueError('Config not found. Please read the github wiki for more info.')
self.config = config
try:
self.run(config['token'])
except discord.errors.LoginFailure:
print(Colours.WARNING + 'Incorrect token.\n'
'Please check ./config.json and make sure the "token" entry is correct.\n'
'If you are still having issues, please go to the github wiki or join our server at:\n'
'https://discord.gg/Sz2qQJt' + Colours.ENDC)
# Permission related wrappers
@staticmethod
def bot_owner(f):
@wraps(f)
def wrapper(*args, **kwargs):
async def error(error, *, user=None):
print('Error: {} attempted bot owner command.'.format(user if user is not None else 'User'))
return error
ctx = args[1]
if ctx.author.id != args[0].config['owner']:
return error('This command is locked to the bot owner only.', user=ctx.author.name)
return f(*args, **kwargs)
return wrapper
class json:
# Json related functions
@classmethod
def save_json(cls, filename, data):
"""Atomically saves json file - Will make directory if need be."""
mypath = r'{}'.format(filename)
rnd = randint(1000, 9999)
path, ext = os.path.splitext(filename)
tmp_file = "{}-{}.tmp".format(path, rnd)
cls._save_json(tmp_file, data)
try:
cls._read_json(tmp_file)
except json.decoder.JSONDecodeError:
logging.exception("Attempted to write file {} but JSON "
"integrity check on tmp file has failed. "
"The original file is unaltered."
"".format(filename))
return False
os.replace(tmp_file, filename)
return True
@classmethod
def load_json(cls, filename):
"""Loads json file"""
return cls._read_json(filename)
def is_valid_json(cls, filename):
"""Verifies if json file exists / is readable"""
try:
cls._read_json(filename)
return True
except FileNotFoundError:
return False
except json.decoder.JSONDecodeError:
return False
@staticmethod
def _read_json(filename):
with open(filename, encoding='utf-8', mode="r") as f:
data = json.load(f)
return data
@staticmethod
def _save_json(filename, data):
dir = filename.split('/')
del dir[-1]
dir = '/'.join(dir)
if not os.path.exists(dir):
directory = filename.split('/')
del directory[-1]
os.makedirs('/'.join(directory))
with open(filename, encoding='utf-8', mode="w") as f:
json.dump(data, f, indent=4, sort_keys=True,
separators=(',', ' : '))
return data
if __name__ == '__main__':
print('This framework is designed to be run inside another script. Try importing.')