Remove from __main__ import ... statements (#1956)

This commit is contained in:
Caleb Johnson 2018-12-15 20:17:46 -06:00 committed by Toby Harradine
parent e874e6aa01
commit a42c4fb215
8 changed files with 71 additions and 70 deletions

View File

@ -2,7 +2,6 @@ from discord.ext import commands
from .utils.chat_formatting import box
from .utils.dataIO import dataIO
from .utils import checks
from __main__ import user_allowed, send_cmd_help
from copy import copy
import os
import discord
@ -19,7 +18,7 @@ class Alias:
async def alias(self, ctx):
"""Manage per-server aliases for commands"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
@alias.command(name="add", pass_context=True, no_pm=True)
@checks.mod_or_permissions(manage_server=True)
@ -121,7 +120,7 @@ class Alias:
if not prefix:
return
if server.id in self.aliases and user_allowed(message):
if server.id in self.aliases and self.bot.user_allowed(message):
alias = self.first_word(msg[len(prefix):]).lower()
if alias in self.aliases[server.id]:
new_command = self.aliases[server.id][alias]

View File

@ -7,7 +7,6 @@ from cogs.utils.dataIO import dataIO
from cogs.utils import checks
from cogs.utils.chat_formatting import pagify, escape
from urllib.parse import urlparse
from __main__ import send_cmd_help, settings
from json import JSONDecodeError
import re
import logging
@ -208,11 +207,11 @@ class Playlist:
if self.main_class._playlist_exists_global(self.name):
return False
admin_role = settings.get_server_admin(self.server)
mod_role = settings.get_server_mod(self.server)
admin_role = self.bot.settings.get_server_admin(self.server)
mod_role = self.bot.settings.get_server_mod(self.server)
is_playlist_author = self.is_author(user)
is_bot_owner = user.id == settings.owner
is_bot_owner = user.id == self.bot.settings.owner
is_server_owner = self.server.owner.id == self.author
is_admin = discord.utils.get(user.roles, name=admin_role) is not None
is_mod = discord.utils.get(user.roles, name=mod_role) is not None
@ -1146,7 +1145,7 @@ class Audio:
async def audioset(self, ctx):
"""Audio settings."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
@audioset.command(name="cachemax")
@ -1323,7 +1322,7 @@ class Audio:
async def audiostat(self, ctx):
"""General stats on audio stuff."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
@audiostat.command(name="servers")
@ -1339,7 +1338,7 @@ class Audio:
async def cache(self, ctx):
"""Cache management tools."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
@cache.command(name="dump")
@ -1396,7 +1395,7 @@ class Audio:
async def local(self, ctx):
"""Local playlists commands"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
@local.command(name="start", pass_context=True, no_pm=True)
async def play_local(self, ctx, *, name):
@ -1592,7 +1591,7 @@ class Audio:
async def playlist(self, ctx):
"""Playlist management/control."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
@playlist.command(pass_context=True, no_pm=True, name="create")
async def playlist_create(self, ctx, name):
@ -2048,10 +2047,10 @@ class Audio:
if not self.get_server_settings(server)["VOTE_ENABLED"]:
return True
admin_role = settings.get_server_admin(server)
mod_role = settings.get_server_mod(server)
admin_role = self.bot.settings.get_server_admin(server)
mod_role = self.bot.settings.get_server_mod(server)
is_owner = member.id == settings.owner
is_owner = member.id == self.bot.settings.owner
is_server_owner = member == server.owner
is_admin = discord.utils.get(member.roles, name=admin_role) is not None
is_mod = discord.utils.get(member.roles, name=mod_role) is not None

View File

@ -2,7 +2,6 @@ from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils import checks
from cogs.utils.chat_formatting import pagify, box
from __main__ import send_cmd_help, set_cog
import os
from subprocess import run as sp_run, PIPE
import shutil
@ -63,14 +62,14 @@ class Downloader:
async def cog(self, ctx):
"""Additional cogs management"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
@cog.group(pass_context=True)
async def repo(self, ctx):
"""Repo management commands"""
if ctx.invoked_subcommand is None or \
isinstance(ctx.invoked_subcommand, commands.Group):
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
@repo.command(name="add", pass_context=True)
@ -375,7 +374,7 @@ class Downloader:
if cog not in self.repos[repo_name]:
await self.bot.say("That cog isn't available from that repo.")
return
set_cog("cogs." + cog, False)
self.bot.set_cog("cogs." + cog, False)
self.repos[repo_name][cog]['INSTALLED'] = False
self.save_repos()
os.remove(os.path.join("cogs", cog + ".py"))
@ -412,7 +411,7 @@ class Downloader:
await self.bot.say("Ok then, you can load it with"
" `{}load {}`".format(ctx.prefix, cog))
elif answer.content.lower().strip() == "yes":
set_cog("cogs." + cog, True)
self.bot.set_cog("cogs." + cog, True)
owner = self.bot.get_cog('Owner')
await owner.load.callback(owner, cog_name=cog)
else:

View File

@ -7,7 +7,6 @@ from copy import deepcopy
from .utils import checks
from cogs.utils.chat_formatting import pagify, box
from enum import Enum
from __main__ import send_cmd_help
import os
import time
import logging
@ -302,7 +301,7 @@ class Economy:
async def _bank(self, ctx):
"""Bank operations"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
@_bank.command(pass_context=True, no_pm=True)
async def register(self, ctx):
@ -626,7 +625,7 @@ class Economy:
for k, v in settings.items():
msg += "{}: {}\n".format(k, v)
msg += "```"
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
await self.bot.say(msg)
@economyset.command(pass_context=True)

View File

@ -2,7 +2,6 @@ import discord
from discord.ext import commands
from .utils.dataIO import dataIO
from .utils import checks
from __main__ import send_cmd_help, settings
from datetime import datetime
from collections import deque, defaultdict, OrderedDict
from cogs.utils.chat_formatting import escape_mass_mentions, box, pagify
@ -113,8 +112,8 @@ class Mod:
"""Manages server administration settings."""
if ctx.invoked_subcommand is None:
server = ctx.message.server
await send_cmd_help(ctx)
roles = settings.get_server(server).copy()
await self.bot.send_cmd_help(ctx)
roles = self.bot.settings.get_server(server).copy()
_settings = {**self.settings[server.id], **roles}
if "respect_hierarchy" not in _settings:
_settings["respect_hierarchy"] = default_settings["respect_hierarchy"]
@ -155,7 +154,7 @@ class Mod:
"".format(channel.mention))
else:
if self.settings[server.id]["mod-log"] is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
self.settings[server.id]["mod-log"] = None
await self.bot.say("Mod log deactivated.")
@ -177,7 +176,7 @@ class Mod:
"".format(max_mentions))
else:
if self.settings[server.id]["ban_mention_spam"] is False:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
self.settings[server.id]["ban_mention_spam"] = False
await self.bot.say("Autoban for mention spam disabled.")
@ -690,7 +689,7 @@ class Mod:
async def cleanup(self, ctx):
"""Deletes messages."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
@cleanup.command(pass_context=True, no_pm=True)
async def text(self, ctx, text: str, number: int):
@ -1014,7 +1013,7 @@ class Mod:
try:
case = int(case)
if not reason:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
except:
if reason:
@ -1023,7 +1022,7 @@ class Mod:
reason = case
case = self.last_case[server.id].get(author.id)
if case is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
try:
await self.update_case(server, case=case, mod=author,
@ -1047,7 +1046,7 @@ class Mod:
async def ignore(self, ctx):
"""Adds servers/channels to ignorelist"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
await self.bot.say(self.count_ignored())
@ignore.command(name="channel", pass_context=True)
@ -1087,7 +1086,7 @@ class Mod:
async def unignore(self, ctx):
"""Removes servers/channels from ignorelist"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
await self.bot.say(self.count_ignored())
@unignore.command(name="channel", pass_context=True)
@ -1137,7 +1136,7 @@ class Mod:
Using this command with no subcommands will send
the list of the server's filtered words."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
server = ctx.message.server
author = ctx.message.author
if server.id in self.filter:
@ -1159,7 +1158,7 @@ class Mod:
filter add word1 word2 word3
filter add \"This is a sentence\""""
if words == ():
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
server = ctx.message.server
added = 0
@ -1184,7 +1183,7 @@ class Mod:
filter remove word1 word2 word3
filter remove \"This is a sentence\""""
if words == ():
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
return
server = ctx.message.server
removed = 0
@ -1206,7 +1205,7 @@ class Mod:
async def editrole(self, ctx):
"""Edits roles settings"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
await self.bot.send_cmd_help(ctx)
@editrole.command(aliases=["color"], pass_context=True)
async def colour(self, ctx, role: discord.Role, value: discord.Colour):
@ -1308,12 +1307,12 @@ class Mod:
raise TypeError('Only messages, members or roles may be passed')
server = obj.server
admin_role = settings.get_server_admin(server)
admin_role = self.bot.settings.get_server_admin(server)
if isinstance(obj, discord.Role):
return obj.name == admin_role
if user.id == settings.owner:
if user.id == self.bot.settings.owner:
return True
elif discord.utils.get(user.roles, name=admin_role):
return True
@ -1331,13 +1330,13 @@ class Mod:
raise TypeError('Only messages, members or roles may be passed')
server = obj.server
admin_role = settings.get_server_admin(server)
mod_role = settings.get_server_mod(server)
admin_role = self.bot.settings.get_server_admin(server)
mod_role = self.bot.settings.get_server_mod(server)
if isinstance(obj, discord.Role):
return obj.name in [admin_role, mod_role]
if user.id == settings.owner:
if user.id == self.bot.settings.owner:
return True
elif discord.utils.get(user.roles, name=admin_role):
return True

View File

@ -2,7 +2,6 @@ import discord
from discord.ext import commands
from cogs.utils import checks
from cogs.utils.converters import GlobalUser
from __main__ import set_cog
from .utils.dataIO import dataIO
from .utils.chat_formatting import pagify, box
@ -77,7 +76,7 @@ class Owner:
'something went wrong. Check your console '
'or logs for more information.')
else:
set_cog(module, True)
self.bot.set_cog(module, True)
await self.disable_commands()
await self.bot.say("The cog has been loaded.")
@ -95,7 +94,7 @@ class Owner:
" turn off autoloading at start just in case"
" this isn't supposed to happen.")
else:
set_cog(module, False)
self.bot.set_cog(module, False)
try: # No matter what we should try to unload it
self._unload_cog(module)
except OwnerUnloadWithoutReloadError:
@ -115,7 +114,7 @@ class Owner:
cogs = self._list_cogs()
still_loaded = []
for cog in cogs:
set_cog(cog, False)
self.bot.set_cog(cog, False)
try:
self._unload_cog(cog)
except OwnerUnloadWithoutReloadError:
@ -158,7 +157,7 @@ class Owner:
await self.bot.say("That cog could not be loaded. Check your"
" console or logs for more information.")
else:
set_cog(module, True)
self.bot.set_cog(module, True)
await self.disable_commands()
await self.bot.say("The cog has been reloaded.")

View File

@ -1,6 +1,5 @@
from discord.ext import commands
import discord.utils
from __main__ import settings
#
# This is a modified version of checks.py, originally made by Rapptz
@ -11,7 +10,7 @@ from __main__ import settings
def is_owner_check(ctx):
_id = ctx.message.author.id
return _id == settings.owner or _id in ctx.bot.settings.co_owners
return _id == ctx.bot.settings.owner or _id in ctx.bot.settings.co_owners
def is_owner():
return commands.check(is_owner_check)
@ -52,8 +51,8 @@ def role_or_permissions(ctx, check, **perms):
def mod_or_permissions(**perms):
def predicate(ctx):
server = ctx.message.server
mod_role = settings.get_server_mod(server).lower()
admin_role = settings.get_server_admin(server).lower()
mod_role = ctx.bot.settings.get_server_mod(server).lower()
admin_role = ctx.bot.settings.get_server_admin(server).lower()
return role_or_permissions(ctx, lambda r: r.name.lower() in (mod_role,admin_role), **perms)
return commands.check(predicate)
@ -61,7 +60,7 @@ def mod_or_permissions(**perms):
def admin_or_permissions(**perms):
def predicate(ctx):
server = ctx.message.server
admin_role = settings.get_server_admin(server)
admin_role = ctx.bot.settings.get_server_admin(server)
return role_or_permissions(ctx, lambda r: r.name.lower() == admin_role.lower(), **perms)
return commands.check(predicate)

44
red.py
View File

@ -63,6 +63,12 @@ class Bot(commands.Bot):
self.logger = set_logger(self)
self._last_exception = None
self.oauth_url = ""
try:
self._cog_registry = dataIO.load_json("data/red/cogs.json")
except Exception:
self._cog_registry = {}
if 'self_bot' in kwargs:
self.settings.self_bot = kwargs['self_bot']
else:
@ -218,6 +224,18 @@ class Bot(commands.Bot):
response = self.loop.run_in_executor(None, install)
return await asyncio.wait_for(response, timeout=timeout)
def set_cog(self, cog, value, save=True):
self._cog_registry[cog] = value
if save:
self.save_cogs()
def save_cogs(self):
dataIO.save_json("data/red/cogs.json", self._cog_registry)
@property
def first_run(self):
return self.settings.bot_settings == self.settings.default_settings
class Formatter(commands.HelpFormatter):
def __init__(self, *args, **kwargs):
@ -244,6 +262,7 @@ def initialize(bot_class=Bot, formatter_class=Formatter):
__main__.send_cmd_help = bot.send_cmd_help # Backwards
__main__.user_allowed = bot.user_allowed # compatibility
__main__.settings = bot.settings # sucks
__main__.set_cog = bot.set_cog # greatly
async def get_oauth_url():
try:
@ -526,21 +545,10 @@ def get_answer():
return False
def set_cog(cog, value): # TODO: move this out of red.py
data = dataIO.load_json("data/red/cogs.json")
data[cog] = value
dataIO.save_json("data/red/cogs.json", data)
def load_cogs(bot):
defaults = ("alias", "audio", "customcom", "downloader", "economy",
"general", "image", "mod", "streams", "trivia")
try:
registry = dataIO.load_json("data/red/cogs.json")
except:
registry = {}
bot.load_extension('cogs.owner')
owner_cog = bot.get_cog('Owner')
if owner_cog is None:
@ -550,21 +558,21 @@ def load_cogs(bot):
if bot.settings._no_cogs:
bot.logger.debug("Skipping initial cogs loading (--no-cogs)")
if not os.path.isfile("data/red/cogs.json"):
dataIO.save_json("data/red/cogs.json", {})
bot._cog_registry.clear()
bot.save_cogs()
return
failed = []
extensions = owner_cog._list_cogs()
if not registry: # All default cogs enabled by default
if not bot._cog_registry: # All default cogs enabled by default
for ext in defaults:
registry["cogs." + ext] = True
bot._cog_registry["cogs." + ext] = True
for extension in extensions:
if extension.lower() == "cogs.owner":
continue
to_load = registry.get(extension, False)
to_load = bot._cog_registry.get(extension, False)
if to_load:
try:
owner_cog._load_cog(extension)
@ -572,9 +580,9 @@ def load_cogs(bot):
print("{}: {}".format(e.__class__.__name__, str(e)))
bot.logger.exception(e)
failed.append(extension)
registry[extension] = False
bot._cog_registry[extension] = False
dataIO.save_json("data/red/cogs.json", registry)
bot.save_cogs()
if failed:
print("\nFailed to load: {}\n".format(" ".join(failed)))