示例#1
0
 def test_when_one_reminder_before_now_no_tag_calls_set_reminder(self):
     from tagrepository import TagRepository
     from configuration import Configuration
     now = datetime.now() - timedelta(seconds=400)
     now_str = datetime.strftime(now, '%Y-%m-%dT%H:%M:%S.000')
     reminder_list = {
         "reminders": [{
             "reminderid": "fa663d5b-217a-4365-ad27-635851868b45",
             "name": "Reminder1",
             "userid": "72be6ab4-727b-4257-ba1d-ef58a3349bfc",
             "deviceid": "08f98cd6-3602-41ee-aa27-a6768412254e",
             "start": now_str,
             "duration": 36000,
             "showled": 1,
             "sunday": 1,
             "monday": 1,
             "tuesday": 1,
             "wednesday": 1,
             "thursday": 1,
             "friday": 1,
             "saturday": 1
         }]
     }
     configuration = Configuration("..\configuration.json")
     tag_repo = TagRepository(configuration)
     tag_repo.get_reminders = MagicMock(return_value=reminder_list)
     led_controller = Mock()
     reminder = Reminder(tag_repo, "08f98cd6-3602-41ee-aa27-a6768412254e",
                         led_controller)
     reminder.update()
     led_controller.set_reminder.assert_called_once()
    def test_delete_event(self):
        """Check if the deletion of an event raises any exceptions."""
        remind = Reminder(self.__db_file)

        result = remind.delete_event('1', preserve=False)

        self.assertEqual(result, 0, 'Deleted without errors')
    def test_save_event(self):
        """Check if there are any exceptions in the insertion."""
        remind = Reminder(self.__db_file)

        result = remind.save_event('test_event',
                                   '2000-01-01 00:00:00',
                                   preserve=False)

        self.assertEqual(result, 0, 'No exceptions')
    def test_get_event(self):
        """Check if it returns a correct event."""
        remind = Reminder(self.__db_file)

        result = remind.get_event('1')

        self.assertFalse(result == '', 'It exists')
        self.assertFalse(result == -1, 'No exceptions')
        self.assertEqual(result, '2017-10-18 12:30:00', 'It is correct')
    def test_next_event(self):
        """Check if the next event is the first on a sorted list."""
        remind = Reminder(self.__db_file)
        next_event_date = {"EventId": "5", "EventDate": "2017-10-05 10:40:00"}

        result = remind.next_event()

        self.assertFalse(result == {}, 'Not empty')
        self.assertEqual(result, next_event_date, 'Correct output')
示例#6
0
 def testReminder_002(self):
     deadline = datetime.datetime.today() + datetime.timedelta(hours=6)
     u = QUser(g_user=users.User(email='*****@*****.**'))
     u.put()
     title = 'chips and beer'
     t = QTask(creator=u, assignee=u, title=title, description='', deadline=deadline, done=True)
     t.put()
     r = Reminder()
     r.get()
     messages = self.mail_stub.get_sent_messages(to='*****@*****.**')
     self.assertEqual(0, len(messages))
示例#7
0
    def test_execute(self):
        from tagrepository import TagRepository
        from configuration import Configuration

        configuration = Configuration("..\configuration.json")
        tag_repo = TagRepository(configuration)

        led_controller = Mock()

        reminder = Reminder(tag_repo, "08f98cd6-3602-41ee-aa27-a6768412254e",
                            led_controller)
        reminder.update()
示例#8
0
 def createR(self):
     logging("Creating Reminder Class")
     R_R = Reminder()
     logging(
         (
             "Setting Reminder class with following: ",
             JSON_Holder["Database"]["Reminder"]["Date"],
             JSON_Holder["Database"]["Reminder"]["Time"],
         )
     )
     R_R.setAll(JSON_Holder["Database"]["Reminder"]["Date"], JSON_Holder["Database"]["Reminder"]["Time"])
     DB.setReminder(R_R)
示例#9
0
    def test_when_no_reminders_calls_clear_reminder_on_led_controller(self):
        from tagrepository import TagRepository
        from configuration import Configuration

        reminder_list = {"reminders": []}
        configuration = Configuration("..\configuration.json")
        tag_repo = TagRepository(configuration)
        tag_repo.get_reminders = MagicMock(return_value=reminder_list)
        led_controller = Mock()

        reminder = Reminder(tag_repo, None, led_controller)
        reminder.update()
        led_controller.clear_reminder.assert_called_once()
