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

Whee! More moving around!

This commit is contained in:
Steffo 2019-04-19 02:29:39 +02:00
parent e677cbe9b3
commit db1f1ded12
4 changed files with 31 additions and 31 deletions

View file

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

View file

@ -1,4 +1,4 @@
from .telegram import TelegramBot
from .discord import DiscordBot
from .discord import DiscordBot, DiscordConfig
__all__ = ["TelegramBot", "DiscordBot"]
__all__ = ["TelegramBot", "DiscordBot", "DiscordConfig"]

View file

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

View file

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