Exemple #1
0
	def save(self,current_user,action,*args,**kwargs):
		"""
		Save form
		"""
		if not self.instance.pk:
			self.instance.created_by = current_user
		self.instance.updated_by = current_user
		self.instance.action = action
		action.follow_up_at = self.instance.follow_up_at
		if self.instance.status:
			action.status = self.instance.status
		action.save()
		action_comment = super(ActionCommentForm,self).save(*args,**kwargs)
		action_comment.save()

		if action.employee.user == current_user:
			self.instance.sendCommentNotification(1, action.employee.manager.user, current_user)
		else:
			self.instance.sendCommentNotification(2, action.employee.user, current_user)

		if self.cleaned_data['reminder_at']:

			at = time(0, 0, 0, 0, tzinfo=utc)
			follow_up_at = None

			if 'follow_up_at' in self.cleaned_data:
				follow_up_at = datetime.combine(self.cleaned_data['follow_up_at'], at)

			Reminder.create(
				ReminderTemplate.ID_CONTRIBUTION_KEY,
				send_date=datetime.combine(self.cleaned_data['reminder_at'], at),
				date=follow_up_at,
				comment=self.cleaned_data['text'],
				created_by=current_user
			)
Exemple #2
0
def init_reminders(project):

    # Add basic reminders to project.
    # Initial contact reminder
    Reminder(
        project=project,
        description="Send initial email",
        reminder="custom",
        due_date= project.startdate + relativedelta(months=1),
        state="Open"
    ).save()

    # Dmp upload reminder
    Reminder(
        project=project,
        description="Make and upload DMP",
        reminder="custom",
        due_date= project.startdate + relativedelta(months=3),
        state="Open"
    ).save()

    # Project nearing end date, check for data
    Reminder(
        project=project,
        description="Project nearing end date",
        reminder="custom",
        due_date= project.enddate + relativedelta(months=-3),
        state="Open"
    ).save()
Exemple #3
0
    def __init__(self, bot):
        super().__init__(bot)
        self.scheduler = TimedScheduler(prefer_utc=True)
        self.scheduler.start()

        Reminder.inject_bot(bot)

        super(AinitMixin).__init__()
Exemple #4
0
    def import_action_triggered(self):
        '''Import json to db'''

        dbFile = QtGui.QFileDialog.getOpenFileName(
            parent=None,
            caption="Import database to a file",
            directory=".",
            filter="QTierna JSON (*.json)")
        if dbFile[0]:
            try:
                with open(dbFile[0], "r") as jsonfile:
                    jdata = json.load(jsonfile)
                    # Clear db
                    db_drop_all_tables()
                    db_create_tables()
                    # Categories
                    categories = jdata['categories']
                    category_instances = []
                    with session_scope() as session:
                        for category in categories:
                            category_instance = Category(
                                category_id=category['category_id'],
                                category_name=category['category_name'])
                            category_instances.append(category_instance)
                            session.add(category_instance)
                            session.commit()
                        # Reminders
                        reminders = jdata['reminders']
                        for reminder in reminders:
                            reminder_categories = filter(
                                lambda c: c.category_id in reminder[
                                    'category_ids'], category_instances)
                            reminder_instance = Reminder(
                                reminder_id=reminder['reminder_id'],
                                due=reminder['due'],
                                complete=reminder['complete'],
                                note=reminder['note'])
                            reminder_instance.categories = reminder_categories
                            session.add(reminder_instance)
                    self.refresh_table()
                    self.refresh_tree()
                    with session_scope() as session:
                        category_count = session.query(Category).count()
                        reminder_count = session.query(Reminder).count()
                    msg = (
                        "Successfully imported %i reminders and %i categories from file\r\n%s"
                        % (reminder_count, category_count,
                           (QtCore.QDir.toNativeSeparators(dbFile[0]))))
                    QtGui.QMessageBox.information(self, __appname__, msg)
            except Exception as importexc:
                QtGui.QMessageBox.critical(
                    self, __appname__,
                    "Error importing file, error is\r\n" + str(importexc))
                return
Exemple #5
0
def create_mention(**kwargs):
    receiver = Member.getMemberByUsername(kwargs['username'])
    if receiver:
        kwargs.update(receiver=receiver)
        reminder = Reminder.create(**kwargs)
    else:
        logging.error("no member found")