示例#10
0
    def remind(self, *args):
        """
        Set a reminder
        """
        if len(args) == 0 or args[0] == "help":
            return "text", REMINDER_HELP_MSG

        try:
            reminder = Reminder(self._full_user, self._channel.id, *args)
            return "text", reminder.execute()

        except ReminderError as error:
            return "text", str(error)
示例#11
0
    def test_pin_full_example(self):
        p = Pin()

        action = Action()
        action.launch_code = 13
        action.title = 'Open in Watchapp'
        action.type = 'openWatchApp'

        self.assertDoesNotRaise(ValidationException, action.validate)

        p.add_action(action)

        reminder = Reminder()
        reminder.time = '2015-08-04T20:00:00+00:00Z'
        reminder.layout.backgroundColor = '#FFFFFF'
        reminder.layout.body = 'Drama about a police unit...'
        reminder.layout.foregroundColor = '#000000'
        reminder.layout.largeIcon = 'system://images/TV_SHOW'
        reminder.layout.smallIcon = 'system://images/TV_SHOW'
        reminder.layout.tinyIcon = 'system://images/TV_SHOW'
        reminder.layout.subtitle = 'New Tricks'
        reminder.layout.title = 'Last Man Standing'
        reminder.layout.type = 'genericReminder'

        self.assertDoesNotRaise(ValidationException, reminder.validate)

        p.add_reminder(reminder)

        p.layout.backgroundColor = '#FFFFFF'
        p.layout.foregroundColor = '#000000'
        p.layout.tinyIcon = 'system://images/TV_SHOW'
        p.layout.title = 'Last Man Standing'
        p.layout.subtitle = 'New Tricks'
        p.layout.type = 'genericPin'
        p.layout.shortTitle = 'Last Man Standing'
        p.layout.body = 'Drama about a police unit...'
        p.layout.add_section('Series', 'New Tricks')

        self.assertDoesNotRaise(ValidationException, p.layout.validate)

        p.duration = 60
        p.id = '101'
        p.time = '2015-08-04T20:00:00+00:00Z'

        self.assertDoesNotRaise(ValidationException, p.validate)

        p.time = ''

        self.assertRaises(ValidationException, p.validate)
示例#12
0
def test_reminder_operations():
    """ Test reminder operations """

    # Test setting the reminder
    args = ["set", "foo", "in", "4", "seconds"]
    reminder = Reminder("user", "channel", *args).execute()
    assert ': "foo" at' in reminder

    # Test showing reminders
    assert "Your Reminders" in Reminder("user", "channel", "show").execute()

    # Test deleting reminder
    id_ = reminder.replace("```", "").split(":")[0]
    assert "Ok. I've deleted" in Reminder("user", "channel", "delete",
                                          id_).execute()
示例#13
0
    def test_store_reminder(self):
        rem = self._build_reminder()

        with self.rh.wrapped_redis(
                op_name=f'hexists("reminders", "{rem.redis_name}")') as r_conn:
            res = r_conn.hexists('reminders', rem.redis_name)
            assert not res, f'Found unexpected, existing key for reminder "{rem.redis_name}" in Redis key "reminders"'

        res = rem.store(self.rh)
        assert res, f'Bad return value for store(): {res} (should be True (1) if not set, False (0) means overwritten)'

        rem_fetched = Reminder.fetch(helper=self.rh,
                                     redis_id='reminders',
                                     redis_name=rem.redis_name)
        assert rem_fetched, f'No response back fetching "reminder" entry for "{rem.redis_name}". Got: {rem_fetched}'

        assert rem == rem_fetched, f'Fetched entry does not match original.\nFetched:\n{rem_fetched.dump()}\nCreated:\n{rem.dump()}'

        print(
            f'Successfully retrieved Reminder entry back. Dump:\n{rem.dump()}')

        with self.rh.wrapped_redis(
                op_name=f'hdel("reminders", "{rem.redis_name}")') as r_conn:
            res = r_conn.hdel('reminders', rem.redis_name)
            assert res, f'Bad return from hdel of "{rem.redis_name}" in "reminders" Redis key. Got: {res}'

        assert rem.is_hashmap, f'Assert that reminder is a hash map failed. Got: {rem}'
