1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-27 13:34:28 +00:00

Merge branch 'master' into yoshi-refactor

This commit is contained in:
Steffo 2019-10-19 12:56:35 +02:00 committed by GitHub
commit f42e9d4180
Signed by: github
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 37 additions and 24 deletions

View file

@ -1,6 +1,7 @@
import discord import discord
import sentry_sdk import sentry_sdk
import logging as _logging import logging as _logging
import asyncio
from .generic import GenericBot from .generic import GenericBot
from ..utils import * from ..utils import *
from ..error import * from ..error import *
@ -14,6 +15,12 @@ if not discord.opus.is_loaded():
log.error("Opus is not loaded. Weird behaviour might emerge.") log.error("Opus is not loaded. Weird behaviour might emerge.")
class MusicData:
def __init__(self):
self.playmode: playmodes.PlayMode = playmodes.Playlist()
self.voice_client: typing.Optional[discord.VoiceClient] = None
class DiscordBot(GenericBot): class DiscordBot(GenericBot):
"""A bot that connects to `Discord <https://discordapp.com/>`_.""" """A bot that connects to `Discord <https://discordapp.com/>`_."""
interface_name = "discord" interface_name = "discord"
@ -21,7 +28,7 @@ class DiscordBot(GenericBot):
def _init_voice(self): def _init_voice(self):
"""Initialize the variables needed for the connection to voice chat.""" """Initialize the variables needed for the connection to voice chat."""
log.debug(f"Creating music_data dict") log.debug(f"Creating music_data dict")
self.music_data: typing.Dict[discord.Guild, playmodes.PlayMode] = {} self.music_data: typing.Dict[discord.Guild, MusicData] = {}
def _interface_factory(self) -> typing.Type[CommandInterface]: def _interface_factory(self) -> typing.Type[CommandInterface]:
# noinspection PyPep8Naming # noinspection PyPep8Naming
@ -67,24 +74,30 @@ class DiscordBot(GenericBot):
# noinspection PyMethodParameters # noinspection PyMethodParameters
class DiscordClient(discord.Client): class DiscordClient(discord.Client):
async def vc_connect_or_move(cli, channel: discord.VoiceChannel): async def vc_connect_or_move(cli, channel: discord.VoiceChannel):
# Connect to voice chat music_data = self.music_data.get(channel.guild)
try: if music_data is None:
# Create a MusicData object
music_data = MusicData()
self.music_data[channel.guild] = music_data
# Connect to voice
log.debug(f"Connecting to Voice in {channel}") log.debug(f"Connecting to Voice in {channel}")
await channel.connect() try:
log.debug(f"Connected to Voice in {channel}") music_data.voice_client = await channel.connect(reconnect=False, timeout=10)
except discord.errors.ClientException: except Exception:
# Move to the selected channel, instead of connecting log.warning(f"Failed to connect to Voice in {channel}")
# noinspection PyUnusedLocal del self.music_data[channel.guild]
for voice_client in cli.voice_clients: raise
voice_client: discord.VoiceClient else:
if voice_client.guild != channel.guild: log.debug(f"Connected to Voice in {channel}")
continue else:
await voice_client.move_to(channel) if music_data.voice_client is None:
log.debug(f"Moved {voice_client} to {channel}") # TODO: change exception type
# Create a music_data entry, if it doesn't exist; default is a Playlist raise Exception("Another connection attempt is already in progress.")
if not self.music_data.get(channel.guild): # Try to move to a different channel
log.debug(f"Creating music_data for {channel.guild}") voice_client = music_data.voice_client
self.music_data[channel.guild] = playmodes.Playlist() log.debug(f"Moving {voice_client} to {channel}")
await voice_client.move_to(channel)
log.debug(f"Moved {voice_client} to {channel}")
async def on_message(cli, message: discord.Message): async def on_message(cli, message: discord.Message):
self.loop.create_task(cli._handle_message(message)) self.loop.create_task(cli._handle_message(message))
@ -209,15 +222,15 @@ class DiscordBot(GenericBot):
for dfile in dfiles: for dfile in dfiles:
log.debug(f"Adding {dfile} to music_data") log.debug(f"Adding {dfile} to music_data")
await asyncify(dfile.ready_up) await asyncify(dfile.ready_up)
guild_music_data.add(dfile) guild_music_data.playmode.add(dfile)
if guild_music_data.now_playing is None: if guild_music_data.playmode.now_playing is None:
await self.advance_music_data(guild) await self.advance_music_data(guild)
async def advance_music_data(self, guild: discord.Guild): async def advance_music_data(self, guild: discord.Guild):
"""Try to play the next song, while it exists. Otherwise, just return.""" """Try to play the next song, while it exists. Otherwise, just return."""
guild_music_data = self.music_data[guild] guild_music_data = self.music_data[guild]
voice_client: discord.VoiceClient = self.client.find_voice_client_by_guild(guild) voice_client: discord.VoiceClient = self.client.find_voice_client_by_guild(guild)
next_source: discord.AudioSource = await guild_music_data.next() next_source: discord.AudioSource = await guild_music_data.playmode.next()
await self.update_activity_with_source_title() await self.update_activity_with_source_title()
if next_source is None: if next_source is None:
log.debug(f"Ending playback chain") log.debug(f"Ending playback chain")
@ -242,7 +255,7 @@ class DiscordBot(GenericBot):
log.debug(f"Updating current Activity: setting to None, as multiple guilds are using the bot") log.debug(f"Updating current Activity: setting to None, as multiple guilds are using the bot")
await self.client.change_presence(status=discord.Status.online) await self.client.change_presence(status=discord.Status.online)
return return
play_mode: playmodes.PlayMode = self.music_data[list(self.music_data)[0]] play_mode: playmodes.PlayMode = self.music_data[list(self.music_data)[0]].playmode
now_playing = play_mode.now_playing now_playing = play_mode.now_playing
if now_playing is None: if now_playing is None:
# No songs are playing now # No songs are playing now

View file

@ -196,7 +196,7 @@ class GenericBot:
def run_blocking(self, verbose=False): def run_blocking(self, verbose=False):
if verbose: if verbose:
core_logger = logging.getLogger("royalnet") core_logger = logging.root
core_logger.setLevel(logging.DEBUG) core_logger.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler() stream_handler = logging.StreamHandler()
stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{") stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")