Exemple #6
0
def edit_dayofweek_body(message, reminder_id):
    session = Session()
    new_day_of_week = message.text
    days = [
        'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday',
        'sunday', 'all'
    ]
    if new_day_of_week not in days:
        bot.send_message(message.chat.id, 'Sorry, incorrect input')
        edit_dayofweek(message.chat.id, reminder_id)
    else:
        reminder = session.query(Reminder).filter(
            Reminder.reminder_id == reminder_id)[0]
        reminder.flag_delete = True
        session.commit()
        reminder_new = Reminder(subgoal_id=reminder.subgoal_id,
                                dayofweek=new_day_of_week,
                                start=reminder.start,
                                text=reminder.text,
                                chat_id=message.chat.id,
                                flag_set=False,
                                flag_delete=False,
                                flag_once=False)
        session.add(reminder_new)
        session.commit()
        bot.send_message(message.chat.id, f"New reminder: {str(reminder_new)}")
    session.close()
Exemple #7
0
def add_reminder_body(message, goal, freq, t, f):
    time = ''
    text = ''
    dayofweek = ''
    if freq == 'week':
        if is_correct_week_reminder(message.text):
            dayofweek, time, text = parse_week_reminder(message.text)
        else:
            add_reminder(goal, message.chat.id, t, f, freq)
    if freq == 'day':
        dayofweek = 'all'
        if is_correct_day_reminder(message.text):
            time, text = parse_day_reminder(message.text)
        else:
            add_reminder(goal, message.chat.id, t, f, freq)
    if time and text and dayofweek:
        session = Session()
        reminder = Reminder(subgoal_id=goal.subgoal_id,
                            dayofweek=dayofweek,
                            start=time,
                            text=text,
                            chat_id=message.chat.id,
                            flag_set=False,
                            flag_delete=False,
                            flag_once=False)
        session.add(reminder)
        session.commit()
        session.close()
        bot.send_message(message.chat.id, "Reminder successfully added!")
Exemple #8
0
    async def add(self, ctx, *, args: ReminderConverter):
        """
        Adds a new reminder.

        Example usage:
        `{prefix}remind in 3 hours to do the laundry`
        `{prefix}remind 15-06-20 at 6pm KST to Irene & Seulgi debut`
        `{prefix}remind in 6 minutes 30 seconds to eggs`
        """
        when, what = args
        parsed_date = parse_date(when)

        now = pendulum.now("UTC")
        diff = parsed_date.diff_for_humans(now, True)

        async with self.bot.Session() as session:
            reminder = Reminder(_user=ctx.author.id,
                                due=parsed_date,
                                content=what)
            session.add(reminder)
            await session.flush()
            self.scheduler.schedule(self.remind_user(reminder.reminder_id),
                                    parsed_date)
            await session.commit()

        await ctx.send(
            f"I'll remind you on `{parsed_date.to_cookie_string()}` (in {diff}): `{what}`."
        )
Exemple #9
0
def remindme(db_session, message, *args):
    reply = ''
    if len(args) == 0:
        # TODO: make this granularity set-able
        return [
            '!remindme <date/time> <message>\nFormat (brackets optional, either date, time or both):\n** - (dd/mm(/yy(yy))) (hh:mm(:ss))**\nGranularity set to 10s.'
        ]
    elif len(args) == 1:
        return ['Missing argument.']
    else:
        date = None
        time = None
        if re.match(r'^[0-3]?[0-9]/[01]?[0-9](/[0-9][0-9]([0-9][0-9])?)?$',
                    args[0]):
            # got a date
            date = args[0]
        i = 0 if date == None else 1

        if re.match(r'[0-2]?[0-9]:[0-5]?[0-9](:[0-5]?[0-9])?', args[i]):
            time = args[i]

        if time == None and date == None:
            return ['Invalid time and date format.']

        date_str = ''
        if not date == None:
            date_str += date + ' '
        if not time == None:
            date_str += time
        date_str = date_str.strip()

        valid_date = None
        try:
            valid_date = dateutil.parser.parse(date_str, dayfirst=True)
        except ValueError:
            return ['Date doesn\'t exist.']

        if time == None or date == None:
            content = ' '.join(args[1:])
        else:
            content = ' '.join(args[2:])

        user = db_session.query(User).filter(
            User.uid == message.author.id).first()
        channel_id = message.channel.id
        trigger_time = valid_date
        # used to constantly message a person about it until they say otherwise
        persistent = False

        reminder = Reminder(user_id=user.id,
                            channel_id=channel_id,
                            trigger_time=trigger_time,
                            content=content,
                            persistent=persistent)
        db_session.add(reminder)
        db_session.commit()
        return ['Added reminder on ' + str(valid_date) + '.']
