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

Fix leftover bugs

This commit is contained in:
Steffo 2019-08-24 00:00:42 +02:00
parent d65f677e21
commit b6ffbef521
8 changed files with 15 additions and 104 deletions

View file

@ -24,6 +24,7 @@ class DiscordConfig:
class DiscordBot(GenericBot): class DiscordBot(GenericBot):
"""A bot that connects to `Discord <https://discordapp.com/>`_.""" """A bot that connects to `Discord <https://discordapp.com/>`_."""
interface_name = "discord"
def _init_voice(self): def _init_voice(self):
"""Initialize the variables needed for the connection to voice chat.""" """Initialize the variables needed for the connection to voice chat."""
@ -36,7 +37,7 @@ class DiscordBot(GenericBot):
# noinspection PyMethodParameters,PyAbstractClass # noinspection PyMethodParameters,PyAbstractClass
class DiscordInterface(GenericInterface): class DiscordInterface(GenericInterface):
name = "discord" name = self.interface_name
prefix = "!" prefix = "!"
return DiscordInterface return DiscordInterface

View file

@ -24,7 +24,7 @@ class GenericBot:
self._Interface = self._interface_factory() self._Interface = self._interface_factory()
self._Data = self._data_factory() self._Data = self._data_factory()
self.commands = {} self.commands = {}
for SelectedCommand in self.commands: for SelectedCommand in commands:
interface = self._Interface() interface = self._Interface()
self.commands[f"{interface.prefix}{SelectedCommand.name}"] = SelectedCommand(interface) self.commands[f"{interface.prefix}{SelectedCommand.name}"] = SelectedCommand(interface)
self.network_handlers: typing.Dict[str, typing.Type[NetworkHandler]] = {} self.network_handlers: typing.Dict[str, typing.Type[NetworkHandler]] = {}
@ -107,7 +107,7 @@ class GenericBot:
"""Create an :py:class:`royalnet.database.Alchemy` with the tables required by the commands. Then, """Create an :py:class:`royalnet.database.Alchemy` with the tables required by the commands. Then,
find the chain that links the ``master_table`` to the ``identity_table``. """ find the chain that links the ``master_table`` to the ``identity_table``. """
log.debug(f"Initializing database") log.debug(f"Initializing database")
required_tables = set() required_tables = {database_config.master_table, database_config.identity_table}
for command in commands: for command in commands:
required_tables = required_tables.union(command.require_alchemy_tables) required_tables = required_tables.union(command.require_alchemy_tables)
log.debug(f"Found {len(required_tables)} required tables") log.debug(f"Found {len(required_tables)} required tables")

View file

@ -21,6 +21,7 @@ class TelegramConfig:
class TelegramBot(GenericBot): class TelegramBot(GenericBot):
"""A bot that connects to `Telegram <https://telegram.org/>`_.""" """A bot that connects to `Telegram <https://telegram.org/>`_."""
interface_name = "telegram"
def _init_client(self): def _init_client(self):
"""Create the :py:class:`telegram.Bot`, and set the starting offset.""" """Create the :py:class:`telegram.Bot`, and set the starting offset."""
@ -35,7 +36,7 @@ class TelegramBot(GenericBot):
# noinspection PyMethodParameters,PyAbstractClass # noinspection PyMethodParameters,PyAbstractClass
class TelegramInterface(GenericInterface): class TelegramInterface(GenericInterface):
name = "telegram" name = self.interface_name
prefix = "/" prefix = "/"
return TelegramInterface return TelegramInterface
@ -99,7 +100,7 @@ class TelegramBot(GenericBot):
command_text, *parameters = text.split(" ") command_text, *parameters = text.split(" ")
command_name = command_text.replace(f"@{self.client.username}", "").lower() command_name = command_text.replace(f"@{self.client.username}", "").lower()
# Send a typing notification # Send a typing notification
self.client.send_chat_action(update.message.chat, telegram.ChatAction.TYPING) update.message.chat.send_action(telegram.ChatAction.TYPING)
# Find the command # Find the command
try: try:
command = self.commands[command_name] command = self.commands[command_name]
@ -125,4 +126,3 @@ class TelegramBot(GenericBot):
self._offset = last_updates[-1].update_id + 1 self._offset = last_updates[-1].update_id + 1
except IndexError: except IndexError:
pass pass

View file

