From db1f1ded12b4ee7857404710969ca976332cb2f0 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 19 Apr 2019 02:29:39 +0200 Subject: [PATCH] Whee! More moving around! --- royalgames.py | 22 +++++++++++----------- royalnet/bots/__init__.py | 4 ++-- royalnet/bots/discord.py | 16 +++++++--------- royalnet/bots/generic.py | 20 +++++++++++--------- 4 files changed, 31 insertions(+), 31 deletions(-) diff --git a/royalgames.py b/royalgames.py index bb7293aa..a0596b8c 100644 --- a/royalgames.py +++ b/royalgames.py @@ -1,11 +1,11 @@ import os import asyncio import logging -from royalnet.bots import TelegramBot, DiscordBot +from royalnet.bots import DiscordBot, DiscordConfig from royalnet.commands import * from royalnet.commands.debug_create import DebugCreateCommand from royalnet.commands.error_handler import ErrorHandlerCommand -from royalnet.network import RoyalnetServer +from royalnet.network import RoyalnetServer, RoyalnetConfig from royalnet.database import DatabaseConfig from royalnet.database.tables import Royal, Telegram, Discord @@ -13,21 +13,21 @@ loop = asyncio.get_event_loop() log = logging.root log.addHandler(logging.StreamHandler()) -logging.getLogger("royalnet.audio.royalaudiofile").setLevel(logging.DEBUG) -logging.getLogger("royalnet.bots.discord").setLevel(logging.DEBUG) +logging.getLogger("royalnet.bots.generic").setLevel(logging.DEBUG) commands = [PingCommand, ShipCommand, SmecdsCommand, ColorCommand, CiaoruoziCommand, DebugCreateCommand, SyncCommand, AuthorCommand, DiarioCommand, RageCommand, DateparserCommand, ReminderCommand, KvactiveCommand, KvCommand, KvrollCommand, VideoinfoCommand, SummonCommand, PlayCommand] -master = RoyalnetServer("localhost", 2468, "sas") -tg_db_cfg = DatabaseConfig(os.environ["DB_PATH"], Royal, Telegram, "tg_id") -tg_bot = TelegramBot(os.environ["TG_AK"], "ws://localhost:2468", "sas", commands, NullCommand, ErrorHandlerCommand, tg_db_cfg) -ds_db_cfg = DatabaseConfig(os.environ["DB_PATH"], Royal, Discord, "discord_id") -ds_bot = DiscordBot(os.environ["DS_AK"], "ws://localhost:2468", "sas", commands, NullCommand, ErrorHandlerCommand, ds_db_cfg) +address, port = "localhost", 1234 + +master = RoyalnetServer(address, port, "sas") +ds_bot = DiscordBot(discord_config=DiscordConfig(os.environ["DS_AK"]), + royalnet_config=RoyalnetConfig(f"ws://{address}:{port}", "sas"), + database_config=DatabaseConfig(os.environ["DB_PATH"], Royal, Discord, "discord_id"), + commands=commands, + error_command=ErrorHandlerCommand) loop.run_until_complete(master.run()) -# Dirty hack, remove me asap -loop.create_task(tg_bot.run()) loop.create_task(ds_bot.run()) print("Starting loop...") loop.run_forever() diff --git a/royalnet/bots/__init__.py b/royalnet/bots/__init__.py index 5977bc16..d229f4c2 100644 --- a/royalnet/bots/__init__.py +++ b/royalnet/bots/__init__.py @@ -1,4 +1,4 @@ from .telegram import TelegramBot -from .discord import DiscordBot +from .discord import DiscordBot, DiscordConfig -__all__ = ["TelegramBot", "DiscordBot"] +__all__ = ["TelegramBot", "DiscordBot", "DiscordConfig"] diff --git a/royalnet/bots/discord.py b/royalnet/bots/discord.py index 8f600520..958a082e 100644 --- a/royalnet/bots/discord.py +++ b/royalnet/bots/discord.py @@ -2,14 +2,13 @@ import discord import asyncio import typing import logging as _logging -import sys from .generic import GenericBot from ..commands import NullCommand from ..utils import asyncify, Call, Command from ..error import UnregisteredError, NoneFoundError, TooManyFoundError, InvalidConfigError -from ..network import RoyalnetLink, Message, RequestSuccessful, RequestError, RoyalnetConfig -from ..database import Alchemy, relationshiplinkchain, DatabaseConfig -from ..audio import RoyalPCMFile, PlayMode, Playlist +from ..network import Message, RequestError, RoyalnetConfig +from ..database import DatabaseConfig +from ..audio import PlayMode, Playlist loop = asyncio.get_event_loop() log = _logging.getLogger(__name__) @@ -25,13 +24,15 @@ class DiscordConfig: class DiscordBot(GenericBot): + interface_name = "discord" + def _init_voice(self): self.music_data: typing.Dict[discord.Guild, PlayMode] = {} def _call_factory(self) -> typing.Type[Call]: # noinspection PyMethodParameters class DiscordCall(Call): - interface_name = "discord" + interface_name = self.interface_name interface_obj = self interface_prefix = "!" @@ -172,14 +173,13 @@ class DiscordBot(GenericBot): error_command=error_command) self._discord_config = discord_config self._init_bot() + self._init_voice() async def run(self): await self.bot.login(self._discord_config.token) await self.bot.connect() # TODO: how to stop? - - # class DiscordBot: # async def add_to_music_data(self, url: str, guild: discord.Guild): # """Add a file to the corresponding music_data object.""" @@ -212,5 +212,3 @@ class DiscordBot(GenericBot): # log.debug(f"Starting playback of {next_source}") # voice_client.play(next_source, after=advance) # - -# \ No newline at end of file diff --git a/royalnet/bots/generic.py b/royalnet/bots/generic.py index f9dd8592..e38bdd00 100644 --- a/royalnet/bots/generic.py +++ b/royalnet/bots/generic.py @@ -13,6 +13,8 @@ log = logging.getLogger(__name__) class GenericBot: """A generic bot class, to be used as base for the other more specific classes, such as TelegramBot and DiscordBot.""" + interface_name = NotImplemented + def _init_commands(self, commands: typing.List[typing.Type[Command]], missing_command: typing.Type[Command], @@ -39,7 +41,7 @@ class GenericBot: log.debug(f"Running RoyalnetLink {self.network}") loop.create_task(self.network.run()) - def _network_handler(self, message: Message) -> Message: + async def _network_handler(self, message: Message) -> Message: """Handle a single Message received from the RoyalnetLink""" log.debug(f"Received {message} from the RoyalnetLink") try: @@ -49,7 +51,7 @@ class GenericBot: return RequestError(KeyError("Missing network_handler")) try: log.debug(f"Using {network_handler} as handler for {message}") - return await network_handler.discord(message) + return await getattr(network_handler, self.interface_name)(message) except Exception as exc: log.debug(f"Exception {exc} in {network_handler}") return RequestError(exc) @@ -75,6 +77,13 @@ class GenericBot: commands: typing.List[typing.Type[Command]] = None, missing_command: typing.Type[Command] = NullCommand, error_command: typing.Type[Command] = NullCommand): + if database_config is None: + self.alchemy = None + self.master_table = None + self.identity_table = None + self.identity_column = None + else: + self._init_database(commands=commands, database_config=database_config) if commands is None: commands = [] self._init_commands(commands, missing_command=missing_command, error_command=error_command) @@ -83,13 +92,6 @@ class GenericBot: self.network = None else: self._init_royalnet(royalnet_config=royalnet_config) - if database_config is None: - self.alchemy = None - self.master_table = None - self.identity_table = None - self.identity_column = None - else: - self._init_database(commands=commands, database_config=database_config) async def call(self, command_name: str, channel, parameters: typing.List[str] = None, **kwargs): """Call a command by its string, or missing_command if it doesn't exists, or error_command if an exception is raised during the execution."""