Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename bot.db as bot._config #2967

Merged
merged 7 commits into from Sep 1, 2019
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions changelog.d/2967.breaking.rst
@@ -0,0 +1,11 @@
The main bot config is no longer directly accessible to cogs. New methods have been added for use where this is concerned.
mikeshardmind marked this conversation as resolved.
Show resolved Hide resolved
New methods for this include

- ``bot.get_shared_api_tokens``
- ``bot.set_shared_api_tokens``
- ``bot.get_embed_color``
- ``bot.get_embed_colour``
- ``bot.get_admin_roles``
- ``bot.get_admin_role_ids``
- ``bot.get_mod_roles``
- ``bot.get_mod_role_ids``
8 changes: 4 additions & 4 deletions docs/framework_apikeys.rst
Expand Up @@ -18,7 +18,7 @@ and when accessed in the code it should be done by

.. code-block:: python

await self.bot.db.api_tokens.get_raw("twitch", default={"client_id": None, "client_secret": None})
await self.bot.get_shared_api_keys("twitch")

Each service has its own dict of key, value pairs for each required key type. If there's only one key required then a name for the key is still required for storing and accessing.

Expand All @@ -30,7 +30,7 @@ and when accessed in the code it should be done by

.. code-block:: python

await self.bot.db.api_tokens.get_raw("youtube", default={"api_key": None})
await self.bot.get_shared_api_keys("youtube")


