forked from cgrok/selfbot.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
347 lines (304 loc) · 11.1 KB
/
bot.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
import discord
from ext.formatter import EmbedHelp
from discord.ext import commands
from contextlib import redirect_stdout
import datetime
import json
import inspect
import os
import glob
import io
import textwrap
import traceback
def run_wizard():
print('------------------------------------------')
print('WELCOME TO THE VERIXX-SELFBOT SETUP WIZARD!')
print('------------------------------------------')
token = input('Enter your token:\n> ')
print('------------------------------------------')
prefix = input('Enter a prefix for your selfbot:\n> ')
data = {
"BOT": {
"TOKEN" : token,
"PREFIX" : prefix
},
"FIRST" : False
}
with open('data/config.json','w') as f:
f.write(json.dumps(data, indent=4))
print('------------------------------------------')
print('Successfully saved your data!')
print('------------------------------------------')
if 'TOKEN' in os.environ:
heroku = True
TOKEN = os.environ['TOKEN']
else:
heroku = False
with open('data/config.json') as f:
if json.load(f)['FIRST']:
run_wizard()
with open('data/config.json') as f:
TOKEN = json.load(f)["BOT"]['TOKEN']
async def get_pre(bot, message):
if 'PREFIX' in os.environ:
return os.environ['PREFIX']
with open('data/config.json') as f:
config = json.load(f)
try:
return config["BOT"]['PREFIX']
except:
return 's.'
bot = commands.Bot(command_prefix=get_pre, self_bot=True, formatter=EmbedHelp())
bot.remove_command('help')
_extensions = [
'cogs.misc',
'cogs.info',
'cogs.utils',
'cogs.mod'
]
@bot.event
async def on_ready():
bot.uptime = datetime.datetime.now()
print('------------------------------------------\n'
'Self-Bot Ready\n'
'Author: verix#7220\n'
'------------------------------------------\n'
'Username: {}\n'
'User ID: {}\n'
'------------------------------------------'
.format(bot.user, bot.user.id))
@bot.command(pass_context=True)
async def ping(ctx):
"""Pong! Check your response time."""
msgtime = ctx.message.timestamp.now()
await (await bot.ws.ping())
now = datetime.datetime.now()
ping = now - msgtime
pong = discord.Embed(title='Pong! Response Time:',
description=str(ping.microseconds / 1000.0) + ' ms',
color=0x00ffff)
await bot.say(embed=pong)
@bot.command(pass_context=True)
async def shutdown(ctx):
"""Shuts down the selfbot."""
channel = ctx.message.channel
await bot.say("Are you sure you want to shut down the bot? Type \"YES\" if you want to, or anything else to cancel.")
response = await bot.wait_for_message(timeout=30, channel=channel)
if response.content == "YES":
await bot.say("Shutting down...")
await bot.logout()
else:
await bot.say("Cancelled.")
@bot.command(name='presence')
async def _set(Type,*,message=None):
"""Change your discord game/stream!"""
if Type.lower() == 'stream':
await bot.change_presence(game=discord.Game(name=message,type=1,url='https://www.twitch.tv/a'),status='online')
await bot.say('Set presence to. `Streaming {}`'.format(message))
elif Type.lower() == 'game':
await bot.change_presence(game=discord.Game(name=message))
await bot.say('Set presence to `Playing {}`'.format(message))
elif Type.lower() == 'clear':
await bot.change_presence(game=None)
await bot.say('Cleared Presence')
else:
await bot.say('Usage: `.presence [game/stream] [message]`')
async def send_cmd_help(ctx):
if ctx.invoked_subcommand:
pages = bot.formatter.format_help_for(ctx, ctx.invoked_subcommand)
for page in pages:
print(page)
await bot.send_message(ctx.message.channel, embed=page)
print('Sent command help')
else:
pages = bot.formatter.format_help_for(ctx, ctx.command)
for page in pages:
print(page)
await bot.send_message(ctx.message.channel, embed=page)
print('Sent command help')
@bot.event
async def on_command_error(error, ctx):
print(error)
channel = ctx.message.channel
if isinstance(error, commands.MissingRequiredArgument):
await send_cmd_help(ctx)
print('Sent command help')
elif isinstance(error, commands.BadArgument):
await send_cmd_help(ctx)
print('Sent command help')
elif isinstance(error, commands.DisabledCommand):
await bot.send_message(channel, "That command is disabled.")
print('Command disabled.')
elif isinstance(error, commands.CommandInvokeError):
# A bit hacky, couldn't find a better way
no_dms = "Cannot send messages to this user"
is_help_cmd = ctx.command.qualified_name == "help"
is_forbidden = isinstance(error.original, discord.Forbidden)
if is_help_cmd and is_forbidden and error.original.text == no_dms:
msg = ("I couldn't send the help message to you in DM. Either"
" you blocked me or you disabled DMs in this server.")
await bot.send_message(channel, msg)
return
@bot.command(pass_context=True)
async def coglist(ctx):
'''See unloaded and loaded cogs!'''
def pagify(text, delims=["\n"], *, escape=True, shorten_by=8,
page_length=2000):
"""DOES NOT RESPECT MARKDOWN BOXES OR INLINE CODE"""
in_text = text
if escape:
num_mentions = text.count("@here") + text.count("@everyone")
shorten_by += num_mentions
page_length -= shorten_by
while len(in_text) > page_length:
closest_delim = max([in_text.rfind(d, 0, page_length)
for d in delims])
closest_delim = closest_delim if closest_delim != -1 else page_length
if escape:
to_send = escape_mass_mentions(in_text[:closest_delim])
else:
to_send = in_text[:closest_delim]
yield to_send
in_text = in_text[closest_delim:]
yield in_text
def box(text, lang=""):
ret = "```{}\n{}\n```".format(lang, text)
return ret
loaded = [c.__module__.split(".")[1] for c in bot.cogs.values()]
# What's in the folder but not loaded is unloaded
def _list_cogs():
cogs = [os.path.basename(f) for f in glob.glob("cogs/*.py")]
return ["cogs." + os.path.splitext(f)[0] for f in cogs]
unloaded = [c.split(".")[1] for c in _list_cogs()
if c.split(".")[1] not in loaded]
if not unloaded:
unloaded = ["None"]
msg = ("+ Loaded\n"
"{}\n\n"
"- Unloaded\n"
"{}"
"".format(", ".join(sorted(loaded)),
", ".join(sorted(unloaded)))
)
for page in pagify(msg, [" "], shorten_by=16):
await bot.say(box(page.lstrip(" "), lang="diff"))
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])
# remove `foo`
return content.strip('` \n')
def get_syntax_error(e):
if e.text is None:
return '```py\n{0.__class__.__name__}: {0}\n```'.format(e)
return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__)
async def to_code_block(ctx, body):
if body.startswith('```') and body.endswith('```'):
content = '\n'.join(body.split('\n')[1:-1])
else:
content = body.strip('`')
await bot.edit_message(ctx.message, '```py\n'+content+'```')
@bot.command(pass_context=True, name='eval')
async def _eval(ctx, *, body: str):
'''Run python scripts on discord!'''
await to_code_block(ctx, body)
env = {
'bot': bot,
'ctx': ctx,
'channel': ctx.message.channel,
'author': ctx.message.author,
'server': ctx.message.server,
'message': ctx.message,
}
env.update(globals())
body = cleanup_code(content=body)
stdout = io.StringIO()
to_compile = 'async def func():\n%s' % textwrap.indent(body, ' ')
try:
exec(to_compile, env)
except SyntaxError as e:
return await bot.say(get_syntax_error(e))
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
x = await bot.say('```py\n{}{}\n```'.format(value, traceback.format_exc()))
try:
await bot.add_reaction(x, '\U0001f534')
except:
pass
else:
value = stdout.getvalue()
if TOKEN in value:
value = value.replace(TOKEN,"[EXPUNGED]")
if ret is None:
if value:
try:
x = await bot.say('```py\n%s\n```' % value)
except:
x = await bot.say('```py\n\'Result was too long.\'```')
try:
await bot.add_reaction(x, '\U0001f535')
except:
pass
else:
try:
await bot.add_reaction(ctx.message, '\U0001f535')
except:
pass
else:
try:
x = await bot.say('```py\n%s%s\n```' % (value, ret))
except:
x = await bot.say('```py\n\'Result was too long.\'```')
try:
await bot.add_reaction(x, '\U0001f535')
except:
pass
@bot.command(pass_context=True,name='reload')
async def _reload(ctx,*, module : str):
"""Reloads a module."""
channel = ctx.message.channel
module = 'cogs.'+module
try:
bot.unload_extension(module)
x = await bot.send_message(channel,'Successfully Unloaded.')
bot.load_extension(module)
x = await bot.edit_message(x,'Successfully Reloaded.')
except Exception as e:
x = await bot.edit_message(x,'\N{PISTOL}')
await bot.say('{}: {}'.format(type(e).__name__, e))
else:
x = await bot.edit_message(x,'Done. \N{OK HAND SIGN}')
@bot.command(pass_context=True)
async def load(ctx, *, module):
'''Loads a module.'''
module = 'cogs.'+module
try:
bot.load_extension(module)
await bot.say('Successfully Loaded.')
except Exception as e:
await bot.say('\N{PISTOL}\n{}: {}'.format(type(e).__name__, e))
@bot.command(pass_context=True)
async def unload(ctx, *, module):
'''Unloads a module.'''
module = 'cogs.'+module
try:
bot.unload_extension(module)
await bot.say('Successfully Unloaded `{}`'.format(module))
except:
pass
for extension in _extensions:
try:
bot.load_extension(extension)
print('Loaded: {}'.format(extension))
except Exception as e:
exc = '{}: {}'.format(type(e).__name__, e)
print('Error on load: {}\n{}'.format(extension, exc))
try:
bot.run(TOKEN.strip('\"'), bot=False)
except Exception as e:
print('\n[ERROR]: \n{}\n'.format(e))