1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00

Start work on the beeg refactor

This commit is contained in:
Steffo 2019-10-04 09:55:20 +02:00
parent 5fcf2652c6
commit 22c3cd6351
14 changed files with 55 additions and 64 deletions

View file

@ -2,5 +2,15 @@ from .commandinterface import CommandInterface
from .command import Command from .command import Command
from .commanddata import CommandData from .commanddata import CommandData
from .commandargs import CommandArgs from .commandargs import CommandArgs
from .commanderrors import CommandError, InvalidInputError, UnsupportedError, KeyboardExpiredError
__all__ = ["CommandInterface", "Command", "CommandData", "CommandArgs"] __all__ = [
"CommandInterface",
"Command",
"CommandData",
"CommandArgs",
"CommandError",
"InvalidInputError",
"UnsupportedError",
"KeyboardExpiredError",
]

View file

@ -1,5 +1,4 @@
import typing import typing
from ..error import UnsupportedError
from .commandinterface import CommandInterface from .commandinterface import CommandInterface
from .commandargs import CommandArgs from .commandargs import CommandArgs
from .commanddata import CommandData from .commanddata import CommandData
@ -28,4 +27,4 @@ class Command:
self.interface = interface self.interface = interface
async def run(self, args: CommandArgs, data: CommandData) -> None: async def run(self, args: CommandArgs, data: CommandData) -> None:
raise UnsupportedError(f"Command {self.name} can't be called on {self.interface.name}.") raise NotImplementedError()

View file

@ -1,6 +1,6 @@
import re import re
import typing import typing
from royalnet.error import InvalidInputError from .commanderrors import InvalidInputError
class CommandArgs(list): class CommandArgs(list):

View file

