forked from mdiller/MangoByte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmangobyte.py
221 lines (184 loc) · 7.84 KB
/
mangobyte.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
# The following have to be imported and initialized in the correct order
from cogs.utils.settings import Settings
settings = Settings()
from cogs.utils.botdata import BotData
botdata = BotData()
import cogs.utils.loggingdb as loggingdb
loggingdb_session = loggingdb.create_session(settings.resource("loggingdb.db"))
from cogs.utils.httpgetter import HttpGetter
httpgetter = HttpGetter()
from cogs.utils.helpers import *
import discord
import traceback
import asyncio
import string
from discord.ext import commands
import logging
import datetime
from cogs.utils.helpformatter import MangoHelpFormatter
from cogs.utils.clip import *
logging.basicConfig(level=logging.INFO)
description = """The juiciest unsigned 8 bit integer you is eva gonna see.
For more information about me, try `{cmdpfx}info`"""
permissions = 314432
bot = commands.Bot(command_prefix=botdata.command_prefix_botmessage, formatter=MangoHelpFormatter(), description=description)
bot.remove_command("help")
thinker = Thinker(bot)
invite_link = f"https://discordapp.com/oauth2/authorize?permissions={permissions}&scope=bot&client_id=213476188037971968"
deprecated_commands = {
"ttschannel": "config ttschannel",
"unttschannel": "config ttschannel none",
"opendotasql": "https://www.opendota.com/explorer",
"setintrotts": "userconfig introtts",
"setwelcome": "userconfig introtts",
"setoutrotts": "userconfig outrotts",
"setintro": "userconfig intro",
"setoutro": "userconfig outro",
"setsteam": "userconfig steam",
"register": "userconfig steam"
}
@bot.event
async def on_ready():
print('Logged in as:\n{0} (ID: {0.id})'.format(bot.user))
print('Connecting to voice channels if specified in botdata.json ...')
game = discord.Activity(
name="DOTA 3 [?help]",
type=discord.ActivityType.playing,
start=datetime.datetime.utcnow())
await bot.change_presence(status=discord.Status.online, activity=game)
cog = bot.get_cog("Audio")
# stuff to help track/log the connection of voice channels
start_time = datetime.datetime.now()
connected_count = 0
not_found_count = 0
timeout_count = 0
for guildinfo in botdata.guildinfo_list():
if guildinfo.voicechannel is not None:
try:
print(f"connecting voice to: {guildinfo.voicechannel}")
await cog.connect_voice(guildinfo.voicechannel)
print(f"connected: {guildinfo.voicechannel}")
connected_count += 1
except UserError as e:
if e.message == "channel not found":
guildinfo.voicechannel = None
print("channel not found!")
not_found_count += 1
else:
raise
except asyncio.TimeoutError:
guildinfo.voicechannel = None
print("timeout error when connecting to channel")
timeout_count += 1
print("\nupdating guilds")
loggingdb.update_guilds(bot.guilds, loggingdb_session)
print("\ninitialization finished\n")
message = "__**Initialization complete:**__"
if connected_count > 0:
message += f"\n{connected_count} voice channels connected"
if not_found_count > 0:
message += f"\n{not_found_count} voice channels not found"
if timeout_count > 0:
message += f"\n{timeout_count} voice channels timed out"
appinfo = await bot.application_info()
if not settings.debug:
await appinfo.owner.send(message)
async def get_cmd_signature(ctx):
bot.formatter.context = ctx
bot.formatter.command = ctx.command
return bot.formatter.get_command_signature()
# Whether or not we report invalid commands
async def invalid_command_reporting(ctx):
if ctx.message.guild is None:
return True
else:
return botdata.guildinfo(ctx.message.guild.id).invalidcommands
@bot.event
async def on_command_error(ctx, error):
if ctx.message in thinker.messages:
await thinker.stop_thinking(ctx.message)
cmdpfx = botdata.command_prefix(ctx)
loggingdb.command_finished(ctx, "errored", type(error).__name__, loggingdb_session)
try:
if isinstance(error, commands.CommandNotFound):
cmd = ctx.message.content[1:].split(" ")[0]
if cmd in deprecated_commands:
await ctx.send(f"You shouldn't use `{cmdpfx}{cmd}` anymore. It's *deprecated*. Try `{cmdpfx}{deprecated_commands[cmd]}` instead.")
return
elif cmd == "" or cmd.startswith("?") or cmd.startswith("!"):
return # These were probably not meant to be commands
if cmd.lower() in bot.commands:
new_message = ctx.message
new_message.content = cmdpfx + cmd.lower() + ctx.message.content[len(cmd) + 1:]
await bot.process_commands(new_message)
elif await invalid_command_reporting(ctx):
await ctx.send(f"🤔 Ya I dunno what a '{cmd}' is, but it ain't a command. Try `{cmdpfx}help` fer a list of things that ARE commands.")
elif isinstance(error, commands.CheckFailure):
emoji_dict = read_json(settings.resource("json/emoji.json"))
await ctx.message.add_reaction(bot.get_emoji(emoji_dict["unauthorized"]))
return # The user does not have permissions
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(embed=await bot.formatter.format_as_embed(ctx, ctx.command))
elif isinstance(error, commands.BadArgument):
signature = await get_cmd_signature(ctx)
await ctx.send((
"Thats the wrong type of argument for that command.\n\n"
f"Ya gotta do it like this:\n`{signature}`\n\n"
f"Try `{cmdpfx}help {ctx.command}` for a more detailed description of the command"))
elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, discord.errors.Forbidden):
await print_missing_perms(ctx, error)
elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, discord.errors.HTTPException):
await ctx.send("Looks like there was a problem with discord just then. Try again in a bit.")
elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, UserError):
loggingdb.command_finished(ctx, "user_errored", error.original.message, loggingdb_session)
await error.original.send_self(ctx, botdata)
else:
await ctx.send("Uh-oh, sumthin dun gone wrong 😱")
trace_string = report_error(ctx.message, error, skip_lines=4)
if settings.debug:
await ctx.send(f"```{trace_string}```")
except discord.errors.Forbidden:
await ctx.author.send("Looks like I don't have permission to talk in that channel, sorry")
error_file = "errors.json"
async def print_missing_perms(ctx, error):
if not (ctx.guild):
await ctx.send("Uh-oh, sumthin dun gone wrong 😱")
trace_string = report_error(ctx.message, error, skip_lines=0)
my_perms = ctx.channel.permissions_for(ctx.guild.me)
perms_strings = read_json(settings.resource("json/permissions.json"))
perms = []
for i in range(0, 32):
if ((permissions >> i) & 1) and not my_perms._bit(i):
words = perms_strings["0x{:08x}".format(1 << i)].split("_")
for i in range(0, len(words)):
words[i] = f"**{words[i][0] + words[i][1:].lower()}**"
perms.append(" ".join(words))
if perms:
await ctx.send("Looks like I'm missin' these permissions 😢:\n" + "\n".join(perms))
else:
await ctx.send(f"Looks like I'm missing permissions 😢. Have an admin giff me back my permissions, or re-invite me to the server using this invite link: {invite_link}")
def report_error(message, error, skip_lines=2):
if os.path.isfile(error_file):
error_list = read_json(error_file)
else:
error_list = []
try:
raise error.original
except:
trace = traceback.format_exc().replace("\"", "'").split("\n")
if skip_lines > 0 and len(trace) >= (2 + skip_lines):
del trace[1:(skip_lines + 1)]
trace = [x for x in trace if x] # removes empty lines
trace_string = "\n".join(trace)
loggingdb.insert_error(message, error, trace_string, loggingdb_session)
print(f"\nError on: {message.clean_content}\n{trace_string}\n")
return trace_string
if __name__ == '__main__':
bot.load_extension("cogs.general")
bot.load_extension("cogs.audio")
bot.load_extension("cogs.dotabase")
bot.load_extension("cogs.dotastats")
bot.load_extension("cogs.pokemon")
bot.load_extension("cogs.admin")
bot.load_extension("cogs.owner")
bot.run(settings.token)