Exemple #10
0
    async def add(self, ctx: Context, *args: clean_content):
        if not args:
            await ctx.send("You're missing a time and a message!")
        else:
            trigger_time = parse_time(args[0])
            now = datetime.now()
            if not trigger_time:
                await ctx.send("Incorrect time format, please see help text.")
            elif trigger_time < now:
                await ctx.send("That time is in the past.")
            else:
                # HURRAY the time is valid and not in the past, add the reminder
                display_name = get_name_string(ctx.message)

                # set the id to a random value if the author was the bridge bot, since we wont be using it anyways
                # if ctx.message.clean_content.startswith("**<"): <---- FOR TESTING
                if user_is_irc_bot(ctx):
                    author_id = 1
                    irc_n = display_name
                else:
                    author_id = (
                        db_session.query(User)
                        .filter(User.user_uid == ctx.author.id)
                        .first()
                        .id
                    )
                    irc_n = None

                if len(args) > 1:
                    rem_content = " ".join(args[1:])
                    trig_at = trigger_time
                    trig = False
                    playback_ch_id = ctx.message.channel.id
                    new_reminder = Reminder(
                        user_id=author_id,
                        reminder_content=rem_content,
                        trigger_at=trig_at,
                        triggered=trig,
                        playback_channel_id=playback_ch_id,
                        irc_name=irc_n,
                    )
                    db_session.add(new_reminder)
                    try:
                        db_session.commit()
                        await ctx.send(
                            f"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {CONFIG.REMINDER_SEARCH_INTERVAL} seconds)."
                        )
                    except (ScalarListException, SQLAlchemyError) as e:
                        db_session.rollback()
                        logging.error(e)
                        await ctx.send(f"Something went wrong")
                else:
                    await ctx.send("Please include some reminder text!")
Exemple #11
0
    async def add(self, ctx: Context, *args: clean_content):
        if not args:
            await ctx.send("You're missing a time and a message!")
        else:
            trigger_time = parse_time(args[0])
            now = datetime.now()
            if not trigger_time:
                await ctx.send("Incorrect time format, please see help text.")
            elif trigger_time < now:
                await ctx.send("That time is in the past.")
            else:
                # HURRAY the time is valid and not in the past, add the reminder
                display_name = get_name_string(ctx.message)

                # set the id to a random value if the author was the bridge bot, since we wont be using it anyways
                # if ctx.message.clean_content.startswith("**<"): <---- FOR TESTING
                if ctx.message.author.id == CONFIG[
                        'UWCS_DISCORD_BRIDGE_BOT_ID']:
                    author_id = 1
                    irc_n = display_name
                else:
                    author_id = db_session.query(User).filter(
                        User.user_uid == ctx.message.author.id).first().id
                    irc_n = None

                if len(args) > 1:
                    rem_content = " ".join(args[1:])
                    trig_at = trigger_time
                    trig = False
                    playback_ch_id = ctx.message.channel.id
                    new_reminder = Reminder(user_id=author_id,
                                            reminder_content=rem_content,
                                            trigger_at=trig_at,
                                            triggered=trig,
                                            playback_channel_id=playback_ch_id,
                                            irc_name=irc_n)
                    db_session.add(new_reminder)
                    db_session.commit()
                    await ctx.send(
                        f'Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {CONFIG["REMINDER_SEARCH_INTERVAL"]} seconds).'
                    )
                else:
                    await ctx.send("Please include some reminder text!")
Exemple #12
0
    async def add(self, ctx: Context, trigger_time: DateTimeConverter, *,
                  reminder_content: str):
        now = datetime.now()
        if not trigger_time:
            await ctx.send("Incorrect time format, please see help text.")
        elif trigger_time < now:
            await ctx.send("That time is in the past.")
        else:
            # HURRAY the time is valid and not in the past, add the reminder
            display_name = get_name_string(ctx.message)

            # set the id to a random value if the author was the bridge bot, since we wont be using it anyways
            # if ctx.message.clean_content.startswith("**<"): <---- FOR TESTING
            if user_is_irc_bot(ctx):
                author_id = 1
                irc_n = display_name
            else:
                author_id = get_database_user(ctx.author).id
                irc_n = None

            trig_at = trigger_time
            trig = False
            playback_ch_id = ctx.message.channel.id
            new_reminder = Reminder(
                user_id=author_id,
                reminder_content=reminder_content,
                trigger_at=trig_at,
                triggered=trig,
                playback_channel_id=playback_ch_id,
                irc_name=irc_n,
            )
            db_session.add(new_reminder)
            try:
                db_session.commit()
                await ctx.send(
                    f"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {precisedelta(CONFIG.REMINDER_SEARCH_INTERVAL, minimum_unit='seconds')})."
                )
            except (ScalarListException, SQLAlchemyError) as e:
                db_session.rollback()
                logging.exception(e)
                await ctx.send(f"Something went wrong")