示例#14
0
    def _build_reminder(self,
                        use_dt: datetime = None,
                        num_minutes: int = 5,
                        created_ts: float = None,
                        create_invalid: bool = False):
        use_dt = use_dt or datetime.now()
        trigger_dt = use_dt + timedelta(minutes=num_minutes)

        rem_kwargs = {
            'redis_id': 'reminders',
            'member_id': 12345,
            'member_name': 'pytest User',
            'channel_id': 54321,
            'channel_name': '#pytest',
            'provided_when': f'in {num_minutes} minutes',
            'content': 'pytest reminder content',
            'trigger_ts': trigger_dt.timestamp()
        }

        if created_ts:
            rem_kwargs['created_ts'] = use_dt.timestamp()

        if create_invalid:
            rem_kwargs['redis_name'] = {'bad': 'values', 'other': 5}

        return Reminder(**rem_kwargs)  # type: ignore[arg-type]
def build_reminder(reminder_dict: dict):
    r = reminder_dict
    try:
        id = r['1']['2']
        title = r['3']
        year = r['5']['1']
        month = r['5']['2']
        day = r['5']['3']
        hour = r['5']['4']['1']
        minute = r['5']['4']['2']
        second = r['5']['4']['3']
        creation_timestamp_msec = int(r['18'])
        done = '8' in r and r['8'] == 1

        return Reminder(
            id=id,
            title=title,
            dt=datetime(year, month, day, hour, minute, second),
            creation_timestamp_msec=creation_timestamp_msec,
            done=done,
        )

    except KeyError:
        print('build_reminder failed: unrecognized reminder dictionary format')
        return None
示例#16
0
def add_reminder(message, reminder_date, db_dict='reminders'):
    reminders_lst = db[db_dict]
    new_reminder = Reminder.create_reminder(message, reminder_date)
    if not new_reminder:
        return False
    reminders_lst.append(new_reminder)
    reminders_lst.sort(key=lambda r: r.month + r.day + r.year)
    db[db_dict] = reminders_lst
    return new_reminder
示例#17
0
def test_invalid_reminder():
    """ Test invalid reminder throws error """
    # Test invalid command
    with pytest.raises(ReminderError) as error:
        Reminder("user", "channel", "foo").execute()
    assert "Invalid command foo" in str(error)

    # Test invalid unit
    args = ["set", "foo", "in", "5", "bar"]
    with pytest.raises(ReminderError) as error:
        Reminder("user", "channel", *args).execute()
    assert "Invalid unit bar" in str(error)

    # Test invalid time spec
    args = ["set", "foo", "in", "bar"]
    with pytest.raises(ReminderError) as error:
        Reminder("user", "channel", *args).execute()
    assert "Reminder time must be in format" in str(error)
示例#18
0
    def test_initReminder_wrongPlatform_Exception(self):
        input_value = {
            'bot_platform': 'wrong_platform',
            'bot': None,
            'storage': None
        }

        with self.assertRaises(ValueError):
            reminder = Reminder(**input_value)
示例#19
0
    def __init__(self):
        logging.debug('Initializing Data class')
        self.DueDate = DueDate()
        self.Reminder = Reminder()
        self.Note = Note()
        self.ID  = 'Database'
        self.dbDict = {
            'Database':{
                'DueDate':{
                    DueDate.returndDict()
                },
                'Reminder':{
                    Reminder.returnrDict()

                },
                'Note':{
                    Note.returnnDict()
                }
            }
        }
示例#20
0
def read_reminder_params() -> Optional[Reminder]:
    """
    read parameters from the user and build a Reminder object.
    return a Reminder object, or None, meaning no action required (e.g. wrong
    user parameters, or user aborted the action)
    """
    title = input('What\'s the reminder: ')
    dt = parse_time_str(input('When do you want to be reminded: '))
    if dt is not None:
        print(f'\n"{title}" on {dt.strftime(DATE_FORMAT)}\n')
        save = read_yes_no('Do you want to save this?')
        if save:
            return Reminder(id=gen_id(), title=title, dt=dt)
