def main():
    config = configparser.ConfigParser()
    config.read('config.ini')
    token = config['Todoist']['token']

    api = todoist.TodoistAPI(token)
    api.sync()
    schedule_one(api)
Exemplo n.º 2
0
def delete_all_project():
    api = todoist.TodoistAPI(API_TOKEN)
    all_ids = []
    for i in range(0, len(api.state['projects'])):
        all_ids.append(api.state['projects'][i]['id'])
    for id in all_ids:
        api.projects.get_by_id(id).delete()
    api.commit()
Exemplo n.º 3
0
 def is_completed(self):
     if self.todoist_task_id == '0':
         return 'to_work'
     api = todoist.TodoistAPI(self.related_problem_prob.user.todoist_token)
     item = api.items.get_by_id(self.todoist_task_id)
     if item['item']['checked'] == 0:
         return 'time'
     return 'done'
Exemplo n.º 4
0
def add_task(task_name, project_id=''):
    api = todoist.TodoistAPI(TODOIST_TOKEN)
    if project_id != '':
        api.add_item(task_name, project_id=project_id)
    else:
        api.add_item(task_name)

    api.commit()
Exemplo n.º 5
0
    def __init__(self, slackbot=None):
        self.todoist_api = todoist.TodoistAPI(Config.open_api.todoist.TOKEN)

        if slackbot is None:
            self.slackbot = SlackerAdapter(
                channel=Config.slack.channel.get('TASK', "#general"))
        else:
            self.slackbot = slackbot
Exemplo n.º 6
0
    def __init__(self, todoist_api_key):
        api = todoist.TodoistAPI(token=todoist_api_key)
        self._api = api

        self._api.sync()
        self._time_zone = tz.gettz(
            self._api.state['user']['tz_info']['timezone'])
        self._now = datetime.datetime.now(tz=self.time_zone)
Exemplo n.º 7
0
    def __init__(self):
        load_dotenv()
        api_token = env.get('TODOIST_API_TOKEN')

        if not api_token:
            print("Can't initialize API, no token, check .env")

        self.api = todoist.TodoistAPI(api_token)
Exemplo n.º 8
0
    def __init__(self, text=None):
        self.input = text
        self.config = Config()
        self.todoist_api = todoist.TodoistAPI(
            self.config.open_api['todoist']['TOKEN'])

        self.slackbot = SlackerAdapter()
        self.template = MsgTemplate()
Exemplo n.º 9
0
    def _get_api(self) -> todoist.TodoistAPI:
        if not self._api:
            self._api = todoist.TodoistAPI(self.api_token)

        if not self._last_sync_time or time.time(
        ) - self._last_sync_time > self._sync_timeout:
            self._api.sync()

        return self._api
Exemplo n.º 10
0
 def connect_to_todoist(self, api_token):
     import todoist
     if api_token is None:
         from dev.old.resources import default_token_path
         api_token = default_token_path
     if os.path.exists(api_token):
         from pyutils import get_token
         api_token = get_token(api_token)
     self._api = todoist.TodoistAPI(api_token)
Exemplo n.º 11
0
 def update_avatar(self):
     if not self.has_todoist_token:
         return
     api = todoist.TodoistAPI(self.todoist_token)
     api.user.sync()
     avatar = api.user.get("avatar_big", None)
     self.avatar = avatar
     self.email = api.user.get("email", None)
     return self.has_avatar
Exemplo n.º 12
0
 def __init__(self, api_key):
     Print.rewrite("Loading cache...")
     self.api = todoist.TodoistAPI(api_key)
     Print.rewrite("Syncing...")
     try:
         self.api.sync()
     except OSError:
         pass
     Print.rewrite("Synced")
Exemplo n.º 13
0
    def _init_todoist(self):
        if self.todoist_api and self.todoist_api.token:
            return True

        import todoist
        self.todoist_api = todoist.TodoistAPI(
            self.settings.get('todoist_api_key'))

        return not not self.todoist_api.token
Exemplo n.º 14
0
def create_todoist_tasks(access_token):
    api = todoist.TodoistAPI(access_token)
    project = api.projects.add("Watch 52")

    for m in session['movie_data']:
        api.items.add(m["title"],
                      project_id=project['id'],
                      due={'string': m["due_date"]})
    api.commit()
Exemplo n.º 15
0
def get_api():
    token_exists = int(vim.eval('exists("g:todoist_token")'))

    if token_exists:
        token = vim.eval('g:todoist_token')
        return todoist.TodoistAPI(token)
    else:
        print "To use vim-todoist, you must type your Token API in .vimrc. Please type: let g:todoist_token = 'YOUR_TOKEN'"
        return 0
Exemplo n.º 16
0
 def setup(self):
     # Get API token
     self.token = self.settings.get('token',"")
     if not self.token:
       self.speak_dialog('todoist.error.configuration')
       return
     self.api = todoist.TodoistAPI(self.token)
     self.api.sync()
     self.log.info("Initialized todoist api for {}".format(self.api.state['user']['full_name']))
     return
