예제 #1
0
    async def on_ready():
        if this.running:
            return

        this.running = True

        # Set the playing status
        if settings.NOW_PLAYING:
            print("Setting NP game", flush=True)
            await client.change_presence(
                status=discord.Status.online,
                activity=discord.Game(name=settings.NOW_PLAYING))
        print("Logged in!", flush=True)

        # Load all events
        print("Loading events...", flush=True)
        n_ev = 0
        for ev in BaseEvent.__subclasses__():
            event = ev()
            sched.add_job(event.run,
                          'interval', (client, ),
                          minutes=event.interval_minutes)
            n_ev += 1
        sched.start()
        print(f"{n_ev} events loaded", flush=True)
    async def on_ready():
        if this.running:
            return

        this.running = True

        if not os.path.isfile('watchlist.json'):
            watchlist = {'watchlist': []}
            with open('watchlist.json', 'w') as d:
                json.dump(watchlist, d)

        # Set the playing status
        if settings.NOW_PLAYING:
            print("Setting NP game", flush=True)
            await client.change_presence(activity=discord.Game(
                name=settings.NOW_PLAYING))
        print("Logged in!", flush=True)

        # Load all events
        print("Loading events...", flush=True)
        n_ev = 0
        for ev in BaseEvent.__subclasses__():
            event = ev()
            sched.add_job(event.run,
                          'interval', (client, ),
                          minutes=event.interval_minutes)
            n_ev += 1
        sched.start()
        print(f"{n_ev} events loaded", flush=True)
예제 #3
0
    async def on_ready():
        """on_ready may be called multiple times in the event of a reconnect,
        hence the running flag
        """
        if this.running:
            return

        this.running = True

        if settings.NOW_PLAYING:
            print("Setting NP game", flush=True)
            await client.change_presence(
                activity=discord.Game(name=settings.NOW_PLAYING)
            )
        print("Logged in!", flush=True)

        # Enter any messages for the bot to send on its login
        # Really useful for testing
        if testing:
            import datetime
            # TODO use last channel bot messaged in instead,
            #  or have global movie night channel
            #  These are hardcoded for chanel id #
            timestamp = datetime.datetime.now().strftime("%H:%M:%S")
            await client.get_channel(727105225722429440).send(f'Logged in at {timestamp}!')

        print("Loading events...", flush=True)
        n_ev = 0
        for ev in BaseEvent.__subclasses__():
            event = ev()
            sched.add_job(event.run, 'interval', (client,),
                          minutes=event.interval_minutes)
            n_ev += 1
        sched.start()
        print(f"{n_ev} events loaded", flush=True)
예제 #4
0
    async def on_ready():
        if this.running:
            return

        this.running = True

        game = discord.Game(name=settings.NOW_PLAYING)
        if settings.NOW_PLAYING:
            await client.change_presence(activity=game)
        n_ev = 0
        for ev in BaseEvent.__subclasses__():
            event = ev()
            sched.add_job(event.run,
                          'interval', (client, ),
                          minutes=event.interval_minutes)
            n_ev += 1
        sched.start()
        print("Done")
async def launch_event_loops(client):
    await get_connection_pool()
    print("Made sure we are connected to the DB")

    # Scheduler that will be used to manage events
    sched = get_scheduler()

    # add listeners to catch and format errors also to log
    def event_added(sched_event):
        job_name = sched.get_job(sched_event.job_id)

        # log the execution
        logger = logging.getLogger('events')
        logger.info("Event '%s' with ID '%s' has been added", job_name,
                    sched_event.job_id)

    sched.add_listener(event_added, EVENT_JOB_ADDED)

    def event_removed(sched_event):
        # log the execution
        logger = logging.getLogger('events')
        logger.info("Event with ID '%s' has been removed", sched_event.job_id)

    sched.add_listener(event_removed, EVENT_JOB_REMOVED)

    def event_submitted(sched_event):
        job_name = sched.get_job(sched_event.job_id)
        print(f"Running '{job_name}'")

    sched.add_listener(event_submitted, EVENT_JOB_SUBMITTED)

    def event_executed(sched_event):
        job_name = sched.get_job(sched_event.job_id)

        # log the execution
        logger = logging.getLogger('events')
        logger.info("Event '%s' successfully run", job_name)

    sched.add_listener(event_executed, EVENT_JOB_EXECUTED)

    def event_missed(sched_event):
        job_name = sched.get_job(sched_event.job_id)

        # log the execution
        logger = logging.getLogger('events')
        logger.warning("Event '%s' missed", job_name)

    sched.add_listener(event_missed, EVENT_JOB_MISSED)

    def event_error(sched_event):
        job_name = sched.get_job(sched_event.job_id)

        # log the execution
        logger = logging.getLogger('events')
        logger.error("Event '%s' failed - Error '%s' - Traceback: \n%s",
                     job_name, sched_event.exception, sched_event.traceback)

    sched.add_listener(event_error, EVENT_JOB_ERROR)

    print("Loading events...")
    for ev in BaseEvent.__subclasses__():
        event = ev()

        # check the type of job and schedule acordingly
        if event.scheduler_type == "interval":
            sched.add_job(event.run,
                          'interval', (client, ),
                          minutes=event.interval_minutes,
                          jitter=60)
        elif event.scheduler_type == "cron":
            sched.add_job(event.run,
                          'cron', (client, ),
                          day_of_week=event.dow_day_of_week,
                          hour=event.dow_hour,
                          minute=event.dow_minute)
        elif event.scheduler_type == "date":
            sched.add_job(event.run,
                          'date', (client, ),
                          run_date=event.interval_minutes)
        else:
            print(f"Failed to load event {event}")
    jobs = sched.get_jobs()
    print(f"{len(jobs)} events loaded")

    # load the lfg events
    lfg_events = await select_lfg_datetimes_and_users()
    for lfg_event in lfg_events:
        guild = client.get_guild(lfg_event["guild_id"])
        if guild:
            timedelta = datetime.timedelta(minutes=10)
            sched.add_job(notify_about_lfg_event_start,
                          'date', (client, guild, lfg_event["id"], timedelta),
                          run_date=lfg_event["start_time"] - timedelta,
                          id=str(lfg_event["id"]))
    print(f"{len(sched.get_jobs()) - len(jobs)} LFG events loaded")

    print("Startup complete!")

    # Set the playing status
    await update_status(client)