Exemple #13
0
def edit_time_body(message, reminder_id):
    session = Session()
    new_time = message.text
    if not correct_time(new_time):
        bot.send_message(message.chat.id,
                         'Sorry, time must be in format hh:mm')
        edit_time(message.chat.id, reminder_id)
    else:
        reminder = session.query(Reminder).filter(
            Reminder.reminder_id == reminder_id)[0]
        reminder.flag_delete = True
        session.commit()
        reminder_new = Reminder(subgoal_id=reminder.subgoal_id,
                                dayofweek=reminder.dayofweek,
                                start=new_time,
                                text=reminder.text,
                                chat_id=message.chat.id,
                                flag_set=False,
                                flag_delete=False,
                                flag_once=False)
        session.add(reminder_new)
        session.commit()
        bot.send_message(message.chat.id, f"New reminder: {str(reminder_new)}")
    session.close()
 def accept(self, edit=False):
     '''
     Save the new/edited Reminder if valid
     '''
     if self.is_valid():
         try:
             category_names = []
             if self.categoriesDlg is not None:
                 # User edited categories we must update
                 category_names = self.categoriesDlg._get_selected_categories(
                 )
             logger.debug('Selected categories were %s' % category_names)
             with session_scope() as session:
                 category_instances = []
                 if category_names:
                     category_instances = session.query(Category).filter(
                         Category.category_name.in_(category_names)).all()
                 if self.edit_reminder_id:
                     reminder = session.query(Reminder).get(
                         int(self.edit_reminder_id))
                 else:
                     reminder = Reminder()
                 reminder.due = self._get_reminder_utc_datetime_str()
                 reminder.complete = self._()
                 reminder.note = self._get_reminder_note()
                 if category_instances:
                     reminder.categories = category_instances
                 session.add(reminder)
         except exc.IntegrityError as int_exc:
             # Rollback already handled by scoped_session ctx manager
             logger.error(int_exc)
             QtGui.QMessageBox.warning(
                 self, "Already exists warning",
                 unicode('This reminder already exists'))
             return
         else:
             # All good, accept
             QtGui.QDialog.accept(self)
Exemple #15
0
def submitcircle(request):
    new_member = get_current_member(request)
    new_circle = get_current_circle(request)

    count = 2
    posted_members = {}

    custom_errors = ""

    while count <= settings.CIRCLE_MAX_SIZE:
        member_contact = {}

        current_name = request.POST.get("name_" + str(count), None)
        current_contact = request.POST.get("contact_" + str(count), None)

        if (current_name):
            if (current_contact):
                # Check to see if current contact info is valid phone or email
                if is_phone(current_contact):
                    member_contact["contact_type"] = "phone"

                if is_email(current_contact):
                    member_contact["contact_type"] = "email"

                if not is_phone(current_contact) and not is_email(current_contact):
                    # Bad data error
                    custom_errors += "<li>contact_" + str(count) + " must be either a valid phone number OR email</li>"

                member_contact["contact_info"] = current_contact

                posted_members[current_name] = member_contact
            else:
                # Missing contact data error
                custom_errors += "<li>name_" + str(count) + " is present but contact_" + str(count) + " is missing</li>"
        else:
            if len(posted_members) < (settings.CIRCLE_MIN_SIZE - 1):
                # Missing name data error
                custom_errors += "<li>name_" + str(count) + " is missing</li>"

        count += 1

    # Check to see if we have minimum more members added
    if len(posted_members) < (settings.CIRCLE_MIN_SIZE - 1):
        custom_errors += "<li>You need at least " + str(settings.CIRCLE_MIN_SIZE) + " members (including yourself) in your circle</li>"

    if custom_errors != "":
        custom_errors = format_html("<p><ul>{}</ul></p>",
                                    mark_safe(custom_errors))

        # If there are any errors, kick out and display them
        context = {"member":new_member, "num_range_str":settings.CONTACT_RANGE_STR, "custom_errors":custom_errors, }
        return render(request, "circly/network.html", context)

    for each_member in posted_members.keys():
        # Create new members and add to the circle
        if (posted_members[each_member]["contact_type"] == "email"):
            next_member = Member(circle=new_circle,
                                 circle_owner=False,
                                 member_name=each_member,
                                 member_email=posted_members[each_member]["contact_info"],
                                 member_created_date=timezone.now(), )
        elif (posted_members[each_member]["contact_type"] == "phone"):
            new_phone = phonenumbers.parse(posted_members[each_member]["contact_info"], "US")
            new_phone = phonenumbers.format_number(new_phone, phonenumbers.PhoneNumberFormat.E164)

            next_member = Member(circle=new_circle,
                                 circle_owner=False,
                                 member_name=each_member,
                                 member_phone=new_phone,
                                 member_created_date=timezone.now(), )

        next_member.save()

        # Create invite code with short link for profile sign up
        invite_code = hash_code(posted_members[each_member]["contact_info"])

        invite_url = "http://www.circly.org/invite/" + invite_code
        new_short_url = random_bitly(invite_url)

        invite = Invitation(member=next_member,
                            invite_code=invite_code, 
                            invite_short_url=new_short_url, 
                            invite_created_date=timezone.now(),
                            invite_send_date=timezone.now())
        invite.save()

        # Create reminders for all new members to join the circle
        remind = Reminder(member=next_member,
                          reminder_subject=new_circle.circle_owner_name() + " would like you to join their circle of support",
                          reminder_message="Hey " + each_member + ", visit " + new_short_url + " to fill in your profile and join a circle of preventive care.",
                          reminder_created_date=timezone.now(),
                          reminder_send_date=timezone.now(), )
        remind.save()

    if new_member.member_email:
        owner_hash = hash_code(new_member.member_email)

    if new_member.member_phone:
        owner_hash = hash_code(new_member.member_phone)

    dashboard_url = "http://www.circly.org/dashboard/" + owner_hash
    new_short_dashboard_url = random_bitly(dashboard_url)

    new_circle.circle_short_url = new_short_dashboard_url
    new_circle.save()

    set_member_and_circle(request, new_circle, new_member)

    return HttpResponseRedirect(reverse("connect:dashboard", 
                                        kwargs={"owner_hash":owner_hash}))
