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

do some stuff

This commit is contained in:
Steffo 2019-04-19 00:01:28 +02:00
parent 03b3d52f0e
commit f4fc7dd971
10 changed files with 104 additions and 43 deletions

View file

@ -20,11 +20,11 @@ commands = [PingCommand, ShipCommand, SmecdsCommand, ColorCommand, CiaoruoziComm
AuthorCommand, DiarioCommand, RageCommand, DateparserCommand, ReminderCommand, KvactiveCommand, KvCommand, AuthorCommand, DiarioCommand, RageCommand, DateparserCommand, ReminderCommand, KvactiveCommand, KvCommand,
KvrollCommand, VideoinfoCommand, SummonCommand, PlayCommand] KvrollCommand, VideoinfoCommand, SummonCommand, PlayCommand]
master = RoyalnetServer("localhost", 1234, "sas") master = RoyalnetServer("localhost", 2468, "sas")
tg_db_cfg = DatabaseConfig(os.environ["DB_PATH"], Royal, Telegram, "tg_id") tg_db_cfg = DatabaseConfig(os.environ["DB_PATH"], Royal, Telegram, "tg_id")
tg_bot = TelegramBot(os.environ["TG_AK"], "ws://localhost:1234", "sas", commands, NullCommand, ErrorHandlerCommand, tg_db_cfg) 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_db_cfg = DatabaseConfig(os.environ["DB_PATH"], Royal, Discord, "discord_id")
ds_bot = DiscordBot(os.environ["DS_AK"], "ws://localhost:1234", "sas", commands, NullCommand, ErrorHandlerCommand, ds_db_cfg) ds_bot = DiscordBot(os.environ["DS_AK"], "ws://localhost:2468", "sas", commands, NullCommand, ErrorHandlerCommand, ds_db_cfg)
loop.run_until_complete(master.run()) loop.run_until_complete(master.run())
# Dirty hack, remove me asap # Dirty hack, remove me asap
loop.create_task(tg_bot.run()) loop.create_task(tg_bot.run())

View file

