Beispiel #1
0
    async def report_rss_events(self):
        await self.wait_until_ready()
        feed_response = None
        while not self.is_closed():
            try:
                for country in COUNTRIES.values():
                    latest_ts = DB.get_rss_feed_timestamp(country.id)
                    rss_link = f"https://www.erepublik.com/en/main/news/military/all/{country.link}/1/rss"
                    feed_response = requests.get(rss_link)
                    feed_response.raise_for_status()
                    for entry in reversed(
                            feedparser.parse(feed_response.text).entries):
                        entry_ts = time.mktime(entry["published_parsed"])
                        entry_link = entry["link"]
                        # Check if event timestamp is after latest processed event for country
                        if entry_ts > latest_ts:
                            DB.set_rss_feed_timestamp(country.id, entry_ts)
                            title = text = ""
                            msg = entry["summary"]
                            dont_send = False
                            for kind in events:
                                match = kind.regex.search(msg)
                                if match:
                                    values = match.groupdict()
                                    # Special case for Dictator/Liberation wars
                                    if "invader" in values and not values[
                                            "invader"]:
                                        values["invader"] = values["defender"]

                                    # Special case for resource concession
                                    if "link" in values:
                                        __link = values["link"]
                                        entry_link = __link if __link.startswith(
                                            "http"
                                        ) else f"https://www.erepublik.com{__link}"
                                        logger.debug(
                                            kind.format.format(**dict(
                                                match.groupdict(), **{
                                                    "current_country":
                                                    country.name
                                                })))
                                        logger.debug(entry_link)
                                    is_latvia = country.id == 71
                                    has_latvia = any("Latvia" in v
                                                     for v in values.values())
                                    if is_latvia or has_latvia:
                                        text = kind.format.format(**dict(
                                            match.groupdict(), **
                                            {"current_country": country.name}))
                                        title = kind.name
                                    else:
                                        dont_send = True
                                    break
                            else:
                                logger.warning(
                                    f"Unable to parse: {str(entry)}")
                                continue

                            if dont_send:
                                continue

                            entry_datetime = datetime.datetime.fromtimestamp(
                                entry_ts, pytz.timezone("US/Pacific"))
                            embed = discord.Embed(title=title,
                                                  url=entry_link,
                                                  description=text)
                            embed.set_author(
                                name=country.name,
                                icon_url=
                                f"https://www.erepublik.com/images/flags/L/{country.link}.gif"
                            )
                            embed.set_footer(
                                text=
                                f"{entry_datetime.strftime('%F %T')} (eRepublik time)"
                            )

                            logger.debug(f"Message sent: {text}")
                            for channel_id in DB.get_kind_notification_channel_ids(
                                    "events"):
                                await self.get_channel(channel_id).send(
                                    embed=embed)
            except Exception as e:
                logger.error("eRepublik event reader ran into a problem!",
                             exc_info=e)
                try:
                    with open(f"debug/{timestamp()}.rss", "w") as f:
                        f.write(feed_response.text)
                except (NameError, AttributeError):
                    logger.error("There was no Response object!", exc_info=e)
            finally:
                await asyncio.sleep((timestamp() // 300 + 1) * 300 -
                                    timestamp())
Beispiel #2
0
import feedparser
import pytz
import requests
from constants import events
from erepublik.constants import COUNTRIES

from dbot.base import ADMIN_ID, DB, DB_NAME, DEFAULT_CHANNEL_ID, DISCORD_TOKEN, PRODUCTION, logger
from dbot.bot_commands import bot
from dbot.utils import check_battles, get_battle_page, timestamp

if PRODUCTION:
    logger.warning("Production mode enabled!")
    logger.setLevel(logging.INFO)
    _ts = int(time.time())
    for c_id in COUNTRIES.keys():
        DB.set_rss_feed_timestamp(c_id, _ts)
    del _ts

logger.debug(
    f"Active configs:\nDISCORD_TOKEN='{DISCORD_TOKEN}'\nDEFAULT_CHANNEL_ID='{DEFAULT_CHANNEL_ID}'\nADMIN_ID='{ADMIN_ID}'\nDB_NAME='{DB_NAME}'"
)


class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # create the background task and run it in the background
        self.last_event_timestamp = timestamp()

    async def on_ready(self):
        logger.info("Client running")