def drop(cog, quiet):
    """This removes a database and all its migrations.

    You must be pretty sure about this before you do it,
    as once you do it there's no coming back.

    Also note that the name must be the database name, not
    the cog name.
    """

    run = asyncio.get_event_loop().run_until_complete
    click.confirm('do you really want to do this?', abort=True)

    try:
        pool = run(Table.create_pool(config.postgresql))
    except Exception:
        click.echo(
            f'Could not create PostgreSQL connection pool.\n{traceback.format_exc()}',
            err=True)
        return

    if not cog.startswith('cogs.'):
        cog = f'cogs.{cog}'

    try:
        importlib.import_module(cog)
    except Exception:
        click.echo(f'Could not load {cog}.\n{traceback.format_exc()}',
                   err=True)
        return

    run(remove_databases(pool, cog, quiet))
Exemplo n.º 2
0
def init(cogs, quiet):
    """This manages the migrations and database creation system for you."""

    run = asyncio.get_event_loop().run_until_complete
    try:
        run(Table.create_pool(config.postgresql))
    except Exception:
        click.echo(f'Could not create PostgreSQL connection pool.\n{traceback.format_exc()}', err=True)
        return

    if not cogs:
        cogs = INITIAL_EXTENSIONS
    else:
        cogs = [f'cogs.{e}' if not e.startswith('cogs.') else e for e in cogs]

    for ext in cogs:
        try:
            importlib.import_module(ext)
        except Exception:
            click.echo(f'Could not load {ext}.\n{traceback.format_exc()}', err=True)
            return

    for table in Table.all_tables():
        try:
            created = run(table.create(verbose=not quiet, run_migrations=False))
        except Exception:
            click.echo(f'Could not create {table.__tablename__}.\n{traceback.format_exc()}', err=True)
        else:
            if created:
                click.echo(f'[{table.__module__}] Created {table.__tablename__}.')
            else:
                click.echo(f'[{table.__module__}] No work needed for {table.__tablename__}.')
Exemplo n.º 3
0
def run_bot():
    loop = asyncio.get_event_loop()
    log = logging.getLogger()

    try:
        pool = loop.run_until_complete(Table.create_pool(config.postgresql, command_timeout=60))
    except Exception as e:
        click.echo('Could not set up PostgreSQL. Exiting.', file=sys.stderr)
        log.exception('Could not set up PostgreSQL. Exiting.')
        return
    bot = MathsBot()
    bot.pool = pool
    bot.run()
Exemplo n.º 4
0
def run_bot():
    loop = asyncio.get_event_loop()
    kwargs = {
        'command_timeout': 60,
        'max_size': 20,
        'min_size': 20,
    }
    try:
        pool = loop.run_until_complete(
            Table.create_pool(config.postgresql, **kwargs))
    except Exception as e:
        click.echo('Could not set up PostgreSQL. Exiting.', file=sys.stderr)
        return

    bot = AggyBot()
    bot.pool = pool
    bot.run()
Exemplo n.º 5
0
def init(cogs, quiet):
    run = asyncio.get_event_loop().run_until_complete

    # noinspection PyBroadException
    try:
        run(Table.create_pool(config.postgresql))
    except Exception:
        click.echo(
            f'Could not create PostgreSQL connection pool.\n'
            f'{traceback.format_exc()}',
            err=True
        )
        return

    if not cogs:
        cogs = initial_extensions
    else:
        cogs = [f'cogs.{e}' if not e.startswith('cogs.') else e for e in cogs]

    for ext in cogs:
        # noinspection PyBroadException
        try:
            importlib.import_module(ext)
        except Exception:
            click.echo(
                f'Could not load {ext}.\n{traceback.format_exc()}',
                err=True
            )
            return

    for table in Table.all_tables():
        # noinspection PyBroadException
        try:
            run(table.create(verbose=not quiet))
        except Exception:
            click.echo(
                f'Could not create {table.__tablename__}.\n'
                f'{traceback.format_exc()}',
                err=True
            )
        else:
            click.echo(
                f'[{table.__module__}] Created {table.__tablename__}.'
            )
