From ac2ea55902e77b628f1e94c4a35f2349e2ffaadc Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 14 Apr 2019 23:31:24 +0200 Subject: [PATCH] Add summon command, but it's unfinished --- royalgames.py | 17 ++++++++++++--- royalnet/bots/discord.py | 27 +++++++++++++++++++---- royalnet/bots/telegram.py | 1 + royalnet/commands/__init__.py | 3 ++- royalnet/commands/summon.py | 35 ++++++++++++++++++++++++++++++ royalnet/commands/videoinfo.py | 4 ++-- royalnet/network/royalnetlink.py | 2 +- royalnet/network/royalnetserver.py | 4 ++-- 8 files changed, 80 insertions(+), 13 deletions(-) create mode 100644 royalnet/commands/summon.py diff --git a/royalgames.py b/royalgames.py index 0a31fdf3..02da2fa8 100644 --- a/royalgames.py +++ b/royalgames.py @@ -1,5 +1,6 @@ import os import asyncio +import logging from royalnet.bots import TelegramBot, DiscordBot from royalnet.commands import * from royalnet.commands.debug_create import DebugCreateCommand @@ -9,13 +10,23 @@ from royalnet.database.tables import Royal, Telegram, Discord loop = asyncio.get_event_loop() +tg_log = logging.getLogger("royalnet.bots.telegram") +tg_log.addHandler(logging.StreamHandler()) +tg_log.setLevel(logging.DEBUG) +ds_log = logging.getLogger("royalnet.bots.discord") +ds_log.addHandler(logging.StreamHandler()) +ds_log.setLevel(logging.DEBUG) +rygnet_log = logging.getLogger("royalnet.network.server") +rygnet_log.addHandler(logging.StreamHandler()) +rygnet_log.setLevel(logging.DEBUG) + commands = [PingCommand, ShipCommand, SmecdsCommand, ColorCommand, CiaoruoziCommand, DebugCreateCommand, SyncCommand, AuthorCommand, DiarioCommand, RageCommand, DateparserCommand, ReminderCommand, KvactiveCommand, KvCommand, - KvrollCommand, VideoinfoCommand] + KvrollCommand, VideoinfoCommand, SummonCommand] master = RoyalnetServer("localhost", 1234, "sas") -tg_bot = TelegramBot(os.environ["TG_AK"], "localhost:1234", "sas", commands, os.environ["DB_PATH"], Royal, Telegram, "tg_id", error_command=ErrorHandlerCommand) -ds_bot = DiscordBot(os.environ["DS_AK"], "localhost:1234", "sas", commands, os.environ["DB_PATH"], Royal, Discord, "discord_id", error_command=ErrorHandlerCommand) +tg_bot = TelegramBot(os.environ["TG_AK"], "ws://localhost:1234", "sas", commands, os.environ["DB_PATH"], Royal, Telegram, "tg_id", error_command=ErrorHandlerCommand) +ds_bot = DiscordBot(os.environ["DS_AK"], "ws://localhost:1234", "sas", commands, os.environ["DB_PATH"], Royal, Discord, "discord_id", error_command=ErrorHandlerCommand) loop.create_task(master.run()) loop.create_task(tg_bot.run()) loop.create_task(ds_bot.run()) diff --git a/royalnet/bots/discord.py b/royalnet/bots/discord.py index 348272e6..776ea881 100644 --- a/royalnet/bots/discord.py +++ b/royalnet/bots/discord.py @@ -4,6 +4,7 @@ import typing import logging as _logging import sys from ..commands import NullCommand +from ..commands.summon import SummonMessage, SummonSuccessful, SummonError from ..utils import asyncify, Call, Command, UnregisteredError from ..network import RoyalnetLink, Message from ..database import Alchemy, relationshiplinkchain @@ -11,9 +12,9 @@ from ..database import Alchemy, relationshiplinkchain loop = asyncio.get_event_loop() log = _logging.getLogger(__name__) - -async def todo(message: Message): - log.warning(f"Skipped {message} because handling isn't supported yet.") +# TODO: Load the opus library +if not discord.opus.is_loaded(): + log.error("Opus is not loaded. Weird behaviour might emerge.") class DiscordBot: @@ -31,7 +32,6 @@ class DiscordBot: self.token = token self.missing_command = missing_command self.error_command = error_command - self.network: RoyalnetLink = RoyalnetLink(master_server_uri, master_server_secret, "discord", todo) # Generate commands self.commands = {} required_tables = set() @@ -45,6 +45,25 @@ class DiscordBot: self.identity_column = self.identity_table.__getattribute__(self.identity_table, identity_column_name) self.identity_chain = relationshiplinkchain(self.master_table, self.identity_table) + async def network_handler(message: Message) -> Message: + if isinstance(message, SummonMessage): + channels: typing.List[discord.abc.GuildChannel] = self.bot.get_all_channels() + matching_channels: typing.List[discord.VoiceChannel] = [] + for channel in channels: + if isinstance(channel, discord.VoiceChannel): + if channel.name == message.channel_name: + matching_channels.append(channel) + if len(matching_channels) == 0: + return SummonError("No channels with a matching name found") + elif len(matching_channels) > 1: + return SummonError("Multiple channels with a matching name found") + matching_channel = matching_channels[0] + await matching_channel.connect() + return SummonSuccessful() + + self.network: RoyalnetLink = RoyalnetLink(master_server_uri, master_server_secret, "discord", network_handler) + loop.create_task(self.network.run()) + # noinspection PyMethodParameters class DiscordCall(Call): interface_name = "discord" diff --git a/royalnet/bots/telegram.py b/royalnet/bots/telegram.py index 2c53e8fa..f44f1697 100644 --- a/royalnet/bots/telegram.py +++ b/royalnet/bots/telegram.py @@ -34,6 +34,7 @@ class TelegramBot: self.missing_command = missing_command self.error_command = error_command self.network: RoyalnetLink = RoyalnetLink(master_server_uri, master_server_secret, "telegram", todo) + loop.create_task(self.network.run()) # Generate commands self.commands = {} required_tables = set() diff --git a/royalnet/commands/__init__.py b/royalnet/commands/__init__.py index d03da647..86718a1c 100644 --- a/royalnet/commands/__init__.py +++ b/royalnet/commands/__init__.py @@ -14,8 +14,9 @@ from .kvactive import KvactiveCommand from .kv import KvCommand from .kvroll import KvrollCommand from .videoinfo import VideoinfoCommand +from .summon import SummonCommand __all__ = ["NullCommand", "PingCommand", "ShipCommand", "SmecdsCommand", "CiaoruoziCommand", "ColorCommand", "SyncCommand", "DiarioCommand", "RageCommand", "DateparserCommand", "AuthorCommand", "ReminderCommand", - "KvactiveCommand", "KvCommand", "KvrollCommand", "VideoinfoCommand"] + "KvactiveCommand", "KvCommand", "KvrollCommand", "VideoinfoCommand", "SummonCommand"] diff --git a/royalnet/commands/summon.py b/royalnet/commands/summon.py new file mode 100644 index 00000000..e0284dfe --- /dev/null +++ b/royalnet/commands/summon.py @@ -0,0 +1,35 @@ +import typing +from ..utils import Command, Call +from ..network import Message, ErrorMessage + + +class SummonMessage(Message): + def __init__(self, channel_name: str): + self.channel_name: str = channel_name + + +class SummonSuccessful(Message): + pass + + +class SummonError(ErrorMessage): + pass + + +class SummonCommand(Command): + + command_name = "summon" + command_description = "Evoca il bot in un canale vocale." + command_syntax = "[channelname]" + + @classmethod + async def common(cls, call: Call): + channel_name: str = call.args[0].lstrip("#") + response: typing.Union[SummonSuccessful, SummonError] = await call.net_request(SummonMessage(channel_name), "discord") + if isinstance(response, SummonError): + await call.reply(f"⚠️ Si è verificato un'errore nella richiesta di connessione:\n[c]{response.reason}[/c]") + return + elif isinstance(response, SummonSuccessful): + await call.reply(f"✅ Mi sono connesso in [c]#{channel_name}[/c].") + return + raise Exception(f"wtf is this: {response}") diff --git a/royalnet/commands/videoinfo.py b/royalnet/commands/videoinfo.py index f1a78d7c..f92ac2bd 100644 --- a/royalnet/commands/videoinfo.py +++ b/royalnet/commands/videoinfo.py @@ -6,8 +6,8 @@ from ..audio import YtdlInfo class VideoinfoCommand(Command): command_name = "videoinfo" - command_description = "Scarica e visualizza le informazioni di un video." - command_syntax = "" + command_description = "Visualizza le informazioni di un video." + command_syntax = "(url)" @classmethod async def common(cls, call: Call): diff --git a/royalnet/network/royalnetlink.py b/royalnet/network/royalnetlink.py index 73778528..60da741d 100644 --- a/royalnet/network/royalnetlink.py +++ b/royalnet/network/royalnetlink.py @@ -52,7 +52,7 @@ def requires_connection(func): def requires_identification(func): @functools.wraps(func) async def new_func(self, *args, **kwargs): - await self._identify_event.wait() + await self.identify_event.wait() return await func(self, *args, **kwargs) return new_func diff --git a/royalnet/network/royalnetserver.py b/royalnet/network/royalnetserver.py index c0e4009b..f194cfca 100644 --- a/royalnet/network/royalnetserver.py +++ b/royalnet/network/royalnetserver.py @@ -16,8 +16,8 @@ log = _logging.getLogger(__name__) class ConnectedClient: def __init__(self, socket: websockets.WebSocketServerProtocol): self.socket: websockets.WebSocketServerProtocol = socket - self.nid: str = None - self.link_type: str = None + self.nid: typing.Optional[str] = None + self.link_type: typing.Optional[str] = None self.connection_datetime: datetime.datetime = datetime.datetime.now() @property