Exemplo n.º 1
0
    async def on_ready(self):
        """
        Triggers when the bot is ready.
        """
        if not self.ready:
            self._user = self.client.user
            await self._update_profile()
            LOGGER.debug('Logged in as: %s', self.client.user.name)
            try:
                self._server = set(self.client.servers).pop()
            except KeyError:
                LOGGER.error('Your discord bot has not server to connect to\n'
                             'Go to https://discordapp.com/developers/applications/me to create a bot, and note '
                             'the client ID.\n'
                             'Use the client ID in the following URL to join you bot to your Discord server:\n'
                             'https://discordapp.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot')
            else:
                self._member = self.server.get_member(self.user.id)
                if self.user.display_name != DiscordBotConfig.DISCORD_BOT_NAME():
                    await self.client.change_nickname(self.member, DiscordBotConfig.DISCORD_BOT_NAME())
                await self._update_presence()

            await self.get_channel()

            self._ready = True
Exemplo n.º 2
0
 async def _run(self):
     if CTX.discord_can_start:
         LOGGER.debug('starting Discord client')
         self._create_client()
         await self.client.start(DiscordBotConfig.DISCORD_TOKEN())
     else:
         await asyncio.sleep(1)
Exemplo n.º 3
0
    async def get_channel(self):
        """
        Sets the channel for the bot.

        If the channel does not exist, it will be created on the server, provided the bot has the authorization.
        """
        for channel in self.server.channels:
            if channel.name == DiscordBotConfig.DISCORD_CHANNEL():
                self._channel = channel
                break
        else:
            # noinspection PyUnresolvedReferences
            self._channel = await self.client.create_channel(
                server=self.server,
                name=DiscordBotConfig.DISCORD_CHANNEL(),
                type=discord.ChannelType.text,
            )
Exemplo n.º 4
0
    def __init__(self):
        self._parser = make_root_parser()
        self._client = None
        self._server = None
        self._user = None
        self._member = None
        self._channel = None
        self._ready = False
        self.tasks = None

        if not CTX.start_discord_loop:
            LOGGER.debug('skipping Discord bot startup')
            return

        LOGGER.debug('starting Discord bot')

        CTX.discord_msg_queue.put(DEFAULT_MOTD)
        if DiscordBotConfig.DISCORD_MOTD():
            CTX.discord_msg_queue.put(DiscordBotConfig.DISCORD_MOTD())
        register_logging_handler()
Exemplo n.º 5
0
    async def on_message(self, message: discord.Message):  # noqa: C901
        """
        Triggers on any message received from the Discord server

        Args:
            message: message received

        """
        if message.author.id == self.member.id:
            return
        if message.channel != self.channel:
            return
        if DiscordBotConfig.DISCORD_ADMIN_ROLES():
            is_admin = bool([
                role for role in DiscordBotConfig.DISCORD_ADMIN_ROLES()  # pylint: disable=not-an-iterable
                if role in [role.name for role in message.author.roles]
            ])
        else:
            is_admin = True
        if message.attachments:
            for attach in message.attachments:
                if attach['filename'].endswith('.miz'):
                    if not is_admin:
                        LOGGER.error(
                            f'only users with privileges can load missions on the server'
                        )
                        return
                    overwrite = 'overwrite' in message.content
                    load = 'load' in message.content
                    force = 'force' in message.content
                    missions_manager.download_mission_from_discord(
                        attach, overwrite, load, force)
        if message.content.startswith('!'):
            LOGGER.debug('received "%s" command from: %s%s', message.content,
                         message.author.display_name,
                         " (admin)" if is_admin else "")

            self.parser.parse_discord_message(message.content, is_admin)
Exemplo n.º 6
0
 async def _update_profile(self, user_name: str = None):
     user_name = user_name or DiscordBotConfig.DISCORD_BOT_NAME()
     profile_update = {}
     if self.user.name != user_name:
         profile_update['username'] = user_name
     if os.path.exists('avatar.png'):
         with open('avatar.png', 'rb') as handle:
             profile_update['avatar'] = handle.read()
     if profile_update:
         try:
             await self.client.edit_profile(**profile_update)
         except discord.errors.HTTPException:
             pass
         except aiohttp.errors.ClientResponseError:
             pass
         except websockets.exceptions.ConnectionClosed:
             pass
         except RuntimeError:
             pass
Exemplo n.º 7
0
def _write_auth_file():
    content = read_template('me_authorization.lua')
    LOGGER.debug('writing me_authorization.lua')
    _get_me_auth_path().write_text(
        jinja2.Template(content).render(
            server_name=DiscordBotConfig.DISCORD_BOT_NAME()))
Exemplo n.º 8
0
def main(debug: bool):  # pylint: disable=too-many-locals
    """
    Main entry point

    Args:
        debug: show more verbose console output
    """
    from esst import __version__, LOGGER, LOGGING_CONSOLE_HANDLER, config
    config.init()

    from esst.core import CTX
    from esst import ESSTConfig, DiscordBotConfig, DCSConfig, ListenerConfig, ServerConfig

    from esst.sentry.sentry import SENTRY
    SENTRY.register_context('App context', CTX)
    CTX.sentry = SENTRY

    _setup_logging_debug(__version__, LOGGER, LOGGING_CONSOLE_HANDLER, debug, ESSTConfig.DEBUG())

    LOGGER.debug('instantiating main event loop')
    loop = asyncio.get_event_loop()
    CTX.loop = loop

    _check_wan_and_start_wan_monitor(loop, LOGGER, CTX)

    CTX.start_discord_loop = DiscordBotConfig.DISCORD_START_BOT()
    CTX.start_server_loop = ServerConfig.SERVER_START_LOOP()
    CTX.start_dcs_loop = DCSConfig.DCS_START_LOOP()
    CTX.start_listener_loop = ListenerConfig.LISTENER_START_LOOP()

    if not DCSConfig.DCS_CAN_START():
        CTX.dcs_blocker.append('config')

    CTX.dcs_setup_dedi_config = DCSConfig.DCS_INSTALL_DEDICATED_CONFIG()
    CTX.dcs_install_hooks = DCSConfig.DCS_INSTALL_HOOKS()
    CTX.dcs_auto_mission = DCSConfig.DCS_AUTO_MISSION_ENABLE()

    loop = asyncio.get_event_loop()
    # loop.set_debug(True)
    CTX.discord_msg_queue = queue.Queue()

    _set_console_title(__version__)

    from esst import FS
    FS.init()

    from esst.utils import clean_all_folder, assign_ports
    clean_all_folder()
    assign_ports()

    _init_atis_module()

    import esst.discord_bot.discord_bot
    discord_loop = esst.discord_bot.discord_bot.App()

    from esst.dcs import dcs
    dcs_loop = dcs.App()

    from esst.server import server
    server_loop = server.App()

    from esst.listener.listener import DCSListener
    listener_loop = DCSListener()

    futures = asyncio.gather(
        loop.create_task(discord_loop.run()),
        loop.create_task(dcs_loop.run()),
        loop.create_task(listener_loop.run()),
        loop.create_task(server_loop.run()),
        loop.create_task(watch_for_exceptions()),
    )

    import signal
    signal.signal(signal.SIGINT, sigint_handler)
    loop.run_until_complete(futures)
    LOGGER.debug('main loop is done, killing DCS')

    futures = asyncio.gather(  # type: ignore
        loop.create_task(dcs_loop.kill_running_app()),
        loop.create_task(listener_loop.run_until_dcs_is_closed()),
    )

    loop.run_until_complete(futures)

    LOGGER.debug('all done !')