示例#21
0
def invoke_operation(args):
    """
    inspect the program arguments and invoke the appropriate operation
    """
    client = RemindersClient()

    if args.interactive or args.create:
        # prepare the reminder to create
        if args.interactive:
            reminder = read_reminder_params()
        else:
            title, time_str = args.create
            dt = parse_time_str(time_str)
            if dt is None:
                return
            reminder = Reminder(id=gen_id(),
                                title=title,
                                dt=dt,
                                all_day=args.all_day)

        # execute creation if applicable
        if reminder is not None:
            if client.create_reminder(reminder):
                print('Reminder set successfully:')
                print(reminder)

    elif args.get:
        id = args.get
        reminder = client.get_reminder(reminder_id=id)
        if reminder is not None:
            print(reminder)

    elif args.delete:
        id = args.delete
        if client.delete_reminder(reminder_id=id):
            print('Reminder deleted successfully')

    elif args.list:
        num_reminders = args.list
        if num_reminders < 0:
            print('argument to list command must be positive')
            return
        reminders = client.list_reminders(num_reminders=num_reminders)
        if reminders is not None:
            for r in sorted(reminders):
                print(r)

    else:
        print('Wrong usage: no valid action was specified\n'
              'please read help menu (-h) to see correct usage')
    def test_get_all_events(self):
        """Check if there are any exceptions in the select."""
        remind = Reminder(self.__db_file)
        all_events_json = {
            "1": "2017-10-18 12:30:00",
            "2": "2017-10-20 14:15:00",
            "3": "2017-10-25 16:45:00",
            "5": "2017-10-05 10:40:00"
        }
        all_events_sorted_json = {
            "5": "2017-10-05 10:40:00",
            "1": "2017-10-18 12:30:00",
            "2": "2017-10-20 14:15:00",
            "3": "2017-10-25 16:45:00"
        }

        result1 = remind.get_all_events()
        result2 = remind.get_all_events(date_sorted=False)

        self.assertEqual(result1, all_events_sorted_json,
                         'Date sorted sorted correct output')
        self.assertEqual(result2, all_events_json,
                         'No date sorted sorted correct output')
    def daily_update(self, context: CallbackContext):
        # TODO: optimize
        cursor = self.db_connection().cursor()
        cursor.execute(
            '''SELECT chat_id, time_form FROM Reminder WHERE near_ts < {}'''.
            format((datetime.datetime.now() +
                    datetime.timedelta(days=1)).timestamp()))

        for row in cursor.fetchall():
            try:
                c = self.get_chat(row[0])
                r = Reminder(chat_id=row[0], utc=c.utc, time_form=eval(row[1]))
                context.job_queue.run_once(
                    remind,
                    1 + r.near_ts - datetime.datetime.now(
                        tz=pytz.FixedOffset(c.utc * 60)).timestamp(),
                    context=(self, r),
                    name=r.id())
            except RuntimeError as e:
                cursor.execute(
                    '''DELETE FROM Reminder WHERE chat_id = "{}" and time_form = "{}"'''
                    .format(row[0], row[1]))
                self.db_connection().commit()
        cursor.close()
    def get_all_reminders(self):
        reminders = []
        cursor = self.db_connection().cursor()
        cursor.execute('''SELECT chat_id, time_form FROM Reminder''')
        for row in cursor.fetchall():
            try:
                reminders.append(
                    Reminder(chat_id=row[0],
                             utc=self.get_chat(row[0]).utc,
                             time_form=eval(row[1])))
            except RuntimeError as e:
                cursor.execute(
                    '''DELETE FROM Reminder WHERE chat_id = "{}" and time_form = "{}"'''
                    .format(row[0], row[1]))
                self.db_connection().commit()
        cursor.close()

        return reminders
    def add_reminder(self, r: Reminder, context: CallbackContext):
        # TODO: optimize
        cursor = self.db_connection().cursor()
        query = '''INSERT INTO Reminder VALUES({},"{}","","{}","{}",{},{},{},{},{},{})'''.format(
            r.near_ts, r.chat_id, r.time_form, r.name, r.hour, r.minute,
            r.second, r.day, r.month, r.year)

        cursor.execute(query)
        self.db_connection().commit()
        cursor.close()

        if datetime.datetime.now(tz=pytz.FixedOffset(r.utc * 60)).replace(
                hour=23, minute=59, second=59).timestamp() > r.near_ts:
            context.job_queue.run_once(
                remind,
                1 + r.near_ts - datetime.datetime.now(
                    tz=pytz.FixedOffset(r.utc * 60)).timestamp(),
                context=(self, r),
                name=r.id())
