[V3] Update code standards (black code format pass) (#1650)

* ran black: code formatter against `redbot/` with `-l 99`

* badge
This commit is contained in:
Michael H
2018-05-14 15:33:24 -04:00
committed by Will
parent e7476edd68
commit b88b5a2601
90 changed files with 3629 additions and 3223 deletions

View File

@@ -27,4 +27,4 @@ class OfflineStream(StreamsError):
class OfflineCommunity(StreamsError):
pass
pass

View File

@@ -1,15 +1,11 @@
import subprocess
TO_TRANSLATE = [
'../mod.py'
]
TO_TRANSLATE = ["../mod.py"]
def regen_messages():
subprocess.run(
['pygettext', '-n'] + TO_TRANSLATE
)
subprocess.run(["pygettext", "-n"] + TO_TRANSLATE)
if __name__ == "__main__":
regen_messages()
regen_messages()

View File

@@ -3,9 +3,24 @@ from redbot.core import Config, checks, commands
from redbot.core.utils.chat_formatting import pagify
from redbot.core.bot import Red
from redbot.core.i18n import Translator, cog_i18n
from .streamtypes import TwitchStream, HitboxStream, MixerStream, PicartoStream, TwitchCommunity, YoutubeStream
from .errors import (OfflineStream, StreamNotFound, APIError, InvalidYoutubeCredentials,
CommunityNotFound, OfflineCommunity, StreamsError, InvalidTwitchCredentials)
from .streamtypes import (
TwitchStream,
HitboxStream,
MixerStream,
PicartoStream,
TwitchCommunity,
YoutubeStream,
)
from .errors import (
OfflineStream,
StreamNotFound,
APIError,
InvalidYoutubeCredentials,
CommunityNotFound,
OfflineCommunity,
StreamsError,
InvalidTwitchCredentials,
)
from . import streamtypes as StreamClasses
from collections import defaultdict
import asyncio
@@ -20,21 +35,11 @@ _ = Translator("Streams", __file__)
@cog_i18n(_)
class Streams:
global_defaults = {
"tokens": {},
"streams": [],
"communities": []
}
global_defaults = {"tokens": {}, "streams": [], "communities": []}
guild_defaults = {
"autodelete": False,
"mention_everyone": False,
"mention_here": False
}
guild_defaults = {"autodelete": False, "mention_everyone": False, "mention_here": False}
role_defaults = {
"mention": False
}
role_defaults = {"mention": False}
def __init__(self, bot: Red):
self.db = Config.get_conf(self, 26262626)
@@ -67,8 +72,7 @@ class Streams:
async def twitch(self, ctx: commands.Context, channel_name: str):
"""Checks if a Twitch channel is streaming"""
token = await self.db.tokens.get_raw(TwitchStream.__name__, default=None)
stream = TwitchStream(name=channel_name,
token=token)
stream = TwitchStream(name=channel_name, token=token)
await self.check_online(ctx, stream)
@commands.command()
@@ -110,14 +114,21 @@ class Streams:
except StreamNotFound:
await ctx.send(_("The channel doesn't seem to exist."))
except InvalidTwitchCredentials:
await ctx.send(_("The twitch token is either invalid or has not been set. "
"See `{}`.").format("{}streamset twitchtoken".format(ctx.prefix)))
await ctx.send(
_("The twitch token is either invalid or has not been set. " "See `{}`.").format(
"{}streamset twitchtoken".format(ctx.prefix)
)
)
except InvalidYoutubeCredentials:
await ctx.send(_("The Youtube API key is either invalid or has not been set. "
"See {}.").format("`{}streamset youtubekey`".format(ctx.prefix)))
await ctx.send(
_("The Youtube API key is either invalid or has not been set. " "See {}.").format(
"`{}streamset youtubekey`".format(ctx.prefix)
)
)
except APIError:
await ctx.send(_("Something went wrong whilst trying to contact the "
"stream service's API."))
await ctx.send(
_("Something went wrong whilst trying to contact the " "stream service's API.")
)
else:
await ctx.send(embed=embed)
@@ -166,7 +177,7 @@ class Streams:
await self.stream_alert(ctx, PicartoStream, channel_name)
@streamalert.command(name="stop")
async def streamalert_stop(self, ctx: commands.Context, _all: bool=False):
async def streamalert_stop(self, ctx: commands.Context, _all: bool = False):
"""Stops all stream notifications in the channel
Adding 'yes' will disable all notifications in the server"""
@@ -191,8 +202,9 @@ class Streams:
self.streams = streams
await self.save_streams()
msg = _("All {}'s stream alerts have been disabled."
"").format("server" if _all else "channel")
msg = _("All {}'s stream alerts have been disabled." "").format(
"server" if _all else "channel"
)
await ctx.send(msg)
@@ -226,23 +238,29 @@ class Streams:
if is_yt and not self.check_name_or_id(channel_name):
stream = _class(id=channel_name, token=token)
else:
stream = _class(name=channel_name,
token=token)
stream = _class(name=channel_name, token=token)
try:
exists = await self.check_exists(stream)
except InvalidTwitchCredentials:
await ctx.send(
_("The twitch token is either invalid or has not been set. "
"See {}.").format("`{}streamset twitchtoken`".format(ctx.prefix)))
_("The twitch token is either invalid or has not been set. " "See {}.").format(
"`{}streamset twitchtoken`".format(ctx.prefix)
)
)
return
except InvalidYoutubeCredentials:
await ctx.send(_("The Youtube API key is either invalid or has not been set. "
"See {}.").format("`{}streamset youtubekey`".format(ctx.prefix)))
await ctx.send(
_(
"The Youtube API key is either invalid or has not been set. " "See {}."
).format(
"`{}streamset youtubekey`".format(ctx.prefix)
)
)
return
except APIError:
await ctx.send(
_("Something went wrong whilst trying to contact the "
"stream service's API."))
_("Something went wrong whilst trying to contact the " "stream service's API.")
)
return
else:
if not exists:
@@ -260,16 +278,18 @@ class Streams:
await community.get_community_streams()
except InvalidTwitchCredentials:
await ctx.send(
_("The twitch token is either invalid or has not been set. "
"See {}.").format("`{}streamset twitchtoken`".format(ctx.prefix)))
_("The twitch token is either invalid or has not been set. " "See {}.").format(
"`{}streamset twitchtoken`".format(ctx.prefix)
)
)
return
except CommunityNotFound:
await ctx.send(_("That community doesn't seem to exist."))
return
except APIError:
await ctx.send(
_("Something went wrong whilst trying to contact the "
"stream service's API."))
_("Something went wrong whilst trying to contact the " "stream service's API.")
)
return
except OfflineCommunity:
pass
@@ -331,12 +351,21 @@ class Streams:
current_setting = await self.db.guild(guild).mention_everyone()
if current_setting:
await self.db.guild(guild).mention_everyone.set(False)
await ctx.send(_("{} will no longer be mentioned "
"for a stream alert.").format("@\u200beveryone"))
await ctx.send(
_("{} will no longer be mentioned " "for a stream alert.").format(
"@\u200beveryone"
)
)
else:
await self.db.guild(guild).mention_everyone.set(True)
await ctx.send(_("When a stream configured for stream alerts "
"comes online, {} will be mentioned").format("@\u200beveryone"))
await ctx.send(
_(
"When a stream configured for stream alerts "
"comes online, {} will be mentioned"
).format(
"@\u200beveryone"
)
)
@mention.command(aliases=["here"])
@commands.guild_only()
@@ -346,12 +375,19 @@ class Streams:
current_setting = await self.db.guild(guild).mention_here()
if current_setting:
await self.db.guild(guild).mention_here.set(False)
await ctx.send(_("{} will no longer be mentioned "
"for a stream alert.").format("@\u200bhere"))
await ctx.send(
_("{} will no longer be mentioned " "for a stream alert.").format("@\u200bhere")
)
else:
await self.db.guild(guild).mention_here.set(True)
await ctx.send(_("When a stream configured for stream alerts "
"comes online, {} will be mentioned").format("@\u200bhere"))
await ctx.send(
_(
"When a stream configured for stream alerts "
"comes online, {} will be mentioned"
).format(
"@\u200bhere"
)
)
@mention.command()
@commands.guild_only()
@@ -363,13 +399,22 @@ class Streams:
return
if current_setting:
await self.db.role(role).mention.set(False)
await ctx.send(_("{} will no longer be mentioned "
"for a stream alert").format("@\u200b{}".format(role.name)))
await ctx.send(
_("{} will no longer be mentioned " "for a stream alert").format(
"@\u200b{}".format(role.name)
)
)
else:
await self.db.role(role).mention.set(True)
await ctx.send(_("When a stream configured for stream alerts "
"comes online, {} will be mentioned"
"").format("@\u200b{}".format(role.name)))
await ctx.send(
_(
"When a stream configured for stream alerts "
"comes online, {} will be mentioned"
""
).format(
"@\u200b{}".format(role.name)
)
)
@streamset.command()
@commands.guild_only()
@@ -377,8 +422,7 @@ class Streams:
"""Toggles automatic deletion of notifications for streams that go offline"""
await self.db.guild(ctx.guild).autodelete.set(on_off)
if on_off:
await ctx.send("The notifications will be deleted once "
"streams go offline.")
await ctx.send("The notifications will be deleted once " "streams go offline.")
else:
await ctx.send("Notifications will never be deleted.")
@@ -387,14 +431,20 @@ class Streams:
stream.channels.append(ctx.channel.id)
if stream not in self.streams:
self.streams.append(stream)
await ctx.send(_("I'll send a notification in this channel when {} "
"is online.").format(stream.name))
await ctx.send(
_("I'll send a notification in this channel when {} " "is online.").format(
stream.name
)
)
else:
stream.channels.remove(ctx.channel.id)
if not stream.channels:
self.streams.remove(stream)
await ctx.send(_("I won't send notifications about {} in this "
"channel anymore.").format(stream.name))
await ctx.send(
_("I won't send notifications about {} in this " "channel anymore.").format(
stream.name
)
)
await self.save_streams()
@@ -403,16 +453,28 @@ class Streams:
community.channels.append(ctx.channel.id)
if community not in self.communities:
self.communities.append(community)
await ctx.send(_("I'll send a notification in this channel when a "
"channel is streaming to the {} community"
"").format(community.name))
await ctx.send(
_(
"I'll send a notification in this channel when a "
"channel is streaming to the {} community"
""
).format(
community.name
)
)
else:
community.channels.remove(ctx.channel.id)
if not community.channels:
self.communities.remove(community)
await ctx.send(_("I won't send notifications about channels streaming "
"to the {} community in this channel anymore"
"").format(community.name))
await ctx.send(
_(
"I won't send notifications about channels streaming "
"to the {} community in this channel anymore"
""
).format(
community.name
)
)
await self.save_communities()
def get_stream(self, _class, name):
@@ -499,13 +561,13 @@ class Streams:
settings = self.db.guild(guild)
mentions = []
if await settings.mention_everyone():
mentions.append('@everyone')
mentions.append("@everyone")
if await settings.mention_here():
mentions.append('@here')
mentions.append("@here")
for role in guild.roles:
if await self.db.role(role).mention():
mentions.append(role.mention)
return ' '.join(mentions)
return " ".join(mentions)
async def check_communities(self):
for community in self.communities:
@@ -579,8 +641,7 @@ class Streams:
# Fast dedupe below
seen = set()
seen_add = seen.add
return [x for x in streams
if not (x.name.lower() in seen or seen_add(x.name.lower()))]
return [x for x in streams if not (x.name.lower() in seen or seen_add(x.name.lower()))]
# return streams
@@ -604,8 +665,7 @@ class Streams:
# Fast dedupe below
seen = set()
seen_add = seen.add
return [x for x in communities
if not (x.name.lower() in seen or seen_add(x.name.lower()))]
return [x for x in communities if not (x.name.lower() in seen or seen_add(x.name.lower()))]
# return communities
async def save_streams(self):

