예제 #1
0
async def task_check_for_data_updates(discord_client):
    filenames = LANG_FILES + [
        'World.json', 'User.json', 'Campaign.json', 'Soulforge.json'
    ]
    now = datetime.datetime.now()
    modified_files = []
    for filename in filenames:
        file_path = GameAssets.path(filename)
        try:
            modification_time = datetime.datetime.fromtimestamp(
                os.path.getmtime(file_path))
        except FileNotFoundError:
            continue
        modified = now - modification_time <= datetime.timedelta(
            seconds=CONFIG.get('file_update_check_seconds'))
        if modified:
            modified_files.append(filename)
    if modified_files:
        log.debug(
            f'Game file modification detected, reloading {", ".join(modified_files)}.'
        )
        await asyncio.sleep(5)
        lock = asyncio.Lock()
        async with lock:
            try:
                old_expander = discord_client.expander
                del discord_client.expander
                discord_client.expander = TeamExpander()
                update_translations()
            except Exception as e:
                log.error('Could not update game file. Stacktrace follows.')
                log.exception(e)
                discord_client.expander = old_expander
예제 #2
0
async def task_check_for_news(discord_client):
    lock = asyncio.Lock()
    async with lock:
        try:
            downloader = NewsDownloader()
            downloader.process_news_feed()
            await discord_client.show_latest_news()
        except Exception as e:
            log.error('Could not update news. Stacktrace follows.')
            log.exception(e)
예제 #3
0
    async def show_latest_news(self):
        if not self.is_ready():
            return

        with open(NewsDownloader.NEWS_FILENAME) as f:
            articles = json.load(f)
            articles.reverse()
        if articles:
            log.debug(
                f'Distributing {len(articles)} news articles to {len(self.subscriptions)} channels.'
            )
        for article in articles:
            e = discord.Embed(title='Gems of War news',
                              color=self.WHITE,
                              url=article['url'])
            content = self.views.trim_news_to_length(article['content'],
                                                     article['url'])
            e.add_field(name=article['title'], value=content)
            embeds = [e]
            for image_url in article['images']:
                e = discord.Embed(type='image', color=self.WHITE)
                e.set_image(url=image_url)
                embeds.append(e)

            for subscription in self.subscriptions:
                relevant_news = subscription.get(article['platform'])
                if not relevant_news:
                    continue
                channel = self.get_channel(subscription['channel_id'])
                if not channel:
                    log.debug(
                        f'Subscription {subscription} is broken, skipping.')
                    continue
                log.debug(
                    f'Sending [{article["platform"]}] {article["title"]} to {channel.guild.name}/{channel.name}.'
                )
                if not await self.is_writable(channel):
                    message = 'is not writable' if channel else 'does not exist'
                    log.debug(f'Channel {message}.')
                    continue
                try:
                    for e in embeds:
                        await channel.send(embed=e)
                except Exception as e:
                    log.error('Could not send out news, exception follows')
                    log.exception(e)
        with open(NewsDownloader.NEWS_FILENAME, 'w') as f:
            f.write('[]')
예제 #4
0
    async def show_latest_news(self):
        if not self.is_ready():
            return

        with open(NewsDownloader.NEWS_FILENAME) as f:
            articles = json.load(f)
            articles.reverse()
        if articles:
            log.debug(
                f'Distributing {len(articles)} news articles to {len(self.subscriptions)} channels.'
            )
        for article in articles:
            embeds = self.views.render_news(article)
            for subscription in self.subscriptions:
                relevant_news = subscription.get(article['platform'])
                if not relevant_news:
                    continue
                channel = self.get_channel(subscription['channel_id'])
                if not channel:
                    log.debug(
                        f'Subscription {subscription} is broken, skipping.')
                    continue
                log.debug(
                    f'Sending [{article["platform"]}] {article["title"]} to {channel.guild.name}/{channel.name}.'
                )
                if not await self.is_writable(channel):
                    message = 'is not writable' if channel else 'does not exist'
                    log.debug(f'Channel {message}.')
                    continue
                try:
                    for e in embeds:
                        await channel.send(embed=e)
                except Exception as ex:
                    log.error('Could not send out news, exception follows')
                    log.error(repr(e.fields))
                    log.exception(ex)
        with open(NewsDownloader.NEWS_FILENAME, 'w') as f:
            f.write('[]')
예제 #5
0
        guild_id = CONFIG.get('slash_command_guild_id')
        for command in await get_all_commands(self.user.id,
                                              TOKEN,
                                              guild_id=guild_id):
            await remove_slash_command(self.user.id, TOKEN, guild_id,
                                       command['id'])
        if not CONFIG.get('register_slash_commands'):
            return
        log.debug(f'Registering slash commands...')
        for command in COMMAND_REGISTRY:
            if 'description' not in command:
                continue
            await add_slash_command(self.user.id,
                                    bot_token=TOKEN,
                                    guild_id=guild_id,
                                    cmd_name=command['function'],
                                    description=command['description'],
                                    options=command.get('options', []))


if __name__ == '__main__':
    client = DiscordBot()
    bot_tasks.task_check_for_news.start(client)
    bot_tasks.task_check_for_data_updates.start(client)
    bot_tasks.task_update_pet_rescues.start(client)
    bot_tasks.task_update_dbl_stats.start(client)
    if TOKEN is not None:
        client.run(TOKEN)
    else:
        log.error('FATAL ERROR: DISCORD_TOKEN env var was not specified.')