def build_reminder(reminder_dict: dict) -> Optional[Reminder]:
    r = reminder_dict
    try:
        id = r['1']['2']
        title = r['3']
        if '5' in r:
            year = r['5']['1']
            month = r['5']['2']
            day = r['5']['3']
            if '4' in r['5']:
                hour = r['5']['4']['1']
                minute = r['5']['4']['2']
                second = r['5']['4']['3']
            else:
                hour = 0
                minute = 0
                second = 0
            all_day = '9' in r['5'] and r['5']['9'] == 1
        else:
            now = datetime.now()
            year = now.year
            month = now.month
            day = now.day
            hour = 0
            minute = 0
            second = 0

        creation_timestamp_msec = int(r['18'])
        done_timestamp_msec = int(r['11']) if '11' in r else None
        done = '8' in r and r['8'] == 1

        return Reminder(id=id,
                        title=title,
                        dt=datetime(year, month, day, hour, minute, second),
                        creation_timestamp_msec=creation_timestamp_msec,
                        done_timestamp_msec=done_timestamp_msec,
                        done=done,
                        all_day=all_day)

    except KeyError:
        print('build_reminder failed: unrecognized reminder dictionary format')
        return None
示例#27
0
def get_reminder_from_dataframe(df_reminders, reminder_id):
    """
    Args:
        df_reminders: A pandas DataFrame of reminders.
        reminder_id: Reminder ID whose data will be extracted from `df_reminders`.

    Returns:
        A Reminder object.
    """
    if df_reminders.index.name == 'id':
        assert reminder_id in df_reminders.index, \
            'Reminder with ID {} not found in the given DataFrame.'.format(reminder_id)
        field_values = df_reminders.loc[[reminder_id
                                         ]].reset_index().to_dict('records')[0]
    else:
        assert 'id' in df_reminders.columns
        record = df_reminders[df_reminders['id'] == reminder_id]
        assert len(record) != 0, \
            'Reminder with ID {} not found in the given DataFrame.'.format(reminder_id)
        field_values = record.to_dict('records')[0]
    return Reminder.from_dict(field_values)
示例#28
0
    def __init__(self):
        self.DueDate = DueDate()
        self.Reminder = Reminder()
        self.Note = Note()
        self.ID  = 'Database'
        self.dbDict = {
            'Database':{
                'DueDate':{
                    'Name': self.DueDate.returnName(), 
                    'Date': self.DueDate.returnDate(),
                    'Time': self.DueDate.returnTime()
                },
                'Reminder':{
                    'Date': self.Reminder.returnDate(),
                    'Time': self.Reminder.returnTime()

                },
                'Note':{
                    'Note': self.Note.returnNote()
                }
            }
        }
        logging.debug('Initializing Data class')
