-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
165 lines (129 loc) · 4.55 KB
/
Copy pathbot.py
File metadata and controls
165 lines (129 loc) · 4.55 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
import discord
from discord.ext import commands
import time
import os
import inspect
import json
from contextlib import redirect_stdout
import io
import textwrap
import traceback
import aiohttp
from motor.motor_asyncio import AsyncIOMotorClient
client = AsyncIOMotorClient(os.environ.get("MONGOURL"))
db = client.discordbot2001
async def guildpre(bot, message):
'''Get the prefix for required guild'''
f = await bot.db.config.find_one({"gid" : message.guild.id})
if f is None:
return "e."
else:
f = f['prefix']
return f
bot = commands.Bot(command_prefix=guildpre, description="An easy to use discord bot")
bot.load_extension("cogs.fun")
bot.load_extension("cogs.utility")
bot.load_extension("cogs.mod")
bot.load_extension("cogs.Music")
bot._last_result = None
bot.session = aiohttp.ClientSession(loop=bot.loop)
bot.db = db
def cleanup_code(content):
'''Automatically removes code blocks from the code.'''
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
return content.strip('` \n')
def dev_check(id):
with open('data/devs.json') as f:
devs = json.load(f)
if id in devs:
return True
return False
@bot.event
async def on_ready():
print('Logged in as '+ bot.user.name)
print(bot.user.id)
print('------')
await bot.change_presence(status = os.environ.get('STATUS'), activity=discord.Game(name=os.environ.get('ACTIVITY')))
@bot.command(name='eval')
async def _eval(ctx, *, body):
"""Evaluates python code"""
if not dev_check(ctx.author.id):
return await ctx.send("You cannot use this because you are not a developer.")
env = {
'ctx': ctx,
'channel': ctx.channel,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'_': bot._last_result,
'source': inspect.getsource
}
env.update(globals())
body = cleanup_code(body)
stdout = io.StringIO()
err = out = None
to_compile = f'async def func():\n{textwrap.indent(body, " ")}'
def paginate(text: str):
'''Simple generator that paginates text.'''
last = 0
pages = []
for curr in range(0, len(text)):
if curr % 1980 == 0:
pages.append(text[last:curr])
last = curr
appd_index = curr
if appd_index != len(text) - 1:
pages.append(text[last:curr])
return list(filter(lambda a: a != '', pages))
try:
exec(to_compile, env)
except Exception as e:
err = await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```')
return await ctx.message.add_reaction('\u2049')
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
err = await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```')
else:
value = stdout.getvalue()
if ret is None:
if value:
try:
out = await ctx.send(f'```py\n{value}\n```')
except:
paginated_text = paginate(value)
for page in paginated_text:
if page == paginated_text[-1]:
out = await ctx.send(f'```py\n{page}\n```')
break
await ctx.send(f'```py\n{page}\n```')
else:
bot._last_result = ret
try:
out = await ctx.send(f'```py\n{value}{ret}\n```')
except:
paginated_text = paginate(f"{value}{ret}")
for page in paginated_text:
if page == paginated_text[-1]:
out = await ctx.send(f'```py\n{page}\n```')
break
await ctx.send(f'```py\n{page}\n```')
if out:
await ctx.message.add_reaction('\u2705') # tick
elif err:
await ctx.message.add_reaction('\u2049') # x
else:
await ctx.message.add_reaction('\u2705')
@bot.command()
async def ping(ctx):
'''Ping the bot'''
t1 = ctx.message.created_at
m = await ctx.send('**Pong!**')
time = (m.created_at - t1).total_seconds() * 1000
await m.edit(content='**Pong! Took: {}ms**'.format(int(time)))
bot.run(os.environ.get("TOKEN"))