Exemplo n.º 17
0
def get_api(token):
    api = todoist.TodoistAPI(token, cache='./cache/')
    api.sync()
    if not api.state['user']:
        return api, None
    tz_info = api.state['user']['tz_info']
    timezone = datetime.timezone(
        datetime.timedelta(hours=tz_info['hours'], minutes=tz_info['minutes']),
        tz_info['timezone'])
    return api, timezone
Exemplo n.º 18
0
def main_inner() -> int:
    api = todoist.TodoistAPI(get_todoist_token())
    api.sync()
    # item = api.items.get_by_id(4386215651)
    # item.complete()
    # api.commit()

    serialize_org(convert_to_org(build_todoist_tree(api.state)))

    return 0
Exemplo n.º 19
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Todoist writer has been called.')

    text = req.params.get('text')

    apikey = os.environ['TODOIST_API_KEY']
    splitKeywords = os.environ['SPLIT_KEYWORDS']

    projectName = None
    if "TODOIST_PROJECT_NAME" in os.environ:
        projectName = os.environ['TODOIST_PROJECT_NAME']

    projectId = None
    if "TODOIST_PROJECT_ID" in os.environ:
        projectId = os.environ['TODOIST_PROJECT_ID']

    if text:
        #connect to api
        api = todoist.TodoistAPI(apikey)

        if not projectId and not projectName:
            raise AssertionError('both project_id and project_name aren'
                                 't set')
        elif not projectId and projectName:
            logging.info(
                f'no project id given, loading via api call for {projectName}')
            api.sync()
            project = [
                p for p in api.state['projects'] if p['name'] == projectName
            ][0]
            projectId = project['id']
        else:
            logging.info('Using project id from environment')

        logging.info(f'Using id {projectId}.')

        #split on keywords
        g = re.match(f'(.+)\\s({splitKeywords})\\s(.+)|(.+)', text).groups()

        #create todoist task
        try:
            item1 = api.items.add('%s%s' % (g[0] or '', g[3] or ''),
                                  projectId,
                                  date_string=g[2])
            api.commit()
        except SyncError:
            logging.warn(
                'Looks like an invalid date string, so just use the full text')
            item1 = api.items.add(text, projectId)
            api.commit()

        return func.HttpResponse(f'Created Todoist task "{text}"!')
    else:
        return func.HttpResponse("Please pass a text on the query string",
                                 status_code=400)
Exemplo n.º 20
0
def connect():
    """ Connect to todoist """
    # Get API Token for todoist
    api_file = open(os.path.expanduser("~/.config/todoist/api_key"), "r")
    api_key = api_file.read()
    api_file.close()

    # Connect to todoist
    api = todoist.TodoistAPI(api_key)
    api.sync()
    return api
Exemplo n.º 21
0
 async def todoist_test(self, ctx):
     APIkey = open(path + "Keys/todoist.txt", 'r').read().strip()
     try:
         api = todoist.TodoistAPI(APIkey)
         api.sync()
         full_name = api.state['user']['full_name']
         await ctx.send(full_name)
         for project in api.state['projects']:
             await ctx.send(project['name'])
     except Exception as e:
         await self.log_error(ctx, e)
Exemplo n.º 22
0
def get_api(email, config_path, fresh):
    config = ConfigParser()
    logger.info('Reading config file {}'.format(config_path))
    config.read(config_path)

    logger.debug('Config contents:')
    for key in config:
        logger.debug(config[key])

    if email is None:
        if config.has_option('auth', 'email'):
            email = config['auth']['email']
            logger.info('Read email from config file: {}'.format(email))
        else:
            email = input('Email address: ')

    if fresh:
        token = None
        logger.info('Fresh flag setting initial token to {}'.format(token))
    elif 'session' in config:
        token = config['session'].get('token')
        logger.info('Read token from config file: {}'.format(token))
    else:
        token = None
        logger.info('No token found in config file')

    logger.info('Initializing API object with token: {}'.format(token))
    api = todoist.TodoistAPI(token=token)

    if api.token is None:
        logger.info('No initial token for API, logging in')
        if config.has_option('auth', 'password'):
            password = config['auth']['password']
            logger.info('Read password from config file')
        else:
            password = getpass.getpass(prompt='Password: '******'error' not in user) and (api.token is not None)
        logger.info('Attempted login, status: {}'.format(success))
        logger.debug('Login response: {}'.format(user))
        if success:
            logger.info('Setting session token in config to {}'.format(
                api.token))
            if 'session' not in config:
                logger.info('Creating session section in config file')
                config['session'] = {}
            config['session']['token'] = api.token
            logger.info('Writing to config file: {}'.format(config_path))
            with open(config_path, 'w') as config_file:
                config.write(config_file)
        else:
            raise ValueError
    return api