示例#29
0
class Data_rm(DueDate, Reminder, Note):
    def __init__(self):
        logging.debug('Initializing Data class')
        self.DueDate = DueDate()
        self.Reminder = Reminder()
        self.Note = Note()
        self.ID  = 'Database'
        self.dbDict = {
            'Database':{
                'DueDate':{
                    DueDate.returndDict()
                },
                'Reminder':{
                    Reminder.returnrDict()

                },
                'Note':{
                    Note.returnnDict()
                }
            }
        }

    # Returning Functions (Classses)
    # def returnDueDate(self):
    #     logging.debug(('Returning Data::Duedate: ', self.DueDate))
    #     return self.DueDate

    # def returnReminder(self):
    #     logging.debug(('Returning Data::Reminder: ', self.Reminder))
    #     return self.Reminder

    # def returnNote(self):
    #     logging.debug(('Returning Data::Note: ', self.Note))
    #     return self.Note

    # def returnID(self):
    #     logging.debug(('Returning Data::ID: ', self.ID))
    #     return self.ID

    # # Returning Functions (Dictionaries)
    # def returndDict(self):
    #     logging.debug(('Returning Data::dDict: ', self.DueDate.returndDict()))
    #     return self.DueDate.returndDict()

    # def returnrDict(self):
    #     logging.debug(('Returning Date::rDict: ', self.Reminder.returnrDict()))
    #     return self.Reminder.returnrDict()

    # def returnnDict(self):
    #     logging.debug(('Returning Date::nDict: ', self.Note.returnnNote()))
    #     return self.Note.returnrDict()

    # Setting Individual Functions: setX(params)
    # def setDueDate(self, name, date, time):
    #     logging(('Setting Data::DueDate with parameters: ', name, date, time))
    #     logging(('Previous Data::DueDate parameters: ', self.DueDate.returnName(),
    #              self.DueDate.returnDate(),
    #              self.DueDate.returnTime()))
    #     self.DueDate.setAll(name, date, time)
    #     logging(('Present Data::DueDate parameters: ', self.DueDate.returnName(),
    #              self.DueDate.returnDate(),
    #              self.DueDate.returnTime()))

    # def setReminder(self, date, time):
    #     logging(('Setting Data::Reminder with parameters: ', date, time))
    #     logging(('Previous Data::Reminder parameters: ', self.Reminder.returnDate(),
    #              self.Reminder.returnTime()))
    #     self.Reminder.setAll(date, time)
    #     logging(('Present Data::Reminder parameters: ', self.Reminder.returnDate(),
    #              self.Reminder.returnTime()))

    # def setNote(self, note):
    #     logging(('Setting Data::Note with parameters: ', note))
    #     logging(('Previous Data::Note parameters: ', self.Note.returnNote()))
    #     self.Note.setNote(note)
    #     logging(('Present Data::Note parameters: ', self.Note.returnNote()))

    # Setting with Class: setXC(class)
    def setDueDateC(self, dd):
        logging(('Setting Data::DueDate with class: ', dd.returnName(),
                 dd.returnDate(), dd.returnTime()))
        logging(('Previous Data::DueDate parameters: ', self.DueDate.returnName(),
                 self.DueDate.returnDate(),
                 self.DueDate.returnTime()))
        self.DueDate.setAll(dd.returnName(), dd.returnDate(), dd.returnTime())
        logging(('Presetn Data::DueDate parameters: ', self.DueDate.returnName(),
                 self.DueDate.returnDate(),
                 self.DueDate.returnTime()))

    def setReminderC(self, r):
        logging(('Setting Data::Reminder with class: ', r.returnDate(),
                 r.returnTime()))
        logging(('Previous Data::Reminder parameters: ', self.Reminder.returnDate(),
                 self.Reminder.returnTime()))
        self.Reminder.setAll(r.returnDate(), r.returnTime())
        logging(('Present Data::Reminder parameters: ', self.Reminder.returnDate(),
                 self.Reminder.returnTime()))

    def setReminderC(self, n):
        logging(('Setting Data::Note with class: ', n.returnNote()))
        logging(('Previous Data::Note parameters: ', self.Note.returnNote()))
        self.Note.setNote(n.returnNote())
        logging(('Present Data::Note parameters: ', self.Note.returnNOte()))

    # Clearing Classes
    def clearDueDate(self):
        logging('Clearing Data::DueDate class')
        self.DueDate.setAll(None, None, None)

    def clearReminder(self):
        logging('Clearing Data::Reminder class')
        self.Reminder.setAll(None, None, None)

    def clearNote(self):
        logging('Clearing Data::Note class')
        self.Note.setNote(None)
示例#30
0
from functools import reduce

from web_fetcher import WebFetcher
from dual_markov import DualMarkov
from discord_utils import slow_send, tokenize
from reminder import Reminder
from calendar_manager import CalendarManager

with open("conf.json") as conf:
    params = json.load(conf)

token = params["token"]

client = discord.Client()
webfetcher = WebFetcher(client)
reminder = Reminder(client)
cal_manager = CalendarManager(client, params["calendar_path"])

interpreters = [webfetcher, reminder, cal_manager]
conversations = []

reboot_on_shutdown = 0


@asyncio.coroutine
def shutdown():
    yield from client.logout()


