From f9606e1c9e493194457b0e5afed012841de65486 Mon Sep 17 00:00:00 2001 From: bobloy Date: Thu, 13 Sep 2018 16:18:28 -0400 Subject: [PATCH 1/8] audiotrivia initial commit --- audiotrivia/__init__.py | 5 +++ audiotrivia/audiosession.py | 46 +++++++++++++++++++ audiotrivia/audiotrivia.py | 71 ++++++++++++++++++++++++++++++ audiotrivia/data/lists/csgo.yaml | 5 +++ audiotrivia/data/lists/games.yaml | 4 ++ audiotrivia/data/lists/guitar.yaml | 4 ++ audiotrivia/data/lists/league.yaml | 4 ++ audiotrivia/info.json | 20 +++++++++ 8 files changed, 159 insertions(+) create mode 100644 audiotrivia/__init__.py create mode 100644 audiotrivia/audiosession.py create mode 100644 audiotrivia/audiotrivia.py create mode 100644 audiotrivia/data/lists/csgo.yaml create mode 100644 audiotrivia/data/lists/games.yaml create mode 100644 audiotrivia/data/lists/guitar.yaml create mode 100644 audiotrivia/data/lists/league.yaml create mode 100644 audiotrivia/info.json diff --git a/audiotrivia/__init__.py b/audiotrivia/__init__.py new file mode 100644 index 0000000..327e34e --- /dev/null +++ b/audiotrivia/__init__.py @@ -0,0 +1,5 @@ +from .audiotrivia import AudioTrivia + + +def setup(bot): + bot.add_cog(AudioTrivia(bot)) diff --git a/audiotrivia/audiosession.py b/audiotrivia/audiosession.py new file mode 100644 index 0000000..081c984 --- /dev/null +++ b/audiotrivia/audiosession.py @@ -0,0 +1,46 @@ +"""Module to manage audio trivia sessions.""" +import asyncio + +from redbot.cogs.audio import Audio +from redbot.cogs.trivia import TriviaSession + + +class AudioSession(TriviaSession): + """Class to run a session of audio trivia""" + + def __init__(self, ctx, question_list: dict, settings: dict, audio_cog: Audio): + super().__init__(ctx, question_list, settings) + + self.audio = audio_cog + + async def run(self): + """Run the audio trivia session. + + In order for the trivia session to be stopped correctly, this should + only be called internally by `TriviaSession.start`. + """ + await self._send_startup_msg() + max_score = self.settings["max_score"] + delay = self.settings["delay"] + timeout = self.settings["timeout"] + for question, answers in self._iter_questions(): + async with self.ctx.typing(): + await asyncio.sleep(3) + self.count += 1 + msg = "**Question number {}!**\n\nName this audio!".format(self.count) + await self.ctx.send(msg) + await self.audio.play(self.ctx, question) + + continue_ = await self.wait_for_answer(answers, delay, timeout) + if continue_ is False: + break + if any(score >= max_score for score in self.scores.values()): + await self.end_game() + break + else: + await self.ctx.send("There are no more questions!") + await self.end_game() + + + + diff --git a/audiotrivia/audiotrivia.py b/audiotrivia/audiotrivia.py new file mode 100644 index 0000000..afa82f7 --- /dev/null +++ b/audiotrivia/audiotrivia.py @@ -0,0 +1,71 @@ +from redbot.cogs.trivia import LOG +from redbot.cogs.trivia.trivia import InvalidListError, Trivia +from redbot.core import Config, checks +from redbot.core import commands +from redbot.core.bot import Red +from .audiosession import AudioSession + + +class AudioTrivia(Trivia): + """ + Custom commands + Creates commands used to display text and adjust roles + """ + + def __init__(self, bot: Red): + super().__init__() + self.bot = bot + + @commands.group() + @commands.guild_only() + async def audiotrivia(self, ctx: commands.Context, *categories: str): + """Start trivia session on the specified category. + + You may list multiple categories, in which case the trivia will involve + questions from all of them. + """ + if not categories: + await ctx.send_help() + return + categories = [c.lower() for c in categories] + session = self._get_trivia_session(ctx.channel) + if session is not None: + await ctx.send("There is already an ongoing trivia session in this channel.") + return + trivia_dict = {} + authors = [] + for category in reversed(categories): + # We reverse the categories so that the first list's config takes + # priority over the others. + try: + dict_ = self.get_trivia_list(category) + except FileNotFoundError: + await ctx.send( + "Invalid category `{0}`. See `{1}trivia list`" + " for a list of trivia categories." + "".format(category, ctx.prefix) + ) + except InvalidListError: + await ctx.send( + "There was an error parsing the trivia list for" + " the `{}` category. It may be formatted" + " incorrectly.".format(category) + ) + else: + trivia_dict.update(dict_) + authors.append(trivia_dict.pop("AUTHOR", None)) + continue + return + if not trivia_dict: + await ctx.send( + "The trivia list was parsed successfully, however it appears to be empty!" + ) + return + settings = await self.conf.guild(ctx.guild).all() + config = trivia_dict.pop("CONFIG", None) + if config and settings["allow_override"]: + settings.update(config) + settings["lists"] = dict(zip(categories, reversed(authors))) + session = AudioSession.start(ctx, trivia_dict, settings) + self.trivia_sessions.append(session) + LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id) \ No newline at end of file diff --git a/audiotrivia/data/lists/csgo.yaml b/audiotrivia/data/lists/csgo.yaml new file mode 100644 index 0000000..ab726bb --- /dev/null +++ b/audiotrivia/data/lists/csgo.yaml @@ -0,0 +1,5 @@ +https://www.youtube.com/watch?v=DYWi8qdvWCk: +- AK47 +- AK 47 +https://www.youtube.com/watch?v=DmuK9Wml88E: +- P90 \ No newline at end of file diff --git a/audiotrivia/data/lists/games.yaml b/audiotrivia/data/lists/games.yaml new file mode 100644 index 0000000..eacde4b --- /dev/null +++ b/audiotrivia/data/lists/games.yaml @@ -0,0 +1,4 @@ +https://www.youtube.com/watch?v=FrceWR4XnVU: +- shovel knight +https://www.youtube.com/watch?v=Fn0khIn2wfc: +- super mario world \ No newline at end of file diff --git a/audiotrivia/data/lists/guitar.yaml b/audiotrivia/data/lists/guitar.yaml new file mode 100644 index 0000000..1c0d07e --- /dev/null +++ b/audiotrivia/data/lists/guitar.yaml @@ -0,0 +1,4 @@ +https://www.youtube.com/watch?v=hfyE220BsD0: +- holiday +https://www.youtube.com/watch?v=Hh3U9iPKeXQ: +- sultans of swing \ No newline at end of file diff --git a/audiotrivia/data/lists/league.yaml b/audiotrivia/data/lists/league.yaml new file mode 100644 index 0000000..323aadd --- /dev/null +++ b/audiotrivia/data/lists/league.yaml @@ -0,0 +1,4 @@ +https://www.youtube.com/watch?v=Hi1kUdreiWk: +- Jinx +https://www.youtube.com/watch?v=PNYHFluhOGI: +- Teemo \ No newline at end of file diff --git a/audiotrivia/info.json b/audiotrivia/info.json new file mode 100644 index 0000000..323a69d --- /dev/null +++ b/audiotrivia/info.json @@ -0,0 +1,20 @@ +{ + "author": [ + "Bobloy" + ], + "bot_version": [ + 3, + 0, + 0 + ], + "description": "Start an Audio Trivia game", + "hidden": false, + "install_msg": "Thank you for installing Audio trivia! Get started with `[p]help AudioTrivia`", + "requirements": [], + "short": "Start an Audio Trivia game", + "tags": [ + "fox", + "bobloy", + "games" + ] +} \ No newline at end of file From 952487ef7a456cf517d8a38f06cc46734a8b5ff1 Mon Sep 17 00:00:00 2001 From: bobloy Date: Fri, 14 Sep 2018 08:49:38 -0400 Subject: [PATCH 2/8] Lists --- audiotrivia/audiotrivia.py | 42 ++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/audiotrivia/audiotrivia.py b/audiotrivia/audiotrivia.py index afa82f7..f1cce57 100644 --- a/audiotrivia/audiotrivia.py +++ b/audiotrivia/audiotrivia.py @@ -1,8 +1,14 @@ +import pathlib +from typing import List + from redbot.cogs.trivia import LOG from redbot.cogs.trivia.trivia import InvalidListError, Trivia from redbot.core import Config, checks from redbot.core import commands from redbot.core.bot import Red +from redbot.core.data_manager import cog_data_path +from redbot.core.utils import box + from .audiosession import AudioSession @@ -15,8 +21,9 @@ class AudioTrivia(Trivia): def __init__(self, bot: Red): super().__init__() self.bot = bot + self.audio = None - @commands.group() + @commands.group(invoke_without_command=True) @commands.guild_only() async def audiotrivia(self, ctx: commands.Context, *categories: str): """Start trivia session on the specified category. @@ -24,9 +31,18 @@ class AudioTrivia(Trivia): You may list multiple categories, in which case the trivia will involve questions from all of them. """ - if not categories: + if not categories and ctx.invoked_subcommand is None: await ctx.send_help() return + + if self.audio is None: + self.audio = self.bot.get_cog("Audio") + + if self.audio is None: + await ctx.send("Audio is not loaded. Load it and try again") + return + + categories = [c.lower() for c in categories] session = self._get_trivia_session(ctx.channel) if session is not None: @@ -41,7 +57,7 @@ class AudioTrivia(Trivia): dict_ = self.get_trivia_list(category) except FileNotFoundError: await ctx.send( - "Invalid category `{0}`. See `{1}trivia list`" + "Invalid category `{0}`. See `{1}audiotrivia list`" " for a list of trivia categories." "".format(category, ctx.prefix) ) @@ -68,4 +84,22 @@ class AudioTrivia(Trivia): settings["lists"] = dict(zip(categories, reversed(authors))) session = AudioSession.start(ctx, trivia_dict, settings) self.trivia_sessions.append(session) - LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id) \ No newline at end of file + LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id) + + @audiotrivia.command(name="list") + @commands.guild_only() + async def audiotrivia_list(self, ctx: commands.Context): + """List available trivia categories.""" + lists = set(p.stem for p in self._audio_lists()) + + msg = box("**Available trivia lists**\n\n{}".format(", ".join(sorted(lists)))) + if len(msg) > 1000: + await ctx.author.send(msg) + return + await ctx.send(msg) + + def _audio_lists(self) -> List[pathlib.Path]: + print(cog_data_path(self)) + personal_lists = [p.resolve() for p in cog_data_path(self).glob("*.yaml")] + + return personal_lists \ No newline at end of file From ed94b7e1cd570345933e14cbee26092d64408a2f Mon Sep 17 00:00:00 2001 From: bobloy Date: Fri, 14 Sep 2018 11:13:01 -0400 Subject: [PATCH 3/8] Better starting --- audiotrivia/audiosession.py | 15 ++++++++----- audiotrivia/audiotrivia.py | 43 +++++++++++++++++++++++++++++++------ 2 files changed, 47 insertions(+), 11 deletions(-) diff --git a/audiotrivia/audiosession.py b/audiotrivia/audiosession.py index 081c984..946965e 100644 --- a/audiotrivia/audiosession.py +++ b/audiotrivia/audiosession.py @@ -13,6 +13,13 @@ class AudioSession(TriviaSession): self.audio = audio_cog + @classmethod + def start(cls, ctx, question_list, settings, audio_cog: Audio = None): + session = cls(ctx, question_list, settings, audio_cog) + loop = ctx.bot.loop + session._task = loop.create_task(session.run()) + return session + async def run(self): """Run the audio trivia session. @@ -29,7 +36,9 @@ class AudioSession(TriviaSession): self.count += 1 msg = "**Question number {}!**\n\nName this audio!".format(self.count) await self.ctx.send(msg) - await self.audio.play(self.ctx, question) + print(question) + + await self.audio.play(ctx=self.ctx, query=question) continue_ = await self.wait_for_answer(answers, delay, timeout) if continue_ is False: @@ -40,7 +49,3 @@ class AudioSession(TriviaSession): else: await self.ctx.send("There are no more questions!") await self.end_game() - - - - diff --git a/audiotrivia/audiotrivia.py b/audiotrivia/audiotrivia.py index f1cce57..9b861e8 100644 --- a/audiotrivia/audiotrivia.py +++ b/audiotrivia/audiotrivia.py @@ -1,9 +1,9 @@ import pathlib from typing import List +import yaml from redbot.cogs.trivia import LOG from redbot.cogs.trivia.trivia import InvalidListError, Trivia -from redbot.core import Config, checks from redbot.core import commands from redbot.core.bot import Red from redbot.core.data_manager import cog_data_path @@ -42,7 +42,6 @@ class AudioTrivia(Trivia): await ctx.send("Audio is not loaded. Load it and try again") return - categories = [c.lower() for c in categories] session = self._get_trivia_session(ctx.channel) if session is not None: @@ -54,7 +53,7 @@ class AudioTrivia(Trivia): # We reverse the categories so that the first list's config takes # priority over the others. try: - dict_ = self.get_trivia_list(category) + dict_ = self.get_audio_list(category) except FileNotFoundError: await ctx.send( "Invalid category `{0}`. See `{1}audiotrivia list`" @@ -82,7 +81,7 @@ class AudioTrivia(Trivia): if config and settings["allow_override"]: settings.update(config) settings["lists"] = dict(zip(categories, reversed(authors))) - session = AudioSession.start(ctx, trivia_dict, settings) + session = AudioSession.start(ctx, trivia_dict, settings, self.audio) self.trivia_sessions.append(session) LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id) @@ -98,8 +97,40 @@ class AudioTrivia(Trivia): return await ctx.send(msg) + def get_audio_list(self, category: str) -> dict: + """Get the audiotrivia list corresponding to the given category. + + Parameters + ---------- + category : str + The desired category. Case sensitive. + + Returns + ------- + `dict` + A dict mapping questions (`str`) to answers (`list` of `str`). + + """ + try: + path = next(p for p in self._audio_lists() if p.stem == category) + except StopIteration: + raise FileNotFoundError("Could not find the `{}` category.".format(category)) + + with path.open(encoding="utf-8") as file: + try: + dict_ = yaml.load(file) + except yaml.error.YAMLError as exc: + raise InvalidListError("YAML parsing failed.") from exc + else: + return dict_ + def _audio_lists(self) -> List[pathlib.Path]: - print(cog_data_path(self)) personal_lists = [p.resolve() for p in cog_data_path(self).glob("*.yaml")] - return personal_lists \ No newline at end of file + return personal_lists + get_core_lists() + + +def get_core_lists() -> List[pathlib.Path]: + """Return a list of paths for all trivia lists packaged with the bot.""" + core_lists_path = pathlib.Path(__file__).parent.resolve() / "data/lists" + return list(core_lists_path.glob("*.yaml")) From 20e2d6026f5258903c505d6d54bf80930ddf99b6 Mon Sep 17 00:00:00 2001 From: bobloy Date: Fri, 14 Sep 2018 17:02:20 -0400 Subject: [PATCH 4/8] actual starting --- audiotrivia/audiosession.py | 9 ++++++++- audiotrivia/audiotrivia.py | 8 ++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/audiotrivia/audiosession.py b/audiotrivia/audiosession.py index 946965e..73f3e45 100644 --- a/audiotrivia/audiosession.py +++ b/audiotrivia/audiosession.py @@ -38,7 +38,10 @@ class AudioSession(TriviaSession): await self.ctx.send(msg) print(question) - await self.audio.play(ctx=self.ctx, query=question) + # await self.ctx.invoke(self.audio.play(ctx=self.ctx, query=question)) + await self.ctx.invoke(self.audio.play, query=question) + + print("after audio.play") continue_ = await self.wait_for_answer(answers, delay, timeout) if continue_ is False: @@ -49,3 +52,7 @@ class AudioSession(TriviaSession): else: await self.ctx.send("There are no more questions!") await self.end_game() + + async def end_game(self): + await super().end_game() + await self.ctx.invoke(self.audio.disconnect) \ No newline at end of file diff --git a/audiotrivia/audiotrivia.py b/audiotrivia/audiotrivia.py index 9b861e8..250f15a 100644 --- a/audiotrivia/audiotrivia.py +++ b/audiotrivia/audiotrivia.py @@ -2,6 +2,7 @@ import pathlib from typing import List import yaml +from redbot.cogs.audio import Audio from redbot.cogs.trivia import LOG from redbot.cogs.trivia.trivia import InvalidListError, Trivia from redbot.core import commands @@ -23,6 +24,13 @@ class AudioTrivia(Trivia): self.bot = bot self.audio = None + # @commands.command() + # @commands.is_owner() + # async def testit(self, ctx: commands.Context): + # self.audio: Audio = self.bot.get_cog("Audio") + # await ctx.invoke(self.audio.play, query="https://www.youtube.com/watch?v=FrceWR4XnVU") + # print("done") + @commands.group(invoke_without_command=True) @commands.guild_only() async def audiotrivia(self, ctx: commands.Context, *categories: str): From d876c0a6c3d66bff7189195a0c0b9135c8d4b1f9 Mon Sep 17 00:00:00 2001 From: bobloy Date: Mon, 17 Sep 2018 16:01:40 -0400 Subject: [PATCH 5/8] Actually works now, cool. --- audiotrivia/audiosession.py | 23 +++++++++++++--------- audiotrivia/audiotrivia.py | 39 ++++++++++++++++++++++++++++++------- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/audiotrivia/audiosession.py b/audiotrivia/audiosession.py index 73f3e45..20ad3ae 100644 --- a/audiotrivia/audiosession.py +++ b/audiotrivia/audiosession.py @@ -1,21 +1,21 @@ """Module to manage audio trivia sessions.""" import asyncio -from redbot.cogs.audio import Audio +import lavalink from redbot.cogs.trivia import TriviaSession class AudioSession(TriviaSession): """Class to run a session of audio trivia""" - def __init__(self, ctx, question_list: dict, settings: dict, audio_cog: Audio): + def __init__(self, ctx, question_list: dict, settings: dict, player: lavalink.Player): super().__init__(ctx, question_list, settings) - self.audio = audio_cog + self.player = player @classmethod - def start(cls, ctx, question_list, settings, audio_cog: Audio = None): - session = cls(ctx, question_list, settings, audio_cog) + def start(cls, ctx, question_list, settings, player: lavalink.Player = None): + session = cls(ctx, question_list, settings, player) loop = ctx.bot.loop session._task = loop.create_task(session.run()) return session @@ -36,12 +36,17 @@ class AudioSession(TriviaSession): self.count += 1 msg = "**Question number {}!**\n\nName this audio!".format(self.count) await self.ctx.send(msg) - print(question) + # print("Audio question: {}".format(question)) # await self.ctx.invoke(self.audio.play(ctx=self.ctx, query=question)) - await self.ctx.invoke(self.audio.play, query=question) + # ctx_copy = copy(self.ctx) - print("after audio.play") + # await self.ctx.invoke(self.player.play, query=question) + query = question.strip("<>") + tracks = await self.player.get_tracks(query) + self.player.add(self.ctx.author, tracks[0]) + if not self.player.current: + await self.player.play() continue_ = await self.wait_for_answer(answers, delay, timeout) if continue_ is False: @@ -55,4 +60,4 @@ class AudioSession(TriviaSession): async def end_game(self): await super().end_game() - await self.ctx.invoke(self.audio.disconnect) \ No newline at end of file + await self.ctx.invoke(self.player.disconnect) diff --git a/audiotrivia/audiotrivia.py b/audiotrivia/audiotrivia.py index 250f15a..c170efa 100644 --- a/audiotrivia/audiotrivia.py +++ b/audiotrivia/audiotrivia.py @@ -1,6 +1,8 @@ +import datetime import pathlib from typing import List +import lavalink import yaml from redbot.cogs.audio import Audio from redbot.cogs.trivia import LOG @@ -24,12 +26,12 @@ class AudioTrivia(Trivia): self.bot = bot self.audio = None - # @commands.command() - # @commands.is_owner() - # async def testit(self, ctx: commands.Context): - # self.audio: Audio = self.bot.get_cog("Audio") - # await ctx.invoke(self.audio.play, query="https://www.youtube.com/watch?v=FrceWR4XnVU") - # print("done") + @commands.command() + @commands.is_owner() + async def testit(self, ctx: commands.Context): + self.audio: Audio = self.bot.get_cog("Audio") + await ctx.invoke(self.audio.play, query="https://www.youtube.com/watch?v=FrceWR4XnVU") + print("done") @commands.group(invoke_without_command=True) @commands.guild_only() @@ -55,6 +57,29 @@ class AudioTrivia(Trivia): if session is not None: await ctx.send("There is already an ongoing trivia session in this channel.") return + + if not Audio._player_check(ctx): + try: + if not ctx.author.voice.channel.permissions_for(ctx.me).connect or Audio._userlimit( + ctx.author.voice.channel + ): + return await ctx.send("I don't have permission to connect to your channel." + ) + await lavalink.connect(ctx.author.voice.channel) + lavaplayer = lavalink.get_player(ctx.guild.id) + lavaplayer.store("connect", datetime.datetime.utcnow()) + except AttributeError: + return await ctx.send("Connect to a voice channel first.") + + lavaplayer = lavalink.get_player(ctx.guild.id) + lavaplayer.store("channel", ctx.channel.id) # What's this for? I dunno + lavaplayer.store("guild", ctx.guild.id) + + if ( + not ctx.author.voice or ctx.author.voice.channel != lavaplayer.channel + ): + return await ctx.send("You must be in the voice channel to use the audiotrivia command.") + trivia_dict = {} authors = [] for category in reversed(categories): @@ -89,7 +114,7 @@ class AudioTrivia(Trivia): if config and settings["allow_override"]: settings.update(config) settings["lists"] = dict(zip(categories, reversed(authors))) - session = AudioSession.start(ctx, trivia_dict, settings, self.audio) + session = AudioSession.start(ctx=ctx, question_list=trivia_dict, settings=settings, player=lavaplayer) self.trivia_sessions.append(session) LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id) From 25f0766982e1d53966e31eb88c0221f036ee227a Mon Sep 17 00:00:00 2001 From: bobloy Date: Mon, 17 Sep 2018 17:03:17 -0400 Subject: [PATCH 6/8] small bug and start of config --- audiotrivia/audiosession.py | 2 +- audiotrivia/audiotrivia.py | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/audiotrivia/audiosession.py b/audiotrivia/audiosession.py index 20ad3ae..1d28b7a 100644 --- a/audiotrivia/audiosession.py +++ b/audiotrivia/audiosession.py @@ -60,4 +60,4 @@ class AudioSession(TriviaSession): async def end_game(self): await super().end_game() - await self.ctx.invoke(self.player.disconnect) + await self.player.disconnect() diff --git a/audiotrivia/audiotrivia.py b/audiotrivia/audiotrivia.py index c170efa..0649d76 100644 --- a/audiotrivia/audiotrivia.py +++ b/audiotrivia/audiotrivia.py @@ -7,7 +7,7 @@ import yaml from redbot.cogs.audio import Audio from redbot.cogs.trivia import LOG from redbot.cogs.trivia.trivia import InvalidListError, Trivia -from redbot.core import commands +from redbot.core import commands, Config from redbot.core.bot import Red from redbot.core.data_manager import cog_data_path from redbot.core.utils import box @@ -25,6 +25,12 @@ class AudioTrivia(Trivia): super().__init__() self.bot = bot self.audio = None + self.audioconf = Config.get_conf(self, identifier=651171001051118411410511810597, force_registration=True) + + self.audioconf.register_guild( + delay=30.0, + repeat=True + ) # Todo: Repeat songs shorter than the delay (csgo sound effects for example) @commands.command() @commands.is_owner() From 86f1c4cee69e567050a9c007cc72d1718f486a37 Mon Sep 17 00:00:00 2001 From: bobloy Date: Tue, 18 Sep 2018 10:15:08 -0400 Subject: [PATCH 7/8] Working settings --- audiotrivia/audiosession.py | 13 +++++++++- audiotrivia/audiotrivia.py | 50 +++++++++++++++++++++++++++++-------- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/audiotrivia/audiosession.py b/audiotrivia/audiosession.py index 1d28b7a..780d4b9 100644 --- a/audiotrivia/audiosession.py +++ b/audiotrivia/audiosession.py @@ -34,6 +34,8 @@ class AudioSession(TriviaSession): async with self.ctx.typing(): await asyncio.sleep(3) self.count += 1 + await self.player.stop() + msg = "**Question number {}!**\n\nName this audio!".format(self.count) await self.ctx.send(msg) # print("Audio question: {}".format(question)) @@ -44,7 +46,16 @@ class AudioSession(TriviaSession): # await self.ctx.invoke(self.player.play, query=question) query = question.strip("<>") tracks = await self.player.get_tracks(query) - self.player.add(self.ctx.author, tracks[0]) + seconds = tracks[0].length / 1000 + + if self.settings["repeat"] and seconds < delay: + tot_length = seconds + 0 + while tot_length < delay: + self.player.add(self.ctx.author, tracks[0]) + tot_length += seconds + else: + self.player.add(self.ctx.author, tracks[0]) + if not self.player.current: await self.player.play() diff --git a/audiotrivia/audiotrivia.py b/audiotrivia/audiotrivia.py index 0649d76..6328e37 100644 --- a/audiotrivia/audiotrivia.py +++ b/audiotrivia/audiotrivia.py @@ -7,10 +7,10 @@ import yaml from redbot.cogs.audio import Audio from redbot.cogs.trivia import LOG from redbot.cogs.trivia.trivia import InvalidListError, Trivia -from redbot.core import commands, Config +from redbot.core import commands, Config, checks from redbot.core.bot import Red from redbot.core.data_manager import cog_data_path -from redbot.core.utils import box +from redbot.core.utils.chat_formatting import box from .audiosession import AudioSession @@ -30,14 +30,40 @@ class AudioTrivia(Trivia): self.audioconf.register_guild( delay=30.0, repeat=True - ) # Todo: Repeat songs shorter than the delay (csgo sound effects for example) + ) - @commands.command() - @commands.is_owner() - async def testit(self, ctx: commands.Context): - self.audio: Audio = self.bot.get_cog("Audio") - await ctx.invoke(self.audio.play, query="https://www.youtube.com/watch?v=FrceWR4XnVU") - print("done") + @commands.group() + @commands.guild_only() + @checks.mod_or_permissions(administrator=True) + async def atriviaset(self, ctx: commands.Context): + """Manage Audio Trivia settings.""" + audioset = self.audioconf.guild(ctx.guild) + settings_dict = await audioset.all() + msg = box( + "**Audio settings**\n" + "Answer time limit: {delay} seconds\n" + "Repeat Short Audio: {repeat}" + "".format(**settings_dict), + lang="py", + ) + await ctx.send(msg) + + @atriviaset.command(name="delay") + async def atriviaset_delay(self, ctx: commands.Context, seconds: float): + """Set the maximum seconds permitted to answer a question.""" + if seconds < 4.0: + await ctx.send("Must be at least 4 seconds.") + return + settings = self.audioconf.guild(ctx.guild) + await settings.delay.set(seconds) + await ctx.send("Done. Maximum seconds to answer set to {}.".format(seconds)) + + @atriviaset.command(name="repeat") + async def atriviaset_repeat(self, ctx: commands.Context, true_or_false: bool): + """Set whether or not short audio will be repeated""" + settings = self.audioconf.guild(ctx.guild) + await settings.repeat.set(true_or_false) + await ctx.send("Done. Repeating short audio is now set to {}.".format(true_or_false)) @commands.group(invoke_without_command=True) @commands.guild_only() @@ -116,11 +142,15 @@ class AudioTrivia(Trivia): ) return settings = await self.conf.guild(ctx.guild).all() + audiosettings = await self.audioconf.guild(ctx.guild).all() config = trivia_dict.pop("CONFIG", None) if config and settings["allow_override"]: settings.update(config) settings["lists"] = dict(zip(categories, reversed(authors))) - session = AudioSession.start(ctx=ctx, question_list=trivia_dict, settings=settings, player=lavaplayer) + + # Delay in audiosettings overwrites delay in settings + combined_settings = {**settings, **audiosettings} + session = AudioSession.start(ctx=ctx, question_list=trivia_dict, settings=combined_settings, player=lavaplayer) self.trivia_sessions.append(session) LOG.debug("New audio trivia session; #%s in %d", ctx.channel, ctx.guild.id) From 5b43cfa16a4102f07450fee4e4258cfea598b4a9 Mon Sep 17 00:00:00 2001 From: bobloy Date: Tue, 18 Sep 2018 10:40:28 -0400 Subject: [PATCH 8/8] Add to ReadMe --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ce3bc62..098cd6d 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ Cog Function | Name | Status | Description (Click to see full status) | --- | --- | --- | | announcedaily | **Alpha** |
Send daily announcements to all servers at a specified timesCommissioned release, so suggestions will not be accepted
| +| audiotrivia | **Alpha** |
Guess the audio using the core trivia cogReplaces the core Trivia cog. Needs help adding audio trivia lists, please submit a PR to contribute
| | ccrole | **Beta** |
Create custom commands that also assign rolesMay have some bugs, please create an issue if you find any
| | chatter | **Alpha** |
Chat-bot trained to talk like your guildMissing some key features, but currently functional
| | coglint | **Alpha** |
Error check code in python syntax posted to discordWorks, but probably needs more turning to work for cogs
|