Exemple #16
0
    async def create_reminder(self, message: discord.Message, location: int, text: str, time: int, interval: int=None, method: str='natural') -> ReminderInformation:
        uid: str = self.create_uid(location, message.id) # create a UID

        nudge_channel: ChannelNudge = session.query(ChannelNudge).filter(ChannelNudge.channel == location).first() # check if it's being nudged

        if nudge_channel is not None:
            time += nudge_channel.time

        if time > unix_time() + MAX_TIME:
            return ReminderInformation(CreateReminderResponse.LONG_TIME)

        elif time < unix_time():
            time = int(unix_time()) + 1
            # push time to be 'now'

        url: typing.Optional[str] = None
        channel: typing.Optional[discord.Channel] = None

        if message.guild is not None:
            channel = message.guild.get_channel(location)

            if channel is not None: # if not a DM reminder

                hooks = [x for x in await channel.webhooks() if x.user.id == self.user.id]
                hook = hooks[0] if len(hooks) > 0 else await channel.create_webhook(name='Reminders')
                url = hook.url

                restrict = session.query(RoleRestrict).filter(RoleRestrict.role.in_([x.id for x in message.author.roles]))

            else:
                member = message.guild.get_member(location)

                if member is None:
                    return ReminderInformation(CreateReminderResponse.INVALID_TAG)

                else:
                    await member.create_dm()
                    channel = member.dm_channel

        else:
            channel = message.channel

        if interval is not None:
            if MIN_INTERVAL > interval:
                return ReminderInformation(CreateReminderResponse.SHORT_INTERVAL)

            elif interval > MAX_TIME:
                return ReminderInformation(CreateReminderResponse.LONG_INTERVAL)

            else:
                reminder = Reminder(
                    uid=uid,
                    message=text,
                    channel=channel.id,
                    time=time,
                    webhook=url,
                    enabled=True,
                    position=0,
                    method=method)
                session.add(reminder)
                session.commit()

                i = Interval(reminder=reminder.id, period=interval, position=0)
                session.add(i)
                session.commit()

        else:
            r = Reminder(
                uid=uid,
                message=text,
                channel=channel.id,
                time=time,
                webhook=url,
                enabled=True,
                position=None,
                method=method)
            session.add(r)
            session.commit()

        return ReminderInformation(CreateReminderResponse.OK, channel=channel, time=time)