@ -1,5 +1,6 @@
from .commandinterface import CommandInterface from .commandinterface import CommandInterface
from .command import Command from .command import Command
from .commanddata import CommandData from .commanddata import CommandData
from .commandargs import CommandArgs
__all__ = ["CommandInterface", "Command", "CommandData"] __all__ = ["CommandInterface", "Command", "CommandData", "CommandArgs"]

View file

@ -3,38 +3,6 @@
These probably won't suit your needs, as they are tailored for the bots of the Royal Games gaming community, but they These probably won't suit your needs, as they are tailored for the bots of the Royal Games gaming community, but they
may be useful to develop new ones.""" may be useful to develop new ones."""
from .null import NullCommand
from .ping import PingCommand from .ping import PingCommand
from .ship import ShipCommand
from .smecds import SmecdsCommand
from .ciaoruozi import CiaoruoziCommand
from .color import ColorCommand
from .sync import SyncCommand
from .diario import DiarioCommand
from .rage import RageCommand
from .dateparser import DateparserCommand
from .author import AuthorCommand
from .reminder import ReminderCommand
from .kvactive import KvactiveCommand
from .kv import KvCommand
from .kvroll import KvrollCommand
from .videoinfo import VideoinfoCommand
from .summon import SummonCommand
from .play import PlayCommand
from .skip import SkipCommand
from .playmode import PlaymodeCommand
from .videochannel import VideochannelCommand
from .missing import MissingCommand
from .cv import CvCommand
from .pause import PauseCommand
from .queue import QueueCommand
from .royalnetprofile import RoyalnetprofileCommand
from .id import IdCommand
from .dlmusic import DlmusicCommand
__all__ = ["PingCommand"]
__all__ = ["NullCommand", "PingCommand", "ShipCommand", "SmecdsCommand", "CiaoruoziCommand", "ColorCommand",
"SyncCommand", "DiarioCommand", "RageCommand", "DateparserCommand", "AuthorCommand", "ReminderCommand",
"KvactiveCommand", "KvCommand", "KvrollCommand", "VideoinfoCommand", "SummonCommand", "PlayCommand",
"SkipCommand", "PlaymodeCommand", "VideochannelCommand", "MissingCommand", "CvCommand", "PauseCommand",
"QueueCommand", "RoyalnetprofileCommand", "IdCommand", "DlmusicCommand"]

View file

@ -4,10 +4,7 @@ import os
import asyncio import asyncio
import logging import logging
from royalnet.bots import DiscordBot, DiscordConfig, TelegramBot, TelegramConfig from royalnet.bots import DiscordBot, DiscordConfig, TelegramBot, TelegramConfig
from royalnet.commands import * from royalnet.commands.royalgames import *
# noinspection PyUnresolvedReferences
from royalnet.commands import DebugCreateCommand
from royalnet.commands import ErrorHandlerCommand
from royalnet.network import RoyalnetServer, RoyalnetConfig from royalnet.network import RoyalnetServer, RoyalnetConfig
from royalnet.database import DatabaseConfig from royalnet.database import DatabaseConfig
from royalnet.database.tables import Royal, Telegram, Discord from royalnet.database.tables import Royal, Telegram, Discord
@ -19,15 +16,10 @@ stream_handler = logging.StreamHandler()
stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{") stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")
log.addHandler(stream_handler) log.addHandler(stream_handler)
commands = [PingCommand, ShipCommand, SmecdsCommand, ColorCommand, CiaoruoziCommand, SyncCommand, commands = [PingCommand]
DiarioCommand, RageCommand, ReminderCommand, KvactiveCommand, KvCommand,
KvrollCommand, SummonCommand, PlayCommand, SkipCommand, PlaymodeCommand,
VideochannelCommand, CvCommand, PauseCommand, QueueCommand, RoyalnetprofileCommand, VideoinfoCommand,
IdCommand, DlmusicCommand]
# noinspection PyUnreachableCode # noinspection PyUnreachableCode
if __debug__: if __debug__:
commands = [DebugCreateCommand, DateparserCommand, AuthorCommand, *commands]
log.setLevel(logging.DEBUG) log.setLevel(logging.DEBUG)
else: else:
log.setLevel(logging.INFO) log.setLevel(logging.INFO)
@ -42,15 +34,11 @@ print("Starting bots...")
ds_bot = DiscordBot(discord_config=DiscordConfig(os.environ["DS_AK"]), ds_bot = DiscordBot(discord_config=DiscordConfig(os.environ["DS_AK"]),
royalnet_config=RoyalnetConfig(f"ws://{address}:{port}", os.environ["MASTER_KEY"]), royalnet_config=RoyalnetConfig(f"ws://{address}:{port}", os.environ["MASTER_KEY"]),
database_config=DatabaseConfig(os.environ["DB_PATH"], Royal, Discord, "discord_id"), database_config=DatabaseConfig(os.environ["DB_PATH"], Royal, Discord, "discord_id"),
commands=commands, commands=commands)
error_command=ErrorHandlerCommand,
missing_command=MissingCommand)
tg_bot = TelegramBot(telegram_config=TelegramConfig(os.environ["TG_AK"]), tg_bot = TelegramBot(telegram_config=TelegramConfig(os.environ["TG_AK"]),
royalnet_config=RoyalnetConfig(f"ws://{address}:{port}", os.environ["MASTER_KEY"]), royalnet_config=RoyalnetConfig(f"ws://{address}:{port}", os.environ["MASTER_KEY"]),
database_config=DatabaseConfig(os.environ["DB_PATH"], Royal, Telegram, "tg_id"), database_config=DatabaseConfig(os.environ["DB_PATH"], Royal, Telegram, "tg_id"),
commands=commands, commands=commands)
error_command=ErrorHandlerCommand,
missing_command=MissingCommand)
loop.create_task(tg_bot.run()) loop.create_task(tg_bot.run())
loop.create_task(ds_bot.run()) loop.create_task(ds_bot.run())