View File

@@ -1,5 +1,12 @@
from .errors import StreamNotFound, APIError, OfflineStream, CommunityNotFound, OfflineCommunity, \
InvalidYoutubeCredentials, InvalidTwitchCredentials
from .errors import (
StreamNotFound,
APIError,
OfflineStream,
CommunityNotFound,
OfflineCommunity,
InvalidYoutubeCredentials,
InvalidTwitchCredentials,
)
from random import choice, sample
from string import ascii_letters
import discord
@@ -23,6 +30,7 @@ def rnd(url):
class TwitchCommunity:
def __init__(self, **kwargs):
self.name = kwargs.pop("name")
self.id = kwargs.pop("id", None)
@@ -32,15 +40,12 @@ class TwitchCommunity:
self.type = self.__class__.__name__
async def get_community_id(self):
headers = {
"Accept": "application/vnd.twitchtv.v5+json",
"Client-ID": str(self._token)
}
params = {
"name": self.name
}
headers = {"Accept": "application/vnd.twitchtv.v5+json", "Client-ID": str(self._token)}
params = {"name": self.name}
async with aiohttp.ClientSession() as session:
async with session.get(TWITCH_COMMUNITIES_ENDPOINT, headers=headers, params=params) as r:
async with session.get(
TWITCH_COMMUNITIES_ENDPOINT, headers=headers, params=params
) as r:
data = await r.json()
if r.status == 200:
return data["_id"]
@@ -57,14 +62,8 @@ class TwitchCommunity:
self.id = await self.get_community_id()
except CommunityNotFound:
raise
headers = {
"Accept": "application/vnd.twitchtv.v5+json",
"Client-ID": str(self._token)
}
params = {
"community_id": self.id,
"limit": 100
}
headers = {"Accept": "application/vnd.twitchtv.v5+json", "Client-ID": str(self._token)}
params = {"community_id": self.id, "limit": 100}
url = TWITCH_BASE_URL + "/kraken/streams"
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as r:
@@ -82,14 +81,11 @@ class TwitchCommunity:
raise APIError()
async def make_embed(self, streams: list) -> discord.Embed:
headers = {
"Accept": "application/vnd.twitchtv.v5+json",
"Client-ID": str(self._token)
}
headers = {"Accept": "application/vnd.twitchtv.v5+json", "Client-ID": str(self._token)}
async with aiohttp.ClientSession() as session:
async with session.get(
"{}/{}".format(TWITCH_COMMUNITIES_ENDPOINT, self.id),
headers=headers) as r:
"{}/{}".format(TWITCH_COMMUNITIES_ENDPOINT, self.id), headers=headers
) as r:
data = await r.json()
avatar = data["avatar_image_url"]
@@ -102,9 +98,7 @@ class TwitchCommunity:
else:
stream_list = streams
for stream in stream_list:
name = "[{}]({})".format(
stream["channel"]["display_name"], stream["channel"]["url"]
)
name = "[{}]({})".format(stream["channel"]["display_name"], stream["channel"]["url"])
embed.add_field(name=stream["channel"]["status"], value=name, inline=False)
embed.color = 0x6441A4
@@ -125,10 +119,11 @@ class TwitchCommunity:
class Stream:
def __init__(self, **kwargs):
self.name = kwargs.pop("name", None)
self.channels = kwargs.pop("channels", [])
#self.already_online = kwargs.pop("already_online", False)
# self.already_online = kwargs.pop("already_online", False)
self._messages_cache = kwargs.pop("_messages_cache", [])
self.type = self.__class__.__name__
@@ -153,6 +148,7 @@ class Stream:
class YoutubeStream(Stream):
def __init__(self, **kwargs):
self.id = kwargs.pop("id", None)
self._token = kwargs.pop("token", None)
@@ -167,7 +163,7 @@ class YoutubeStream(Stream):
"part": "snippet",
"channelId": self.id,
"type": "video",
"eventType": "live"
"eventType": "live",
}
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as r:
@@ -176,11 +172,7 @@ class YoutubeStream(Stream):
raise OfflineStream()
elif "items" in data:
vid_id = data["items"][0]["id"]["videoId"]
params = {
"key": self._token,
"id": vid_id,
"part": "snippet"
}
params = {"key": self._token, "id": vid_id, "part": "snippet"}
async with aiohttp.ClientSession() as session:
async with session.get(YOUTUBE_VIDEOS_ENDPOINT, params=params) as r:
data = await r.json()
@@ -199,17 +191,16 @@ class YoutubeStream(Stream):
return embed
async def fetch_id(self):
params = {
"key": self._token,
"forUsername": self.name,
"part": "id"
}
params = {"key": self._token, "forUsername": self.name, "part": "id"}
async with aiohttp.ClientSession() as session:
async with session.get(YOUTUBE_CHANNELS_ENDPOINT, params=params) as r:
data = await r.json()
if "error" in data and data["error"]["code"] == 400 and\
data["error"]["errors"][0]["reason"] == "keyInvalid":
if (
"error" in data
and data["error"]["code"] == 400
and data["error"]["errors"][0]["reason"] == "keyInvalid"
):
raise InvalidYoutubeCredentials()
elif "items" in data and len(data["items"]) == 0:
raise StreamNotFound()
@@ -222,6 +213,7 @@ class YoutubeStream(Stream):
class TwitchStream(Stream):
def __init__(self, **kwargs):
self.id = kwargs.pop("id", None)
self._token = kwargs.pop("token", None)
@@ -232,19 +224,16 @@ class TwitchStream(Stream):
self.id = await self.fetch_id()
url = TWITCH_STREAMS_ENDPOINT + self.id
header = {
'Client-ID': str(self._token),
'Accept': 'application/vnd.twitchtv.v5+json'
}
header = {"Client-ID": str(self._token), "Accept": "application/vnd.twitchtv.v5+json"}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=header) as r:
data = await r.json(encoding='utf-8')
data = await r.json(encoding="utf-8")
if r.status == 200:
if data["stream"] is None:
#self.already_online = False
# self.already_online = False
raise OfflineStream()
#self.already_online = True
# self.already_online = True
# In case of rename
self.name = data["stream"]["channel"]["name"]
return self.make_embed(data)
@@ -256,10 +245,7 @@ class TwitchStream(Stream):
raise APIError()
async def fetch_id(self):
header = {
'Client-ID': str(self._token),
'Accept': 'application/vnd.twitchtv.v5+json'
}
header = {"Client-ID": str(self._token), "Accept": "application/vnd.twitchtv.v5+json"}
url = TWITCH_ID_ENDPOINT + self.name
async with aiohttp.ClientSession() as session:
@@ -280,8 +266,7 @@ class TwitchStream(Stream):
url = channel["url"]
logo = channel["logo"]
if logo is None:
logo = ("https://static-cdn.jtvnw.net/"
"jtv_user_pictures/xarth/404_user_70x70.png")
logo = ("https://static-cdn.jtvnw.net/" "jtv_user_pictures/xarth/404_user_70x70.png")
status = channel["status"]
if not status:
status = "Untitled broadcast"
@@ -303,21 +288,22 @@ class TwitchStream(Stream):
class HitboxStream(Stream):
async def is_online(self):
url = "https://api.hitbox.tv/media/live/" + self.name
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
#data = await r.json(encoding='utf-8')
# data = await r.json(encoding='utf-8')
data = await r.text()
data = json.loads(data, strict=False)
if "livestream" not in data:
raise StreamNotFound()
elif data["livestream"][0]["media_is_live"] == "0":
#self.already_online = False
# self.already_online = False
raise OfflineStream()
elif data["livestream"][0]["media_is_live"] == "1":
#self.already_online = True
# self.already_online = True
return self.make_embed(data)
raise APIError()
@@ -340,20 +326,21 @@ class HitboxStream(Stream):
class MixerStream(Stream):
async def is_online(self):
url = "https://mixer.com/api/v1/channels/" + self.name
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
#data = await r.json(encoding='utf-8')
data = await r.text(encoding='utf-8')
# data = await r.json(encoding='utf-8')
data = await r.text(encoding="utf-8")
if r.status == 200:
data = json.loads(data, strict=False)
if data["online"] is True:
#self.already_online = True
# self.already_online = True
return self.make_embed(data)
else:
#self.already_online = False
# self.already_online = False
raise OfflineStream()
elif r.status == 404:
raise StreamNotFound()
@@ -361,8 +348,7 @@ class MixerStream(Stream):
raise APIError()
def make_embed(self, data):
default_avatar = ("https://mixer.com/_latest/assets/images/main/"
"avatars/default.jpg")
default_avatar = ("https://mixer.com/_latest/assets/images/main/" "avatars/default.jpg")
user = data["user"]
url = "https://mixer.com/" + data["token"]
embed = discord.Embed(title=data["name"], url=url)
@@ -382,19 +368,20 @@ class MixerStream(Stream):
class PicartoStream(Stream):
async def is_online(self):
url = "https://api.picarto.tv/v1/channel/name/" + self.name
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
data = await r.text(encoding='utf-8')
data = await r.text(encoding="utf-8")
if r.status == 200:
data = json.loads(data)
if data["online"] is True:
#self.already_online = True
# self.already_online = True
return self.make_embed(data)
else:
#self.already_online = False
# self.already_online = False
raise OfflineStream()
elif r.status == 404:
raise StreamNotFound()
@@ -402,8 +389,9 @@ class PicartoStream(Stream):
raise APIError()
def make_embed(self, data):
avatar = rnd("https://picarto.tv/user_data/usrimg/{}/dsdefault.jpg"
"".format(data["name"].lower()))
avatar = rnd(
"https://picarto.tv/user_data/usrimg/{}/dsdefault.jpg" "".format(data["name"].lower())
)
url = "https://picarto.tv/" + data["name"]
thumbnail = data["thumbnails"]["web"]
embed = discord.Embed(title=data["title"], url=url)
@@ -424,6 +412,5 @@ class PicartoStream(Stream):
data["adult"] = ""
embed.color = 0x4C90F3
embed.set_footer(text="{adult}Category: {category} | Tags: {tags}"
"".format(**data))
embed.set_footer(text="{adult}Category: {category} | Tags: {tags}" "".format(**data))
return embed