@ -1,4 +1,5 @@
import typing import typing
from .commanderrors import UnsupportedError
class CommandData: class CommandData:
@ -7,31 +8,28 @@ class CommandData:
Parameters: Parameters:
text: The text to be sent, possibly formatted in the weird undescribed markup that I'm using.""" text: The text to be sent, possibly formatted in the weird undescribed markup that I'm using."""
raise NotImplementedError() raise UnsupportedError("'reply' is not supported on this platform")
async def get_author(self, error_if_none: bool = False): async def get_author(self, error_if_none: bool = False):
"""Try to find the identifier of the user that sent the message. """Try to find the identifier of the user that sent the message.
That probably means, the database row identifying the user. That probably means, the database row identifying the user.
Parameters: Parameters:
error_if_none: Raise a :py:exc:`royalnet.error.UnregisteredError` if this is True and the call has no author. error_if_none: Raise an exception if this is True and the call has no author."""
raise UnsupportedError("'get_author' is not supported on this platform")
Raises:
:py:exc:`royalnet.error.UnregisteredError` if ``error_if_none`` is set to True and no author is found."""
raise NotImplementedError()
async def keyboard(self, text: str, keyboard: typing.Dict[str, typing.Callable]) -> None: async def keyboard(self, text: str, keyboard: typing.Dict[str, typing.Callable]) -> None:
"""Send a keyboard having the keys of the dict as keys and calling the correspondent values on a press. """Send a keyboard having the keys of the dict as keys and calling the correspondent values on a press.
The function should be passed the :py:class:`CommandData` instance as a argument.""" The function should be passed the :py:class:`CommandData` instance as a argument."""
raise NotImplementedError() raise UnsupportedError("'keyboard' is not supported on this platform")
async def delete_invoking(self, error_if_unavailable=False): async def delete_invoking(self, error_if_unavailable=False) -> None:
"""Delete the invoking message, if supported by the interface. """Delete the invoking message, if supported by the interface.
The invoking message is the message send by the user that contains the command. The invoking message is the message send by the user that contains the command.
Parameters: Parameters:
error_if_unavailable: if True, raise NotImplementedError() if the message cannot been deleted""" error_if_unavailable: if True, raise an exception if the message cannot been deleted."""
if error_if_unavailable: if error_if_unavailable:
raise NotImplementedError() raise UnsupportedError("'delete_invoking' is not supported on this platform")

View file

@ -0,0 +1,25 @@
class CommandError(Exception):
"""Something went wrong during the execution of this command.
Display an error message to the user, explaining what went wrong."""
def __init__(self, message=""):
self.message = message
def __repr__(self):
return f"{self.__class__.__qualname__}({repr(self.message)})"
class InvalidInputError(CommandError):
"""The command has received invalid input and cannot complete.
Display an error message to the user, along with the correct syntax for the command."""
class UnsupportedError(CommandError):
"""A requested feature is not available on this interface.
Display an error message to the user, telling them to use another interface."""
class KeyboardExpiredError(CommandError):
"""A special type of exception that can be raised in keyboard handlers to mark a specific keyboard as expired."""

View file

@ -1,6 +1,6 @@
import typing import typing
import asyncio import asyncio
from ..error import UnsupportedError from .commanderrors import UnsupportedError
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
from ..database import Alchemy from ..database import Alchemy
from ..bots import GenericBot from ..bots import GenericBot
@ -21,11 +21,11 @@ class CommandInterface:
def register_net_handler(self, message_type: str, network_handler: typing.Callable): def register_net_handler(self, message_type: str, network_handler: typing.Callable):
"""Register a new handler for messages received through Royalnet.""" """Register a new handler for messages received through Royalnet."""
raise UnsupportedError() raise UnsupportedError("'register_net_handler' is not supported on this platform")
def unregister_net_handler(self, message_type: str): def unregister_net_handler(self, message_type: str):
"""Remove a Royalnet handler.""" """Remove a Royalnet handler."""
raise UnsupportedError() raise UnsupportedError("'unregister_net_handler' is not supported on this platform")
async def net_request(self, message, destination: str) -> dict: async def net_request(self, message, destination: str) -> dict:
"""Send data through a :py:class:`royalnet.network.NetworkLink` and wait for a """Send data through a :py:class:`royalnet.network.NetworkLink` and wait for a
@ -34,10 +34,10 @@ class CommandInterface:
Parameters: Parameters:
message: The data to be sent. Must be :py:mod:`pickle`-able. message: The data to be sent. Must be :py:mod:`pickle`-able.
destination: The destination of the request, either in UUID format or node name.""" destination: The destination of the request, either in UUID format or node name."""
raise UnsupportedError() raise UnsupportedError("'net_request' is not supported on this platform")
def register_keyboard_key(self, key_name: str, callback: typing.Callable): def register_keyboard_key(self, key_name: str, callback: typing.Callable):
raise UnsupportedError() raise UnsupportedError("'register_keyboard_key' is not supported on this platform")
def unregister_keyboard_key(self, key_name: str): def unregister_keyboard_key(self, key_name: str):
raise UnsupportedError() raise UnsupportedError("'unregister_keyboard_key' is not supported on this platform")

View file

View file

@ -38,10 +38,7 @@ class PlayNH(NetworkHandler):
"outtmpl": f"./downloads/{datetime.datetime.now().timestamp()}_%(title)s.%(ext)s" "outtmpl": f"./downloads/{datetime.datetime.now().timestamp()}_%(title)s.%(ext)s"
} }
# Start downloading # Start downloading
if data["url"].startswith("http://") or data["url"].startswith("https://"): dfiles: typing. List[YtdlDiscord] = await asyncify(YtdlDiscord.create_from_url, data["url"], **ytdl_args)
dfiles: typing.List[YtdlDiscord] = await asyncify(YtdlDiscord.create_from_url, data["url"], **ytdl_args)
else:
dfiles = await asyncify(YtdlDiscord.create_from_url, f"ytsearch:{data['url']}", **ytdl_args)
await bot.add_to_music_data(dfiles, guild) await bot.add_to_music_data(dfiles, guild)
# Create response dictionary # Create response dictionary
response = { response = {
@ -66,6 +63,8 @@ class PlayCommand(Command):
async def run(self, args: CommandArgs, data: CommandData) -> None: async def run(self, args: CommandArgs, data: CommandData) -> None:
guild_name, url = args.match(r"(?:\[(.+)])?\s*<?(.+)>?") guild_name, url = args.match(r"(?:\[(.+)])?\s*<?(.+)>?")
if not (url.startswith("http://") or url.startswith("https://")):
raise
response = await self.interface.net_request(Request("music_play", {"url": url, "guild_name": guild_name}), "discord") response = await self.interface.net_request(Request("music_play", {"url": url, "guild_name": guild_name}), "discord")
if len(response["videos"]) == 0: if len(response["videos"]) == 0:
await data.reply(f"⚠️ Nessun video trovato.") await data.reply(f"⚠️ Nessun video trovato.")

View file

@ -3,30 +3,6 @@ if typing.TYPE_CHECKING:
from .network import ResponseError from .network import ResponseError
class NoneFoundError(Exception):
"""The element that was being looked for was not found."""
class TooManyFoundError(Exception):
"""Multiple elements matching the request were found, and only one was expected."""
class UnregisteredError(Exception):
"""The command required a registered user, and the user was not registered."""
class UnsupportedError(Exception):
"""The command is not supported for the specified interface."""
class InvalidInputError(Exception):
"""The command has received invalid input and cannot complete."""
class InvalidConfigError(Exception):
"""The bot has not been configured correctly, therefore the command can not function."""
class RoyalnetRequestError(Exception): class RoyalnetRequestError(Exception):
"""An error was raised while handling the Royalnet request. """An error was raised while handling the Royalnet request.
@ -41,19 +17,3 @@ class RoyalnetRequestError(Exception):
class RoyalnetResponseError(Exception): class RoyalnetResponseError(Exception):
"""The :py:class:`royalnet.network.Response` that was received is invalid.""" """The :py:class:`royalnet.network.Response` that was received is invalid."""
class ExternalError(Exception):
"""Something went wrong in a non-Royalnet component and the command execution cannot be completed."""
class FileTooBigError(Exception):
"""The file to be downloaded would be too big to store; therefore, it has been skipped."""
class CurrentlyDisabledError(Exception):
"""This feature is temporarely disabled and is not available right now."""
class KeyboardExpiredError(Exception):
"""A special type of exception that can be raised in keyboard handlers to mark a specific keyboard as expired."""