Exemplo n.º 6
0
        except Exception as exc:
            self.logger.exception("Exception when logging command error", exc_info=exc)

    async def on_error(self, event_method, *args, **kwargs):
        return await discord_event_error(self, event_method, *args, **kwargs)

    async def on_ready(self):
        activity = discord.Game("Clash of Clans")
        await self.change_presence(status=discord.Status.online, activity=activity)
        self.coc.add_clan_updates(*rcs_tags(prefix=True))

    async def after_ready(self):
        await self.wait_until_ready()
        self.session = aiohttp.ClientSession(loop=self.loop)
        logger.add(self.send_log, level=log_level)
        error_webhooks = await self.get_channel(settings['log_channels']['rcs']).webhooks()
        self.error_webhook = error_webhooks[0]
        logger.info("Bot is now ready")


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        pool = loop.run_until_complete(Table.create_pool(f"{settings['pg']['uri']}/tubadata"))
        bot = RcsBot()
        bot.pool = pool
        bot.loop = loop
        bot.run(token, reconnect=True)
    except:
        traceback.print_exc()
Exemplo n.º 7
0
            query = "SELECT DISTINCT clan_tag FROM clans WHERE guild_id = $1"
            fetch = await self.pool.fetch(query, guild_id)
        return await self.coc.get_clans(n[0].strip() for n in fetch).flatten()

    async def on_command_error(self, context, exception):
        return await error_handler(context, exception)

    async def on_error(self, event_method, *args, **kwargs):
        return await discord_event_error(self, event_method, *args, **kwargs)

    async def init_prefixes(self):
        query = "SELECT guild_id, prefix FROM guilds"
        fetch = await self.pool.fetch(query)
        self.prefixes = {n["guild_id"]: n["prefix"] for n in fetch}


if __name__ == '__main__':
    loop = asyncio.get_event_loop()

    try:
        # configure the database connection
        pool = loop.run_until_complete(Table.create_pool(creds.postgres))

        bot = DonationBot()
        bot.pool = pool  # add db as attribute
        setup_logging(bot)
        bot.run(creds.bot_token)  # run bot

    except Exception:
        traceback.print_exc()
Exemplo n.º 8
0
        with contextlib.redirect_stdout(None):
            await super().close()
            await self.session.close()
        print('Bot session closed!')

    def run(self):
        super().run(load_config()['token'], reconnect=True)


if __name__ == '__main__':
    with setup_logging():
        try:
            loop = asyncio.get_event_loop()
            try:
                pool = loop.run_until_complete(
                    Table.create_pool(load_config()['database'],
                                      command_timeout=60))
                print('Database connected!')
            except Exception as error:
                logging.error(''.join(
                    traceback.format_exception(type(error), error,
                                               error.__traceback__)))
                click.echo('Could not set up PostgreSQL. Exiting.',
                           file=sys.stderr)
                sys.exit(0)
            bot = HypixelBot()
            bot.pool = pool
            bot.run()
        except KeyboardInterrupt:
            sys.exit(0)
        except Exception as error:
            logging.error(''.join(
Exemplo n.º 9
0
        try:
            await self.log_channel.send(embed=e)
        except:
            pass

    async def on_ready(self):
        activity = discord.Game("Clash of Clans")
        await self.change_presence(status=discord.Status.online,
                                   activity=activity)

    async def close(self):
        await super().close()
        await self.coc.close()

    async def after_ready(self):
        await self.wait_until_ready()
        logger.add(self.send_log, level=log_level)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        pool = loop.run_until_complete(
            Table.create_pool(f"{settings['pg']['uri']}/tubadata"))
        bot = RcsBot()
        bot.pool = pool
        bot.loop = loop
        bot.run(token, reconnect=True)
    except:
        traceback.print_exc()