Exemple #17
0
    async def interval(self, message, stripped, server):
        if server is None:
            return

        if not self.get_patrons(message.author.id, level=1):
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(
                    server)['interval']['donor'].format(prefix=server.prefix)))
            return

        args = message.content.split(' ')
        args.pop(0)  # remove the command item

        if len(args) < 3:
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(server)['interval']
                ['no_argument'].format(prefix=server.prefix)))
            return

        scope = message.channel.id
        pref = '#'

        if args[0].startswith('<'):  # if a scope is provided

            scope, pref = self.parse_mention(message, args[0], server)
            if scope is None:
                await message.channel.send(
                    embed=discord.Embed(description=self.get_strings(server)
                                        ['remind']['invalid_tag']))
                return

            args.pop(0)

        while args[0] == '':
            args.pop(0)

        msg_time = self.format_time(args[0], server)

        if msg_time == None:
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(server)['remind']['invalid_time'])
                                       )
            return

        args.pop(0)

        while args[0] == '':
            args.pop(0)

        msg_interval = self.format_time(args[0], message.guild.id)

        if msg_interval == None:
            await message.channel.send(
                embed=discord.Embed(description=self.get_strings(server)
                                    ['interval']['invalid_interval']))
            return

        msg_interval -= time.time()
        msg_interval = round(msg_interval)

        if msg_interval < 8:
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(server)['interval']['8_seconds']))
            return

        args.pop(0)

        msg_text = ' '.join(args)

        if self.length_check(message, msg_text) is not True:
            if self.length_check(message, msg_text) == '150':
                await message.channel.send(embed=discord.Embed(
                    description=self.get_strings(server)['remind']
                    ['invalid_chars'].format(len(msg_text))))

            elif self.length_check(message, msg_text) == '2000':
                await message.channel.send(
                    embed=discord.Embed(description=self.get_strings(server)
                                        ['remind']['invalid_chars_2000']))

            return

        if pref == '#':
            if not self.perm_check(message, server):
                await message.channel.send(embed=discord.Embed(
                    description=self.get_strings(server)['remind']['no_perms'])
                                           )
                return

        reminder = Reminder(time=msg_time,
                            interval=msg_interval,
                            channel=scope,
                            message=msg_text)

        await message.channel.send(embed=discord.Embed(
            description=self.get_strings(server)['interval']['success'].format(
                pref, scope, round(msg_time - time.time()))))

        session.add(reminder)
        session.commit()

        print('Registered a new interval for {}'.format(message.guild.name))
Exemple #18
0
    async def remind(self, message, stripped, server):
        if server is None:
            return

        args = stripped.split(' ')

        if len(args) < 2:
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(server)['remind']
                ['no_argument'].format(prefix=server.prefix)))
            return

        scope = message.channel.id
        pref = '#'

        if args[0].startswith('<'):  # if a scope is provided

            scope, pref = self.parse_mention(message, args[0], server)
            if scope is None:
                await message.channel.send(
                    embed=discord.Embed(description=self.get_strings(server)
                                        ['remind']['invalid_tag']))
                return

            args.pop(0)

        try:
            while args[0] == '':
                args.pop(0)

            msg_time = self.format_time(args[0], server)
        except ValueError:
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(server)['remind']['invalid_time'])
                                       )
            return

        if msg_time is None:
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(server)['remind']['invalid_time'])
                                       )
            return

        args.pop(0)

        msg_text = ' '.join(args)

        if self.count_reminders(scope) > 5 and not self.get_patrons(
                message.author.id):
            await message.channel.send(embed=discord.Embed(
                description=self.get_strings(server)['remind']
                ['invalid_count'].format(prefix=server.prefix)))
            return

        if self.length_check(message, msg_text) is not True:
            if self.length_check(message, msg_text) == '150':
                await message.channel.send(embed=discord.Embed(
                    description=self.get_strings(server)['remind']
                    ['invalid_chars'].format(len(msg_text),
                                             prefix=server.prefix)))

            elif self.length_check(message, msg_text) == '2000':
                await message.channel.send(
                    embed=discord.Embed(description=self.get_strings(server)
                                        ['remind']['invalid_chars_2000']))

            return

        if pref == '#':
            if not self.perm_check(message, server):
                await message.channel.send(embed=discord.Embed(
                    description=self.get_strings(server)['remind']
                    ['no_perms'].format(prefix=server.prefix)))
                return

        reminder = Reminder(time=msg_time, channel=scope, message=msg_text)

        await message.channel.send(embed=discord.Embed(
            description=self.get_strings(server)['remind']['success'].format(
                pref, scope, round(msg_time - time.time()))))

        session.add(reminder)
        session.commit()

        print('Registered a new reminder for {}'.format(message.guild.name))
