Beispiel #1
0
    async def _reminders_add(self,
                             ctx: SlashContext,
                             when: str,
                             content: str,
                             timezone: str = None) -> None:
        if not self.bot.init_done:
            await ctx.send(
                'Sorry, the bot is not yet loaded.. Try again in a few moments'
            )
            return

        if not timezone:
            timezone = self.bot.bot_config.get_user_setting(
                ctx.author.id, 'timezone', default=None) or 'UTC'

        if not Timezone.is_valid_timezone(timezone):
            await ctx.send(
                f'Invalid timezone provided "{timezone}".. :slight_frown:')
            return

        user_tz = Timezone.build(timezone)

        fuzzy_when = FuzzyTime.build(provided_when=when, use_timezone=user_tz)
        reminder = Reminder.build(fuzzy_when,
                                  member=ctx.author,
                                  channel=ctx.channel,
                                  content=content)  # type: ignore[arg-type]

        reminder.store(self.bot.redis_helper)
        reminder_md = cast(discord.Embed,
                           reminder.as_markdown(
                               ctx.author,
                               as_embed=True))  # type: ignore[arg-type]
        logger.info(
            f'Successfully created a new reminder for "{ctx.author.name}" via slash command'
        )
        logger.debug(f'Slash Command Reminder Reminder:\n{reminder.dump()}')

        self.bot.scheduler.add_job(self._process_reminder,
                                   kwargs={
                                       'reminder': reminder,
                                       'added_at': datetime.now()
                                   },
                                   trigger='date',
                                   run_date=reminder.trigger_dt,
                                   id=reminder.redis_name)
        logger.info(
            f'Scheduled new reminder job at "{reminder.trigger_dt.ctime()}"')

        await ctx.send(
            f'Adding new reminder for `{fuzzy_when.resolved_time.ctime()}` :wink:',
            embed=reminder_md)
Beispiel #2
0
    async def add_reminder(self, ctx: commands.Context,
                           fuzzy_when: FuzzyTimeConverter, *,
                           content: str) -> None:
        dt_now = datetime.now()
        reminder = Reminder.build(fuzzy_when,
                                  member=ctx.author,
                                  channel=ctx.channel,
                                  content=content)  # type: ignore[arg-type]

        reminder.store(self.bot.redis_helper)
        reminder_md = cast(
            discord.Embed,
            reminder.as_markdown(ctx.author, ctx.channel,
                                 as_embed=True))  # type: ignore[arg-type]
        logger.info(
            f'Successfully created a new reminder for "{ctx.author.name}"')
        logger.debug(f'Reminder:\n{reminder.dump()}')

        confirm = await ConfirmMenu(
            f'Create reminder at `{reminder.trigger_dt.ctime()}` for `{content}`?'
        ).prompt(ctx)

        if not confirm:
            logger.info(
                f'Canceling reminder for {ctx.author.name} based on prompt response'
            )
            return

        self.bot.scheduler.add_job(self._process_reminder,
                                   kwargs={
                                       'reminder': reminder,
                                       'added_at': dt_now
                                   },
                                   trigger='date',
                                   run_date=reminder.trigger_dt,
                                   id=reminder.redis_name)
        logger.info(
            f'Scheduled new reminder job at "{reminder.trigger_dt.ctime()}"')

        await ctx.send(
            f'Adding new reminder for {ctx.author.mention} at {reminder.trigger_dt.ctime()}`',
            embed=reminder_md)
Beispiel #3
0
def reminders():
    if request.method == 'GET':
        exclude = [ex_attr.lower() for ex_attr in request.args.get('exclude', '').split(',')]
        member_id = request.args.get('member_id', None)
        channel_id = request.args.get('channel_id', None)

        rems = []

        for r_key in current_app.redis_helper.keys(redis_id='reminders', use_encoding='utf-8'):
            rem = Reminder.fetch(current_app.redis_helper, redis_id='reminders', redis_name=r_key)

            if 'complete' in exclude and rem.is_complete:
                continue

            if 'notified' in exclude and rem.user_notified:
                continue

            if member_id and int(member_id) != rem.member_id:
                continue

            if channel_id and int(channel_id) != rem.channel_id:
                continue

            rems.append(rem.as_dict())

        msg_out = 'No reminders found' if not rems else f'Found #{len(rems)} reminders'
        return jsonify({'message': msg_out, 'count': len(rems), 'is_error': False, 'data': rems})

    # Handle POST / PUT request
    form_dict = request.form.to_dict()
    req_attrs = ['when', 'content', 'member_id', 'member_name']

    if 'channel_id' in request.form:
        req_attrs += ['channel_id', 'channel_name']

    for attr in req_attrs:
        if attr not in request.form:
            raise MinderWebError(f'No value for "{attr}" provided when attemptingn to create reminder', status_code=400, payload=form_dict)

    opts = {attr: request.form.get(attr) for attr in req_attrs}

    for o_name, o_val in opts.items():
        if not o_val:
            raise MinderWebError(f'No value provided for "{attr}" (value: "{o_val}")', status_code=400, payload=form_dict)

        if o_name.endswith('_id'):
            opts[o_name] = int(o_val)

    opts['timezone'] = request.form.get('timezone', None)
    when = opts['when']

    member_dict = {'id': opts['member_id'], 'name': opts['member_name']}

    channel_dict = {'id': opts['channel_id'], 'name': opts['channel_name']} if 'channel_id' in opts else None

    try:
        fuz_time = FuzzyTime.build(when, use_timezone=opts['timezone'])
    except Exception as ex:
        raise MinderWebError(f'Error parsing fuzzy timestamp for "{when}": {ex}', status_code=400, payload=form_dict, base_exception=ex) from ex

    try:
        rem = Reminder.build(fuz_time, member=member_dict, content=opts['content'], channel=channel_dict, use_timezone=opts['timezone'])
    except Exception as ex:
        raise MinderWebError(f'Error building new reminder for "{when}": {ex}', status_code=500, payload=form_dict, base_exception=ex) from ex

    try:
        rem.store(current_app.redis_helper)
    except Exception as ex:
        raise MinderWebError(f'Error storing new reminder for "{when}" in Redis: {ex}', status_code=500, payload=form_dict, base_exception=ex) from ex

    msg_out = f'Successfully built new reminder for "{when}" at "{rem.trigger_dt.ctime()}"'
    return jsonify({'message': msg_out, 'is_error': False, 'data': {'reminder': rem.as_dict()}})
Beispiel #4
0
def fake_dm_reminder(fake_member, fake_dm_channel):
    return Reminder.build(trigger_time='in 5 minutes', member=fake_member, content='pytest test DM reminder', channel=fake_dm_channel)