@asyncio.coroutine
def check_hard_commands(msg):
示例#31
0
    Copyright (C) 2016 Logvinov Dima.
    This program comes with ABSOLUTELY NO WARRANTY.
    This is free software, and you are welcome to redistribute it
    under certain conditions.
    """)

    parser = argparse.ArgumentParser(description="PyReminder - python reminder app for ElementaryOS.")
    parser.add_argument('--add', help="Add new event.\n"
                                      "$ pyreminder --add 'Event text:Event time hours.minutes.day.month.year'", type=str)
    parser.add_argument('--list', help="Print list of events.", action="store_true")
    parser.add_argument('--delete', help="Delete event.\n "
                                         "$ pyreminder --delete event_id ", type=int)
    parser.add_argument('--gui', help="Run gui program.", action="store_true")

    args = parser.parse_args()
    reminder = Reminder()

    if args.gui:
        root = Tk()
        root.geometry("500x200+350+500")
        app = GUI(root, reminder)
        root.mainloop()

    if args.add:
        event_text, event_date = args.add.split(":")
        reminder.add_task(event_date, event_text)
        reminder.update_db()

    if args.list:
        tasks = reminder.get_tasks_list()
示例#32
0
	def createR(self):
		logging('Creating Reminder Class')
		R_R = Reminder()
		logging(('Setting Reminder class with following: ', JSON_Holder['Reminder']['Date'],JSON_Holder['Reminder']['Time']))
		R_R.setAll(JSON_Holder['Reminder']['Date'], JSON_Holder['Reminder']['Time'])
		DB.setReminder(R_R)
示例#33
0
import fileinput
from datetime import datetime, date
from reminder import Reminder

dates = []

for line in fileinput.input():
  line = line.rstrip('\n')
  date = datetime.strptime(line, '%m/%d/%Y')
  dates.append(date)

reminder = Reminder(date.today())

if reminder.shouldRemind(dates):
  print 'Reminder should be sent'
else:
  print 'A reminder should not be sent'
示例#34
0
import json
import asyncio
import discord

from reminder import Reminder
from dice import RollDice
from pinner import Pinner

config = json.load(open('./config.json'))
loop = asyncio.get_event_loop()
client = discord.Client()

reminder = Reminder(loop)
dice = RollDice()
pinner = Pinner()


@client.event
async def on_ready():
    print("Bot is ready.")
    for ch in config['greet_ch']:
        channel = client.get_channel(ch)
        await channel.send('おはよう!')


@client.event
async def on_message(message):
    if message.author.bot:
        return

    print("Received message: " + message.content)
示例#35
0
文件: tobo.py 项目: dendiz/tobo-py
        tasklist = rmd.tryRun()
        #TODO if task list contains task ids, send out reminder messages
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        for taskid in tasklist:
            if taskid is None: pass
            sql = "select * from todos where id = '%s'" % taskid
            cursor.execute(sql)
            row = cursor.fetchone()
            conn.send(xmpp.Message(row["jid"], "reminder:\n%s" % row['todo']))
        conn.Process(1)
    except KeyboardInterrupt:
        return 0
    return 1


rmd = Reminder()
db = MySQLdb.connect(host="localhost", user=dbuser, passwd=dbpasswd, db="tobo")
cursor = db.cursor(MySQLdb.cursors.DictCursor)
sql = "select * from users"
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
    auths.append(row['jid'])
#conn = xmpp.Client(server, debug=['always', 'nodebuilder'])
conn = xmpp.Client(server, debug=[])
conres = conn.connect()
if not conres:
    logging.error("Unable to connect to jabber server")
    sys.exit(1)
if conres <> 'tls':
    logging.warning("TLS failed, using plain")
示例#36
0
 def set_task(self):
     Reminder().get_schedule_info()
示例#37
0
 def create(self):
     msg = input('What do you want to remind: ')
     hour = int(input('Hour: '))
     minute = int(input('Minute: '))
     second = int(input('Second: '))
     self.reminders.append(Reminder(msg, hour, minute, second))
示例#38
0
def handle_message(event):
    print("Event: ", event)
    print("event.reply_token:", event.reply_token)
    print("event.message.text:", event.message.text)
    rem = Reminder()

    if event.source.type == 'user':
        userid = event.source.user_id
        typeid = ''
        sourcetype = 'user'
    elif event.source.type == 'group':
        userid = event.source.user_id
        typeid = event.source.group_id
        sourcetype = 'group'
    elif event.source.type == 'room':
        userid = event.source.user_id
        typeid = event.source.room_id
        sourcetype = 'group'

    try:
        profile = line_bot_api.get_profile(userid)
        username = profile.display_name
    except LineBotApiError:
        userid = typeid
        username = '******'

    replyToken = event.reply_token
    text = event.message.text
    if text.count(' ') > 0:
        command, message = text.split(' ', 1)
    else:
        command = text
        message = ' '

    print("command:", command)
    print("message:", message)

    if command == "/wf":
        try:
            content = wolfram(message)
        except AttributeError:
            content = 'invalid query'
        line_bot_api.reply_message(replyToken, TextSendMessage(text=content))

    elif command == "/tp":
        res = tokopedia(message)
        data = res.get('items')[0].get('pagemap').get('metatags')[0]
        if data.get('twitter:data1') is not None:
            msg = []
            judul, a = data.get('og:title').split('|', 1)
            textt = 'Harga: ' + data.get(
                'twitter:data1') + '\nKota: ' + data.get(
                    'twitter:data2') + '\n\n' + data.get('og:url')
            msg.append(TextSendMessage(text=judul))
            msg.append(
                ImageSendMessage(original_content_url=data.get('og:image'),
                                 preview_image_url=data.get('og:image')))
            msg.append(TextSendMessage(text=textt))
            print('MESSAGE: ', msg[0].text)
            line_bot_api.reply_message(replyToken, msg)
        else:
            line_bot_api.reply_message(
                replyToken,
                TextSendMessage(
                    text="Nama barang yang dicari terlalu umum / kurang detail"
                ))

    elif command == "/remind":
        # me to <do stuff> in <x> <time>
        m = re.search('me to(\s.+)(?=in)(in\s)(\d+)(\s\w+)', message)

        if m != None:
            msg = m.group(1).strip()
            time1 = int(m.group(3))
            time2 = m.group(4)
            print('time2= ', time2)
            time = 0
            if time1 > 0:
                if time2 == ' minute' or time2 == ' minutes':
                    time = time1 * 60
                elif time2 == ' hour' or time2 == ' hours':
                    time = time1 * 3600
                elif time2 == ' day' or time2 == ' days':
                    time = time1 * 86400
                elif time2 == ' week' or time2 == ' weeks':
                    time = time1 * 604800
                printt = 'TIME= ' + str(time) + ' seconds'
                print(printt)
                rem.createReminder(username, userid, typeid, time, msg,
                                   sourcetype)

                line_bot_api.reply_message(replyToken,
                                           TextSendMessage(text='ok'))
        else:
            line_bot_api.reply_message(
                replyToken, TextSendMessage(text='your command is invalid'))

    elif text == "/test":
        content = 'hello, ' + username + '. \nyour userid is ' + userid
        line_bot_api.reply_message(replyToken, TextSendMessage(text=content))

    else:
        line = []
        line.append('Daftar fungsi yang bisa digunakan: \n\n')
        line.append(
            'Wolfram: Mencari informasi umum, menyelesaikan perhitungan, mencari definisi, dll.\n'
        )
        line.append('   Command: "/wf <query>"\n')
        line.append('   Query harus dalam bahasa inggris dan jelas. \n')
        line.append('   contoh: "/wf us third president"\n\n')
        line.append(
            'Tokopedia: Mencari barang yang dijual di tokopedia sesuai query.\n'
        )
        line.append('   Command: "/tp <query>"\n')
        line.append(
            '   Query tidak boleh menggunakan kata yang terlalu umum. \n')
        line.append('   contoh: "/tp gtx 1050"\n\n')
        line.append(
            'Reminder: Meminta bot untuk mengirim pesan yang diinginkan setelah waktu yang ditentukan\n'
        )
        line.append(
            '   Command: "/remind me to <message> in <angka> <satuanWaktu>"\n')
        line.append(
            '   Satuan waktu yang bisa digunakan mulai dari minute(s) sampai week(s)\n'
        )
        line.append(
            '   contoh: "/remind me to ngerjain tugas python in 3 hours"\n')
        content = '-'.join(line)

        if sourcetype == 'user' or text == '/help':
            line_bot_api.reply_message(replyToken,
                                       TextSendMessage(text=content))
示例#39
0
    def test_initReminder_RightPlatformVk(self):
        input_value = {'bot_platform': 'vk', 'bot': None, 'storage': None}

        reminder = Reminder(**input_value)

        self.assertIsNotNone(reminder)