View file

@ -1,46 +0,0 @@
"""The production Royalnet, active at @royalgamesbot on Telegram and Royalbot on Discord."""
import os
import asyncio
import logging
from royalnet.bots import DiscordBot, DiscordConfig, TelegramBot, TelegramConfig
from royalnet.commands import *
# noinspection PyUnresolvedReferences
from royalnet.commands import DebugCreateCommand
from royalnet.commands import ErrorHandlerCommand
from royalnet.network import RoyalnetServer, RoyalnetConfig
loop = asyncio.get_event_loop()
log = logging.root
stream_handler = logging.StreamHandler()
stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")
log.addHandler(stream_handler)
log.setLevel(logging.INFO)
commands = [PingCommand, SummonCommand, PlayCommand, SkipCommand, PlaymodeCommand, PauseCommand, QueueCommand]
address, port = "127.0.0.1", 1234
print("Starting master...")
master = RoyalnetServer(address, port, os.environ["MASTER_KEY"])
loop.run_until_complete(master.start())
print("Starting bots...")
ds_bot = DiscordBot(discord_config=DiscordConfig(os.environ["DS_AK"]),
royalnet_config=RoyalnetConfig(f"ws://{address}:{port}", os.environ["MASTER_KEY"]),
database_config=None,
commands=commands,
error_command=ErrorHandlerCommand,
missing_command=MissingCommand)
tg_bot = TelegramBot(telegram_config=TelegramConfig(os.environ["TG_AK"]),
royalnet_config=RoyalnetConfig(f"ws://{address}:{port}", os.environ["MASTER_KEY"]),
database_config=None,
commands=commands,
error_command=ErrorHandlerCommand,
missing_command=MissingCommand)
loop.create_task(tg_bot.run())
loop.create_task(ds_bot.run())
print("Running loop...")
loop.run_forever()

View file

@ -2,13 +2,12 @@
from .asyncify import asyncify from .asyncify import asyncify
from .escaping import telegram_escape, discord_escape from .escaping import telegram_escape, discord_escape
from .commandargs import CommandArgs
from .safeformat import safeformat from .safeformat import safeformat
from .classdictjanitor import cdj from .classdictjanitor import cdj
from .sleepuntil import sleep_until from .sleepuntil import sleep_until
from .networkhandler import NetworkHandler from .networkhandler import NetworkHandler
from .formatters import andformat, plusformat, fileformat, ytdldateformat, numberemojiformat from .formatters import andformat, plusformat, fileformat, ytdldateformat, numberemojiformat
__all__ = ["asyncify", "safeformat", "cdj", "sleep_until", "plusformat", "CommandArgs", __all__ = ["asyncify", "safeformat", "cdj", "sleep_until", "plusformat",
"NetworkHandler", "andformat", "plusformat", "fileformat", "ytdldateformat", "numberemojiformat", "NetworkHandler", "andformat", "plusformat", "fileformat", "ytdldateformat", "numberemojiformat",
"telegram_escape", "discord_escape"] "telegram_escape", "discord_escape"]