***********
Expand All @@ -42,7 +42,7 @@ Basic Usage
class MyCog:
@commands.command()
async def youtube(self, ctx, user: str):
apikey = await self.bot.db.api_tokens.get_raw("youtube", default={"api_key": None})
if apikey["api_key"] is None:
youtube_keys = await self.bot.get_shared_api_keys("youtube")
if youtube_keys.get("api_key") is None:
return await ctx.send("The YouTube API key has not been set.")
# Use the API key to access content as you normally would
10 changes: 5 additions & 5 deletions redbot/__main__.py
Expand Up @@ -52,8 +52,8 @@ async def _get_prefix_and_token(red, indict):
:param indict:
:return:
"""
indict["token"] = await red.db.token()
indict["prefix"] = await red.db.prefix()
indict["token"] = await red._config.token()
indict["prefix"] = await red._config.prefix()


def list_instances():
Expand Down Expand Up @@ -115,7 +115,7 @@ def main():
red = Red(
cli_flags=cli_flags, description=description, dm_help=None, fetch_offline_members=True
)
loop.run_until_complete(red.maybe_update_config())
loop.run_until_complete(red._maybe_update_config())
init_global_checks(red)
init_events(red, cli_flags)

Expand Down Expand Up @@ -153,11 +153,11 @@ def main():
loop.run_until_complete(red.start(token, bot=True))
except discord.LoginFailure:
log.critical("This token doesn't seem to be valid.")
db_token = loop.run_until_complete(red.db.token())
db_token = loop.run_until_complete(red._config.token())
if db_token and not cli_flags.no_prompt:
print("\nDo you want to reset the token? (y/n)")
if confirm("> "):
loop.run_until_complete(red.db.token.set(""))
loop.run_until_complete(red._config.token.set(""))
print("Token has been reset.")
except KeyboardInterrupt:
log.info("Keyboard interrupt detected. Quitting...")
Expand Down
33 changes: 12 additions & 21 deletions redbot/cogs/audio/audio.py
Expand Up @@ -296,7 +296,7 @@ async def _status_check(playing_servers):
else:
dur = lavalink.utils.format_time(player.current.length)
embed = discord.Embed(
colour=(await self._get_embed_colour(notify_channel)),
colour=(await self.bot.get_embed_color(notify_channel)),
title=_("Now Playing"),
description=description,
)
Expand Down Expand Up @@ -328,7 +328,8 @@ async def _status_check(playing_servers):
if notify_channel:
notify_channel = self.bot.get_channel(notify_channel)
embed = discord.Embed(
colour=(await self._get_embed_colour(notify_channel)), title=_("Queue ended.")
colour=(await self.bot.get_embed_colour(notify_channel)),
title=_("Queue ended."),
)
await notify_channel.send(embed=embed)

Expand All @@ -346,7 +347,7 @@ async def _status_check(playing_servers):
if message_channel:
message_channel = self.bot.get_channel(message_channel)
embed = discord.Embed(
colour=(await self._get_embed_colour(message_channel)),
colour=(await self.bot.get_embed_color(message_channel)),
title=_("Track Error"),
description="{}\n**[{}]({})**".format(
extra, player.current.title, player.current.uri
Expand Down Expand Up @@ -3834,14 +3835,12 @@ async def _channel_check(self, ctx):
return False

async def _check_api_tokens(self):
spotify = await self.bot.db.api_tokens.get_raw(
"spotify", default={"client_id": "", "client_secret": ""}
)
youtube = await self.bot.db.api_tokens.get_raw("youtube", default={"api_key": ""})
spotify = await self.bot.get_shared_api_tokens("spotify")
youtube = await self.bot.get_shared_api_tokens("youtube")
return {
"spotify_client_id": spotify["client_id"],
"spotify_client_secret": spotify["client_secret"],
"youtube_api": youtube["api_key"],
"spotify_client_id": spotify.get("client_id", ""),
"spotify_client_secret": spotify.get("client_secret", ""),
"youtube_api": youtube.get("api_key", ""),
}

async def _check_external(self):
Expand Down Expand Up @@ -4081,13 +4080,6 @@ async def _eq_msg_clear(eq_message):
except discord.errors.NotFound:
pass

async def _get_embed_colour(self, channel: discord.abc.GuildChannel):
# Unfortunately we need this for when context is unavailable.
if await self.bot.db.guild(channel.guild).use_bot_color():
return channel.guild.me.color
else:
return self.bot.color

async def _get_eq_reaction(self, ctx, message, emoji):
try:
reaction, user = await self.bot.wait_for(
Expand Down Expand Up @@ -4323,10 +4315,9 @@ def _make_token_auth(self, client_id, client_secret):
return {"Authorization": "Basic %s" % auth_header.decode("ascii")}

async def _request_token(self):
self.client_id = await self.bot.db.api_tokens.get_raw("spotify", default={"client_id": ""})
self.client_secret = await self.bot.db.api_tokens.get_raw(
"spotify", default={"client_secret": ""}
)
tokens = await self.bot.get_shared_api_tokens("spotify")
self.client_id = tokens.get("client_id", "")
self.client_secret = tokens.get("client_secret", "")
payload = {"grant_type": "client_credentials"}
headers = self._make_token_auth(
self.client_id["client_id"], self.client_secret["client_secret"]
Expand Down
4 changes: 2 additions & 2 deletions redbot/cogs/bank/bank.py
Expand Up @@ -47,9 +47,9 @@ async def pred(ctx: commands.Context):
return True
if ctx.channel.permissions_for(author).manage_guild:
return True
admin_roles = set(await ctx.bot.db.guild(ctx.guild).admin_role())
admin_role_ids = await ctx.bot.get_admin_role_ids(ctx.guild.id)
for role in author.roles:
if role.id in admin_roles:
if role.id in admin_role_ids:
return True
else:
return await ctx.bot.is_owner(author)
Expand Down
21 changes: 11 additions & 10 deletions redbot/cogs/image/image.py
Expand Up @@ -28,8 +28,9 @@ def cog_unload(self):
async def initialize(self) -> None:
"""Move the API keys from cog stored config to core bot config if they exist."""
imgur_token = await self.settings.imgur_client_id()
if imgur_token is not None and "imgur" not in await self.bot.db.api_tokens():
await self.bot.db.api_tokens.set_raw("imgur", value={"client_id": imgur_token})
if imgur_token is not None:
if not await self.bot.get_shared_api_tokens("imgur"):
await self.bot.set_shared_api_tokens(client_id=imgur_token)
await self.settings.imgur_client_id.clear()

@commands.group(name="imgur")
Expand All @@ -48,15 +49,15 @@ async def imgur_search(self, ctx, *, term: str):
"""
url = self.imgur_base_url + "gallery/search/time/all/0"
params = {"q": term}
imgur_client_id = await ctx.bot.db.api_tokens.get_raw("imgur", default=None)
imgur_client_id = (await ctx.bot.get_shared_api_tokens("imgur")).get("client_id")
if not imgur_client_id:
await ctx.send(
_(
"A Client ID has not been set! Please set one with `{prefix}imgurcreds`."
).format(prefix=ctx.prefix)
)
return
headers = {"Authorization": "Client-ID {}".format(imgur_client_id["client_id"])}
headers = {"Authorization": "Client-ID {}".format(imgur_client_id)}
async with self.session.get(url, headers=headers, params=params) as search_get:
data = await search_get.json()