@ -28,18 +28,6 @@ class DiscordBot:
error_command: typing.Type[Command] = NullCommand, error_command: typing.Type[Command] = NullCommand,
database_config: typing.Optional[DatabaseConfig] = None): database_config: typing.Optional[DatabaseConfig] = None):
self.token = token self.token = token
# Generate commands
self.missing_command = missing_command
self.error_command = error_command
self.commands = {}
required_tables = set()
for command in commands:
self.commands[f"!{command.command_name}"] = command
required_tables = required_tables.union(command.require_alchemy_tables)
# Generate network handlers
self.network_handlers: typing.Dict[typing.Type[Message], typing.Type[NetworkHandler]] = {}
for command in commands:
self.network_handlers = {**self.network_handlers, **command.network_handler_dict()}
# Generate the Alchemy database # Generate the Alchemy database
if database_config: if database_config:
self.alchemy = Alchemy(database_config.database_uri, required_tables) self.alchemy = Alchemy(database_config.database_uri, required_tables)
@ -49,16 +37,12 @@ class DiscordBot:
self.identity_chain = relationshiplinkchain(self.master_table, self.identity_table) self.identity_chain = relationshiplinkchain(self.master_table, self.identity_table)
else: else:
if required_tables: if required_tables:
raise InvalidConfigError("Tables are required by the commands, but Alchemy is not configured") raise InvalidConfigError("Tables are required by the _commands, but Alchemy is not configured")
self.alchemy = None self.alchemy = None
self.master_table = None self.master_table = None
self.identity_table = None self.identity_table = None
self.identity_column = None self.identity_column = None
self.identity_chain = None self.identity_chain = None
# Connect to Royalnet
self.network: RoyalnetLink = RoyalnetLink(master_server_uri, master_server_secret, "discord",
self.network_handler)
loop.create_task(self.network.run())
# Create the PlayModes dictionary # Create the PlayModes dictionary
self.music_data: typing.Dict[discord.Guild, PlayMode] = {} self.music_data: typing.Dict[discord.Guild, PlayMode] = {}
@ -134,8 +118,9 @@ class DiscordBot:
try: try:
selected_command = self.commands[command_text] selected_command = self.commands[command_text]
except KeyError: except KeyError:
# Skip inexistent commands # Skip inexistent _commands
selected_command = self.missing_command selected_command = self.missing_command
log.error(f"Running {selected_command}")
# Call the command # Call the command
try: try:
return await self.DiscordCall(message.channel, selected_command, parameters, log, return await self.DiscordCall(message.channel, selected_command, parameters, log,
@ -208,11 +193,6 @@ class DiscordBot:
return voice_client return voice_client
raise NoneFoundError("No voice clients found") raise NoneFoundError("No voice clients found")
async def network_handler(self, message: Message) -> Message:
"""Handle a Royalnet request."""
log.debug(f"Received {message} from Royalnet")
return await self.network_handlers[message.__class__].discord(message)
async def add_to_music_data(self, url: str, guild: discord.Guild): async def add_to_music_data(self, url: str, guild: discord.Guild):
"""Add a file to the corresponding music_data object.""" """Add a file to the corresponding music_data object."""
log.debug(f"Downloading {url} to add to music_data") log.debug(f"Downloading {url} to add to music_data")

View file

@ -33,7 +33,7 @@ class TelegramBot:
self.error_command = error_command self.error_command = error_command
self.network: RoyalnetLink = RoyalnetLink(master_server_uri, master_server_secret, "telegram", todo) self.network: RoyalnetLink = RoyalnetLink(master_server_uri, master_server_secret, "telegram", todo)
loop.create_task(self.network.run()) loop.create_task(self.network.run())
# Generate commands # Generate _commands
self.commands = {} self.commands = {}
required_tables = set() required_tables = set()
for command in commands: for command in commands:
@ -48,7 +48,7 @@ class TelegramBot:
self.identity_chain = relationshiplinkchain(self.master_table, self.identity_table) self.identity_chain = relationshiplinkchain(self.master_table, self.identity_table)
else: else:
if required_tables: if required_tables:
raise InvalidConfigError("Tables are required by the commands, but Alchemy is not configured") raise InvalidConfigError("Tables are required by the _commands, but Alchemy is not configured")
self.alchemy = None self.alchemy = None
self.master_table = None self.master_table = None
self.identity_table = None self.identity_table = None
@ -135,7 +135,7 @@ class TelegramBot:
try: try:
command = self.commands[command_text] command = self.commands[command_text]
except KeyError: except KeyError:
# Skip inexistent commands # Skip inexistent _commands
command = self.missing_command command = self.missing_command
# Call the command # Call the command
# noinspection PyBroadException # noinspection PyBroadException

View file

@ -35,6 +35,7 @@ class PlayNH(NetworkHandler):
# TODO: change Exception # TODO: change Exception
raise Exception("No music_data for this guild") raise Exception("No music_data for this guild")
# Start downloading # Start downloading
# noinspection PyAsyncCall
loop.create_task(bot.add_to_music_data(message.url, guild)) loop.create_task(bot.add_to_music_data(message.url, guild))
return RequestSuccessful() return RequestSuccessful()

View file

@ -2,6 +2,7 @@ from .messages import Message, ServerErrorMessage, InvalidSecretEM, InvalidDesti
from .packages import Package from .packages import Package
from .royalnetlink import RoyalnetLink, NetworkError, NotConnectedError, NotIdentifiedError from .royalnetlink import RoyalnetLink, NetworkError, NotConnectedError, NotIdentifiedError
from .royalnetserver import RoyalnetServer from .royalnetserver import RoyalnetServer
from .royalnetconfig import RoyalnetConfig
__all__ = ["Message", __all__ = ["Message",
"ServerErrorMessage", "ServerErrorMessage",
@ -15,4 +16,5 @@ __all__ = ["Message",
"Package", "Package",
"RoyalnetServer", "RoyalnetServer",
"RequestSuccessful", "RequestSuccessful",
"RequestError"] "RequestError",
"RoyalnetConfig"]

View file

@ -0,0 +1,12 @@
import typing
class RoyalnetConfig:
def __init__(self,
master_uri: str,
master_secret: str):
if not (master_uri.startswith("ws://")
or master_uri.startswith("wss://")):
raise ValueError("Invalid protocol (must be ws:// or wss://)")
self.master_uri = master_uri
self.master_secret = master_secret

75
royalnet/utils/bot.py Normal file
View file

@ -0,0 +1,75 @@
import typing
import asyncio
import logging
from ..utils import Command, NetworkHandler
from ..commands import NullCommand
from ..network import RoyalnetLink, Message, RequestError, RoyalnetConfig
from ..database import Alchemy, DatabaseConfig, relationshiplinkchain
loop = asyncio.get_event_loop()
log = logging.getLogger(__name__)
class GenericBot:
def _init_commands(self,
commands: typing.List[typing.Type[Command]],
missing_command: typing.Type[Command],
error_command: typing.Type[Command]):
log.debug(f"Now generating commands")
self.commands: typing.Dict[str, typing.Type[Command]] = {}
self.network_handlers: typing.Dict[typing.Type[Message], typing.Type[NetworkHandler]] = {}
for command in commands:
self.commands[f"!{command.command_name}"] = command
self.network_handlers = {**self.network_handlers, **command.network_handler_dict()}
self.missing_command: typing.Type[Command] = missing_command
self.error_command: typing.Type[Command] = error_command
log.debug(f"Successfully generated commands")
def _init_royalnet(self, royalnet_config: RoyalnetConfig):
self.network: RoyalnetLink = RoyalnetLink(royalnet_config.master_uri, royalnet_config.master_secret, "discord",
self._network_handler)
log.debug(f"Running RoyalnetLink {self.network}")
loop.create_task(self.network.run())
def _network_handler(self, message: Message) -> Message:
log.debug(f"Received {message} from the RoyalnetLink")
try:
network_handler = self.network_handlers[message.__class__]
except KeyError as exc:
log.debug(f"Missing network_handler for {message}")
return RequestError(KeyError("Missing network_handler"))
try:
log.debug(f"Using {network_handler} as handler for {message}")
return await network_handler.discord(message)
except Exception as exc:
log.debug(f"Exception {exc} in {network_handler}")
return RequestError(exc)
def _init_database(self, commands: typing.List[typing.Type[Command]], database_config: DatabaseConfig):
required_tables = set()
for command in commands:
required_tables = required_tables.union(command.require_alchemy_tables)
self.alchemy = Alchemy(database_config.database_uri, required_tables)
self.master_table = self.alchemy.__getattribute__(database_config.master_table.__name__)
self.identity_table = self.alchemy.__getattribute__(database_config.identity_table.__name__)
self.identity_column = self.identity_table.__getattribute__(self.identity_table,
database_config.identity_column_name)
self.identity_chain = relationshiplinkchain(self.master_table, self.identity_table)
def __init__(self, *,
royalnet_config: RoyalnetConfig,
database_config: typing.Optional[DatabaseConfig] = None,
commands: typing.Optional[typing.List[typing.Type[Command]]] = None,
missing_command: typing.Type[Command] = NullCommand,
error_command: typing.Type[Command] = NullCommand):
if commands is None:
commands = []
self._init_commands(commands, missing_command=missing_command, error_command=error_command)
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)

View file

@ -56,7 +56,10 @@ class Call:
async def run(self): async def run(self):
await self.session_init() await self.session_init()
try:
coroutine = getattr(self.command, self.interface_name) coroutine = getattr(self.command, self.interface_name)
except AttributeError:
coroutine = self.command.common
try: try:
result = await coroutine(self) result = await coroutine(self)
finally: finally:

View file

@ -27,9 +27,3 @@ class Command:
for network_handler in cls.network_handlers: for network_handler in cls.network_handlers:
d[network_handler.message_type] = network_handler d[network_handler.message_type] = network_handler
return d return d
def __getattribute__(self, item: str):
try:
return self.__dict__[item]
except KeyError:
return self.common

View file

@ -6,9 +6,3 @@ class NetworkHandler:
"""The NetworkHandler functions are called when a specific Message type is received.""" """The NetworkHandler functions are called when a specific Message type is received."""
message_type = NotImplemented message_type = NotImplemented
def __getattribute__(self, item: str):
try:
return self.__dict__[item]
except KeyError:
raise UnsupportedError()