Exemple #19
0
    async def interval(self, message, stripped, server):

        if not self.get_patrons(message.author.id, level=1):
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'interval/donor').format(prefix=server.prefix)))
            return

        args = message.content.split(' ')
        args.pop(0) # remove the command item

        if len(args) < 3:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'interval/no_argument').format(prefix=server.prefix)))
            return

        scope = message.channel.id
        pref = '#'

        if args[0].startswith('<'): # if a scope is provided

            scope, pref = self.parse_mention(message, args[0], server)
            if scope is None:
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_tag')))
                return

            args.pop(0)

        while args[0] == '':
            args.pop(0)

        msg_time = self.format_time(args[0], server)

        if msg_time is None or msg_time - time.time() > 1576800000:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_time')))
            return

        args.pop(0)

        while args[0] == '':
            args.pop(0)

        msg_interval = self.format_time(args[0], message.guild.id)

        if msg_interval == None or msg_interval > 1576800000:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'interval/invalid_interval')))
            return

        msg_interval -= time.time()
        msg_interval = round(msg_interval)

        if msg_interval < 8:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'interval/8_seconds')))
            return

        args.pop(0)

        msg_text = ' '.join(args)

        if self.length_check(message, msg_text) is not True:
            if self.length_check(message, msg_text) == '150':
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_chars').format(len(msg_text))))

            elif self.length_check(message, msg_text) == '2000':
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_chars_2000')))

            return

        webhook = ''

        if pref == '#':
            if not self.perm_check(message, server):
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/no_perms')))
                return

            c = message.guild.get_channel(scope)

            for hook in await c.webhooks():
                if hook.user.id == self.user.id:
                    webhook = hook.url
                    break

            if webhook == '':
                w = await c.create_webhook(name='Reminders')
                webhook = w.url


        reminder = Reminder(time=msg_time, interval=msg_interval, channel=scope, message=msg_text, webhook=webhook)

        await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'interval/success').format(pref, scope, round(msg_time - time.time()))))

        session.add(reminder)
        session.commit()

        logger.info('Registered a new interval for {}'.format(message.guild.name))
Exemple #20
0
    async def remind(self, message, stripped, server):

        webhook = ''

        args = stripped.split(' ')

        if len(args) < 2:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/no_argument').format(prefix=server.prefix)))
            return

        scope = message.channel.id
        pref = '#'

        if args[0].startswith('<'): # if a scope is provided

            scope, pref = self.parse_mention(message, args[0], server)
            if scope is None:
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_tag')))
                return

            args.pop(0)

        try:
            while args[0] == '':
                args.pop(0)

            msg_time = self.format_time(args[0], server)
        except ValueError:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_time')))
            return

        if msg_time is None or msg_time - time.time() > 1576800000:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_time')))
            return

        args.pop(0)

        msg_text = ' '.join(args)

        if self.length_check(message, msg_text) is not True:
            if self.length_check(message, msg_text) == '150':
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_chars').format(len(msg_text), prefix=server.prefix)))

            elif self.length_check(message, msg_text) == '2000':
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_chars_2000')))

            return

        if pref == '#':
            if not self.perm_check(message, server):
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/no_perms').format(prefix=server.prefix)))
                return

            c = message.guild.get_channel(scope)

            for hook in await c.webhooks():
                if hook.user.id == self.user.id:
                    webhook = hook.url
                    break

            if webhook == '':
                w = await c.create_webhook(name='Reminders')
                webhook = w.url

        reminder = Reminder(time=msg_time, channel=scope, message=msg_text, webhook=webhook)

        await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/success').format(pref, scope, round(msg_time - time.time()))))

        session.add(reminder)
        session.commit()

        logger.info('Registered a new reminder for {}'.format(message.guild.name))
Exemple #21
0
    async def create_reminder(self, message: discord.Message, location: int, text: str, time: int,
                              interval: typing.Optional[int] = None, method: str = 'natural') -> ReminderInformation:
        ut: float = unix_time()

        if time > ut + MAX_TIME:
            return ReminderInformation(CreateReminderResponse.LONG_TIME)

        elif time < ut:

            if (ut - time) < 10:
                time = int(ut)

            else:
                return ReminderInformation(CreateReminderResponse.PAST_TIME)

        channel: typing.Optional[Channel] = None
        user: typing.Optional[User] = None

        creator: User = User.from_discord(message.author)

        # noinspection PyUnusedLocal
        discord_channel: typing.Optional[typing.Union[discord.TextChannel, DMChannelId]] = None

        # command fired inside a guild
        if message.guild is not None:
            discord_channel = message.guild.get_channel(location)

            if discord_channel is not None:  # if not a DM reminder

                channel, _ = Channel.get_or_create(discord_channel)

                await channel.attach_webhook(discord_channel)

                time += channel.nudge

            else:
                user = await self.find_and_create_member(location, message.guild)

                if user is None:
                    return ReminderInformation(CreateReminderResponse.INVALID_TAG)

                discord_channel = DMChannelId(user.dm_channel, user.user)

        # command fired in a DM; only possible target is the DM itself
        else:
            user = User.from_discord(message.author)
            discord_channel = DMChannelId(user.dm_channel, message.author.id)

        if interval is not None:
            if MIN_INTERVAL > interval:
                return ReminderInformation(CreateReminderResponse.SHORT_INTERVAL)

            elif interval > MAX_TIME:
                return ReminderInformation(CreateReminderResponse.LONG_INTERVAL)

            else:
                # noinspection PyArgumentList
                reminder = Reminder(
                    message=Message(content=text),
                    channel=channel or user.channel,
                    time=time,
                    enabled=True,
                    method=method,
                    interval=interval,
                    set_by=creator.id)
                session.add(reminder)
                session.commit()

        else:
            # noinspection PyArgumentList
            reminder = Reminder(
                message=Message(content=text),
                channel=channel or user.channel,
                time=time,
                enabled=True,
                method=method,
                set_by=creator.id)
            session.add(reminder)
            session.commit()

        return ReminderInformation(CreateReminderResponse.OK, channel=discord_channel, time=time)