Exemplo n.º 23
0
def update_todoist_api(key):
    """updated the todoist api key"""
    global API

    with open(os.path.dirname(__file__) + "/todoist-key.api", "w+") as f:
        f.truncate(0)
        f.write(key)
    if HAVE_TODOIST_LIBRARY:
        API = todoist.TodoistAPI(key)
    else:
        API = key
Exemplo n.º 24
0
 def mark_as_done(self, url):
     try:
         api = todoist.TodoistAPI(token=self.get_todoist_api_key())
         items = api.state['items']
         filtered = [i for i in items if i['id'] == int(url)]
         item_to_complete = filtered[0]
         item_to_complete.complete()
         api.commit()
         api.sync()
         WoxAPI.show_msg("Marked as done", "GZ!")
     except Exception as e:
         WoxAPI.show_msg("Something went wrong :( :(", f"{str(e)}")
Exemplo n.º 25
0
    def load(api_token: str) -> List[datetime.datetime]:
        api = todoist.TodoistAPI(api_token)
        activity_list = api.activity.get(event_type="completed",
                                         since=TODOIST_START,
                                         limit=100)
        dates = []
        for activity in activity_list:
            event_date = datetime.datetime.strptime(activity["event_date"],
                                                    DATE_FORMAT)
            dates.append(event_date)

        return dates
Exemplo n.º 26
0
    def __init__(self):
        self._habitica = HabiticaAPI({
            'url': 'https://habitica.com',
            'x-api-user': Config.habitica_user_id,
            'x-api-key': Config.habitica_api_key
        })

        self._log = logging.getLogger(self.__class__.__name__)
        self._todoist = todoist.TodoistAPI(Config.todoist_api_key,
                                           cache=join(dirname(__file__),
                                                      '.todoist-sync/'))

        self._task_cache = TasksCache()
Exemplo n.º 27
0
 def connect_to_todoist(self, api_token=None):
     if connected_to_internet():
         import todoist
         if api_token is None:
             from resources import default_token_path
             api_token = default_token_path
         if os.path.exists(api_token):
             from pyutils import get_token
             api_token = get_token(api_token)
         self._api = todoist.TodoistAPI(api_token)
     else:
         raise NotImplementedError(
             "Todo - mock todoist api client that behaves ")
Exemplo n.º 28
0
def main(api_token):

    from pyutils import connected_to_internet
    if not connected_to_internet():
        raise RuntimeError("Need connection to the internet to generate mock")
    if api_token is None:
        from resources import default_token_path
        api_token = default_token_path
    if os.path.exists(api_token):
        from pyutils import get_token
        api_token = get_token(api_token)
    else:
        raise RuntimeError("Need api token to generate mock")

    prototype = todoist.TodoistAPI(api_token)
    from resources import lib_root
    engine = 'pkl'  # 'json' or 'pkl'
    mock_path = os.path.join(lib_root, 'resources',
                             'mock_TodoistAPI.{engine}'.format(engine=engine))
    from pyutils import Mock
    mock_api = Mock(prototype, dump_path=mock_path, dump_engine=engine)

    api = todoist.TodoistAPI(api_token)
    from resources import lib_root
    engine = 'pkl'  # 'json' or 'pkl'
    mock_path = os.path.join(lib_root, 'resources',
                             'mock_TodoistAPI.{engine}'.format(engine=engine))
    from pyutils import Mock
    mock_api = Mock(prototype, dump_path=mock_path, dump_engine=engine)

    # now do sample requests
    print("Sync:\n", mock_api.sync().__repr__()[:200])

    # _ = mock_api.updates # no such field, what was i thinking
    print("\n\tActivity:\n", mock_api.activity.__repr__()[:200])
    print("\n\tcommit:\n", mock_api.commit().__repr__()[:200])
    print("\n\titems:\n", mock_api.items.all().__repr__()[:200])
    print("\n\tprojects:\n", mock_api.projects.all().__repr__()[:200])
    print('It seems mock is doing alright')
def main():
    key = os.getenv("TODOIST_TOKEN")
    if key is None:
        print("Environment Variable named $TODOIST_TOKEN doesn't exist!")
        sys.exit()

    api = todoist.TodoistAPI(key, 'https://todoist.com', None, None)
    api.sync()
    logger.debug('Filtering start')
    items = ExList(api.completed.get_all()['items'])\
            .filter(completedYesterday)
    logger.debug('Filtering finished')
    message = makeText(api.projects, items)
    sendSlackMessage(message)
Exemplo n.º 30
0
def get_project_id():
    api = todoist.TodoistAPI(TODOIST)
    projects = api.state['projects']
    tamer_project_id = 0
    if len(projects):
        for item in projects:
            if item['name'] == 'Tamer':
                tamer_project_id = item['id']
    if tamer_project_id == 0:
        project = api.projects.add('Tamer')
        tamer_project_id = project['id']
        api.commit()

    return tamer_project_id