Expand Down Expand Up @@ -101,7 +102,7 @@ async def imgur_subreddit(
await ctx.send_help()
return

imgur_client_id = await ctx.bot.db.api_tokens.get_raw("imgur", default=None)
imgur_client_id = (await ctx.bot.get_shared_api_tokens("imgur")).get("client_id")
if not imgur_client_id:
await ctx.send(
_(
Expand All @@ -111,7 +112,7 @@ async def imgur_subreddit(
return

links = []
headers = {"Authorization": "Client-ID {}".format(imgur_client_id["client_id"])}
headers = {"Authorization": "Client-ID {}".format(imgur_client_id)}
url = self.imgur_base_url + "gallery/r/{}/{}/{}/0".format(subreddit, sort, window)

async with self.session.get(url, headers=headers) as sub_get:
Expand Down Expand Up @@ -164,7 +165,7 @@ async def gif(self, ctx, *keywords):
await ctx.send_help()
return

giphy_api_key = await ctx.bot.db.api_tokens.get_raw("GIPHY", default=None)
giphy_api_key = (await ctx.bot.get_shared_api_tokens("GIPHY")).get("api_key")
if not giphy_api_key:
await ctx.send(
_("An API key has not been set! Please set one with `{prefix}giphycreds`.").format(
Expand All @@ -174,7 +175,7 @@ async def gif(self, ctx, *keywords):
return

url = "http://api.giphy.com/v1/gifs/search?&api_key={}&q={}".format(
giphy_api_key["api_key"], keywords
giphy_api_key, keywords
)

async with self.session.get(url) as r:
Expand All @@ -197,7 +198,7 @@ async def gifr(self, ctx, *keywords):
await ctx.send_help()
return

giphy_api_key = await ctx.bot.db.api_tokens.get_raw("GIPHY", default=None)
giphy_api_key = (await ctx.bot.get_shared_api_tokens("GIPHY")).get("api_key")
if not giphy_api_key:
await ctx.send(
_("An API key has not been set! Please set one with `{prefix}giphycreds`.").format(
Expand All @@ -207,7 +208,7 @@ async def gifr(self, ctx, *keywords):
return

url = "http://api.giphy.com/v1/gifs/random?&api_key={}&tag={}".format(
giphy_api_key["api_key"], keywords
giphy_api_key, keywords
)

async with self.session.get(url) as r:
Expand Down
18 changes: 9 additions & 9 deletions redbot/cogs/streams/streams.py
Expand Up @@ -82,27 +82,27 @@ async def initialize(self) -> None:
async def move_api_keys(self):
"""Move the API keys from cog stored config to core bot config if they exist."""
tokens = await self.db.tokens()
youtube = await self.bot.db.api_tokens.get_raw("youtube", default={})
twitch = await self.bot.db.api_tokens.get_raw("twitch", default={})
youtube = await self.bot.get_shared_api_tokens("youtube")
twitch = await self.bot.get_shared_api_tokens("twitch")
for token_type, token in tokens.items():
if token_type == "YoutubeStream" and "api_key" not in youtube:
await self.bot.db.api_tokens.set_raw("youtube", value={"api_key": token})
await self.bot.set_shared_api_tokens("youtube", api_key=token)
if token_type == "TwitchStream" and "client_id" not in twitch:
# Don't need to check Community since they're set the same
await self.bot.db.api_tokens.set_raw("twitch", value={"client_id": token})
await self.bot.set_shared_api_tokens("twitch", client_id=token)
await self.db.tokens.clear()

@commands.command()
async def twitchstream(self, ctx: commands.Context, channel_name: str):
"""Check if a Twitch channel is live."""
token = await self.bot.db.api_tokens.get_raw("twitch", default={"client_id": None})
token = (await self.bot.get_shared_api_tokens("twitch")).get("client_id")
stream = TwitchStream(name=channel_name, token=token)
await self.check_online(ctx, stream)

@commands.command()
async def youtubestream(self, ctx: commands.Context, channel_id_or_name: str):
"""Check if a YouTube channel is live."""
apikey = await self.bot.db.api_tokens.get_raw("youtube", default={"api_key": None})
apikey = await self.bot.get_shared_api_tokens("youtube")
is_name = self.check_name_or_id(channel_id_or_name)
if is_name:
stream = YoutubeStream(name=channel_id_or_name, token=apikey)
Expand Down Expand Up @@ -273,7 +273,7 @@ async def streamalert_list(self, ctx: commands.Context):
async def stream_alert(self, ctx: commands.Context, _class, channel_name):
stream = self.get_stream(_class, channel_name)
if not stream:
token = await self.bot.db.api_tokens.get_raw(_class.token_name, default=None)
token = await self.bot.get_shared_api_tokens(_class.token_name)
is_yt = _class.__name__ == "YoutubeStream"
if is_yt and not self.check_name_or_id(channel_name):
stream = _class(id=channel_name, token=token)
Expand Down Expand Up @@ -651,8 +651,8 @@ async def load_streams(self):
pass
else:
raw_stream["_messages_cache"].append(msg)
token = await self.bot.db.api_tokens.get_raw(_class.token_name, default=None)
if token is not None:
token = await self.bot.get_shared_api_tokens(_class.token_name)
if token:
raw_stream["token"] = token
streams.append(_class(**raw_stream))

Expand Down