Exemple #22
0
    async def natural(self, message, stripped, server):

        err = False
        if len(stripped.split(self.get_strings(server, 'natural/send'))) < 2:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'natural/no_argument').format(prefix=server.prefix)))
            return

        scope = message.channel

        time_crop = stripped.split(self.get_strings(server, 'natural/send'))[0]
        message_crop = stripped.split(self.get_strings(server, 'natural/send'), 1)[1]
        datetime_obj = await self.do_blocking( partial(dateparser.parse, time_crop, settings={'TIMEZONE': server.timezone, 'TO_TIMEZONE': 'UTC'}) )

        if datetime_obj is None:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'natural/bad_time')))
            err = True

        elif datetime_obj.timestamp() - time.time() > 1576800000:
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'natural/long_time')))
            err = True

        chan_split = message_crop.split(self.get_strings(server, 'natural/to'))
        if len(chan_split) > 1 \
            and chan_split[-1].strip()[0] == '<' \
            and chan_split[-1].strip()[-1] == '>' \
            and all([x not in '< >' for x in chan_split[-1].strip()[1:-1]]):

            id = int( ''.join([x for x in chan_split[-1] if x in '0123456789']) )
            scope = message.guild.get_member(id)
            if scope is None:
                scope = message.guild.get_channel(id)

                if scope is None:
                    await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_tag')))
                    err = True

            message_crop = message_crop.rsplit(self.get_strings(server, 'natural/to'), 1)[0]

        interval_split = message_crop.split(self.get_strings(server, 'natural/every'))
        recurring = False
        interval = 0

        if len(interval_split) > 1:
            interval = await self.do_blocking( partial(dateparser.parse, '1 ' + interval_split[-1], settings={'TO_TIMEZONE' : 'UTC'}) )

            if interval is None:
                pass
            elif self.get_patrons(message.author.id, level=1):
                recurring = True
                interval = abs((interval - datetime.utcnow()).total_seconds())
                if interval < 8:
                    await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'interval/8_seconds')))
                    err = True
                elif interval > 1576800000:
                    await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'natural/long_time')))
                    err = True

                message_crop = message_crop.rsplit(self.get_strings(server, 'natural/every'), 1)[0]
            else:
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'interval/donor')))
                return

        if isinstance(scope, discord.TextChannel):
            if not self.perm_check(message, server):

                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/no_perms').format(prefix=server.prefix)))
                err = True

        if self.length_check(message, message_crop) is not True:
            if self.length_check(message, message_crop) == '150':
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_chars').format(len(message_crop), prefix=server.prefix)))
                err = True

            elif self.length_check(message, message_crop) == '2000':
                await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'remind/invalid_chars_2000')))
                err = True

        if not err:
            webhook = ''

            if isinstance(scope, discord.TextChannel):
                for hook in await scope.webhooks():
                    if hook.user.id == self.user.id:
                        webhook = hook.url
                        break

                if webhook == '':
                    w = await scope.create_webhook(name='Reminders')
                    webhook = w.url

            if recurring:
                reminder = Reminder(time=datetime_obj.timestamp(), message=message_crop.strip(), channel=scope.id, interval=interval, webhook=webhook)
            else:
                reminder = Reminder(time=datetime_obj.timestamp(), message=message_crop.strip(), channel=scope.id, webhook=webhook)

            logger.info('{}: New: {}'.format(datetime.utcnow().strftime('%H:%M:%S'), reminder))
            await message.channel.send(embed=discord.Embed(description=self.get_strings(server, 'natural/success').format(scope.mention, round(datetime_obj.timestamp() - time.time()))))

            session.add(reminder)
            session.commit()