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

Add summon command, but it's unfinished

This commit is contained in:
Steffo 2019-04-14 23:31:24 +02:00
parent 43ce9b09f2
commit ac2ea55902
8 changed files with 80 additions and 13 deletions

View file

@ -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())

View file

@ -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"

View file

@ -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()

View file

@ -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"]

View file

@ -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}")

View file

@ -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):

View file

@ -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

View file

@ -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