コード例 #1
0
def add_todoist_task(task_name,
                     project="Inbox",
                     priority="no",
                     dtstart=None,
                     note=None):
    """
    :param task_name: (str) Name of task in todoist
    :param project: (str, "Inbox") project to add to. Default is Inbox
    :param priority: (str, "normal"): priority of task. Can be: "normal", "no", "high", "low", "very_high"
    :param dtstart: (str, None) Start Date as date string
    :param note (str, None) additional notes

    """
    user = todoist.login(todoist_mail_adress, todoist_password)
    todoist_project = _get_project(project, user)
    task = todoist_project.add_task(task_name,
                                    priority=_get_priority(priority))
    print("Added task '{}' with priority '{}' to project '{}'".format(
        task_name, priority, project))
    if dtstart is not None:
        task.date_string = dtstart
        task.date_lang = 'en'
        task.update()
        print("Added start date: '{}'".format(dtstart))
    if note is not None:
        task.add_note(note)
        print("Added additional information as note")
コード例 #2
0
 def __init__(self):
     #This is meant as a safe guard against too many todoist API calls
     try:
         self.user = todoist.login(TODOIST["email"], TODOIST["password"])
         self.productivity = self.user.get_productivity_stats()
         self.days_items = self.productivity["days_items"]
     except:
         self.days_items = [{"total_completed" : 0}]
コード例 #3
0
ファイル: todoist.py プロジェクト: EQt/PyTodoist
def _get_user():
    try:
        user = todoist.register(full_name, email, password)
    except todoist.RequestError:
        user = todoist.login(email, password)
        user.delete()
        user = todoist.register(full_name, email, password)
    return user
コード例 #4
0
ファイル: todoist.py プロジェクト: printminion/PyTodoist
def _get_user():
    try:
        user = todoist.register(full_name, email, password)
    except todoist.TodoistException, e:
        if e.response.text == '"ALREADY_REGISTRED"':
            user = todoist.login(email, password)
            user.delete()
            user = todoist.register(full_name, email, password)
コード例 #5
0
ファイル: util.py プロジェクト: TomCompiles/pytodoist
def create_user():
    """Return a newly registered logged in Todoist user."""
    user = TestUser()
    try:
        return todoist.register(user.full_name, user.email, user.password)
    except todoist.RequestError:
        existing_user = todoist.login(user.email, user.password)
        existing_user.delete()
        return todoist.register(user.full_name, user.email, user.password)
コード例 #6
0
ファイル: test_todoist.py プロジェクト: Danisan/pytodoist
def _get_user():
    email = "pytodoist.test.email." + _id_gen() + "@gmail.com"
    try:
        user = todoist.register(_USER_NAME, email, _USER_PASSWORD)
    except todoist.RequestError:
        user = todoist.login(email, _USER_PASSWORD)
        user.delete()
        user = todoist.register(_USER_NAME, email, _USER_PASSWORD)
    return user
コード例 #7
0
def create_user():
    """Return a newly registered logged in Todoist user."""
    user = TestUser()
    try:
        return todoist.register(user.full_name, user.email, user.password)
    except todoist.RequestError:
        existing_user = todoist.login(user.email, user.password)
        existing_user.delete()
        return todoist.register(user.full_name, user.email, user.password)
コード例 #8
0
 def force_sync(self, val):
     self._increment_counter_and_check_for_limit(4)
     try:
         self.user = todoist.login(self.user.email, self.user.password)
         self.project = self.user.get_project(self.project.name)
         self.set_projects(val)
         self.set_tasks()
     except:
         self.gui.displayError("S500 ERROR: Error syncing")
コード例 #9
0
def update_tasks(project_name='School'):
    # get all future events from schoology
    new_events = get_events()

    # git all tasks that have ever been completed in todoist
    user = todoist.login(credentials.todoist_username, credentials.todoist_password)
    project = user.get_project(project_name)
    added_tasks = [task.content for task in project.get_completed_tasks() + project.get_tasks()]

    # checks if each future task is in the list of previous tasks
    # this is pretty inefficient, but I don't have that many tasks in todoist
    for event in new_events:
        if not check_task(user, event.name, added_tasks):
            project.add_task(event.name, event.date)
コード例 #10
0
def run():
    user = todoist.login('*****@*****.**',
                         's8/%6#%G;xN%~WNWH6?t')
    projects = user.get_projects()
    for project in projects:
        pi = '\t' * (project.indent - 1)
        print(pi + project.name + ':')
        tasks = project.get_tasks()
        for task in tasks:
            ti = '\t' * task.indent

            if task.checked:
                done_tag = ' @done'
            else:
                done_tag = ''
            print(pi + ('\t' * task.indent) + '- ' + task.content + done_tag)
コード例 #11
0
ファイル: todoist.py プロジェクト: dj95/todoist-notify
    def __init__(self, config):
        # call the constructor of the Thread object
        super().__init__()

        # create a stop event
        self.stop_event = Event()

        # log in to todoist in order to make api calls
        self.__user = todoist.login(config['username'], config['password'])

        # initialize the TodoistSocket for unix connections
        self.__socket_thread = TodoistSocketThread(self)

        # some variables we need later on
        self.__timeout = 10.0
        self.__projects = None
コード例 #12
0
    def userLogin(self, username, password):
        """
        Login using Todoist login functionality

        """
        try:
            self.user = todoist.login(username, password)
            # print(self.user)
            f = open("user.txt", "w+")
            f.write(username)
            f.close

            keyring.set_password("Pando", username, password)

            self.quit()
        except Exception:
            self.displayError("")
コード例 #13
0
ファイル: todoistcmd.py プロジェクト: LWprogramming/BrYOUno
def go():
    try:
        option = getVoice.select(
            ['list tasks', 'add task', 'check off task', 'cancel'],
            selector="action")
        with open("/home/pi/todoist.txt", "r") as pw_file:
            pw = pw_file.read().replace('\n', '')
        user = todoist.login('*****@*****.**', pw)

        if option == 'list tasks':
            lst(user)
        elif option == "add task":
            add(user)
        elif option == "check off task":
            check(user)
    except Exception as e:
        print("Encountered error")
        talker.say("Encountered error")
        db.log_error(type(e).__name__, str(e), __file__)
コード例 #14
0
ファイル: addTask.py プロジェクト: DrkSephy/hacker-todoist
def sync(name, service):
	"""
	Creates a new project on todoist, and adds all <service>
	issues into the todoist project.
	"""
	user = todoist.login(secrets.credentials['username'], secrets.credentials['password'])
	# name will be passed from a POST request
	# Create a project with name passed in
	user.add_project(name)
	# Get a hold of the project just created
	project = user.get_project(name)
	# Get issue data
	if service == 'Github':
		data = issues.batchTasks('legionJS', 'legionJS')
		for task in data:
			project.add_task(task['title'], date=task['due'])
		return
	else:
		data = bitbucket.batchBitbucketTasks('DrkSephy', 'test')
		for task in data:
			print task['priority']
			project.add_task(task['title'])
コード例 #15
0
from credentials import USER, PASS
import sys
import re
import threading
import urllib

#Setup loggging
FORMAT = '%(asctime)-15s, %(levelname)s: %(message)s'
logging.basicConfig(filename="triage.log", level=logging.INFO, format=FORMAT)
l = logging.getLogger(__name__)

assert sys.argv[1] is not None

print("Starting script")
#Setup pytodoist.todoist
user = todoist.login(USER, PASS)
print("Finished setting up todoist login")

##########################
# Get tasks and projects #
##########################

tasks = user.get_project(sys.argv[1]).get_tasks()

#####################
# Utility functions #
#####################

def task_to_project(task, project):
    task.move(project)
    l.info("{} received '{}'".format(project.name, task.content))
コード例 #16
0
ファイル: todoist.py プロジェクト: printminion/PyTodoist
 def test_update(self):
     self.user.full_name = 'Todoist Py'
     self.user.update()
     self.user = todoist.login(email, password)
     self.assertEqual(self.user.full_name, 'Todoist Py')
コード例 #17
0
def updateTodoist(todoist_email, todoist_password, canvas_url, canvas_api_key,
                  system_time, data):
    global fileData
    #establish time
    today = str(datetime.today()).split(" ")[0]
    tDate = datetime(int(today.split("-")[0]), int(today.split("-")[1]),
                     int(today.split("-")[2])).timestamp()
    #establish canvas
    try:
        canvas = Canvas(canvas_url, canvas_api_key)
        user = canvas.get_current_user()
        courses = user.get_courses()
    except:
        return 1
    # establish todoist
    try:
        user = todoist.login(todoist_email, todoist_password)
    except:
        return 2
    projectsTemp = user.get_projects()
    names = []
    projects = {}
    projectsList = []
    for project in projectsTemp:
        projects.update({project.name: project})
        projectsList.append([project.name, project])
    #establish data
    fileData = json.loads(data)

    for task in fileData:
        # check for expired
        #print(task[2])
        aDate = datetime(int(task[2].split("-")[0]),
                         int(task[2].split("-")[1]),
                         int(task[2].split("-")[2])).timestamp()
        if (aDate < tDate):
            fileData.remove(task)

    tasksAddedCount = 0
    fullAssignments = []
    for course in courses:
        print(course.name)
        for assignment in course.get_assignments():
            try:
                tDate2 = datetime.utcnow()
                d = str(system_time).split(" ")[0]
                t = str(system_time).split(" ")[1]
                system_time = datetime(int(d.split("-")[0]),
                                       int(d.split("-")[1]),
                                       int(d.split("-")[2]),
                                       int(t.split(":")[0]),
                                       int(t.split(":")[1]),
                                       round(float(t.split(":")[2])))
                offset = (tDate2 - system_time)
                if (str(tDate2 - system_time)[0] == "-"):
                    offset = (system_time - tDate)
                d = str(assignment.due_at_date).split(" ")[0]
                t = str(assignment.due_at_date).split(" ")[1]
                due_date_UTC = datetime(int(d.split("-")[0]),
                                        int(d.split("-")[1]),
                                        int(d.split("-")[2]),
                                        int(t.split(":")[0]),
                                        int(t.split(":")[1]),
                                        int(t.split(":")[2].split("+")[0]))
                aDate = (due_date_UTC - offset).timestamp()

                if (aDate >= tDate):
                    flag = False
                    for task in fileData:
                        if (str(task[1]) == str(assignment.name)):
                            flag = True
                    if (flag):
                        break
                    tempData = [
                        course.name, assignment.name,
                        str(datetime.fromtimestamp(aDate)).split(" ")[0]
                    ]
                    projects[tempData[0]].add_task(content=tempData[1],
                                                   date=tempData[2])
                    fullAssignments.append(tempData)
                    fileData.append(tempData)
                    tasksAddedCount += 1
            except:
                pass

    return [tasksAddedCount, fileData]
コード例 #18
0
ファイル: test_todoist.py プロジェクト: Garee/pytodoist
 def test_login_success(self):
     todoist.login(self.user.email, self.user.password)
コード例 #19
0
ファイル: test_todoist.py プロジェクト: vpineda7/pytodoist
 def test_update(self):
     new_name = self.user.full_name + ' Jnr'
     self.user.full_name = new_name
     self.user.update()
     self.user = todoist.login(self.user.email, self.user.password)
     self.assertEqual(self.user.full_name, new_name)
コード例 #20
0
ファイル: test_todoist.py プロジェクト: vpineda7/pytodoist
 def test_login_success(self):
     todoist.login(self.user.email, self.user.password)
コード例 #21
0
ファイル: task_complete.py プロジェクト: ehershey/utilities
def complete_task(task):
    print "Marking task complete: " + task.content
    task.complete()

DEFAULT_FILTER = "overdue, today, & p:Inbox"

parser = argparse.ArgumentParser(description='Mark Todoist Task complete')
parser.add_argument('text_to_match', help='Task text')
parser.add_argument('--exact_match_only', action='store_true',
                    help='If task text must be exact (default is substring)')
parser.add_argument('-v', '--verbose', action='store_true',
                    help='Include some extra details')
args = parser.parse_args()


user = todoist.login(email=todoist_auth.email, password=todoist_auth.password)

tasks = user.search_tasks(DEFAULT_FILTER)

matching_tasks = []
exact_matching_tasks = []

text_to_match = args.text_to_match.lower()

for task in tasks:
    task_content = task.content.lower()
    if text_to_match in task_content:
        matching_tasks.append(task)
    if text_to_match == task_content:
        exact_matching_tasks.append(task)
コード例 #22
0
import csv
import time
from pytodoist import todoist
from pytodoist.api import TodoistAPI

# Use the pytodoist library for simple task of getting all project_ids, 
# and getting all label_ids.  These were previously added using code in
# createProjectsLabels.py.  Store in a dicts for when looping through CSV file.
# A more efficient way would be to create the labels and projects as they are 
# encountered in the CSV. 

username = raw_input("Please enter username: "******"Please enter password: ")

user = todoist.login(username, password)

projects = user.get_projects()
projectDict = {}
for project in projects:
 	projectDict[project.name] = project.id

labels = user.get_labels()
labelDict = {}
for label in labels:
	labelDict[label.name] = label.id



# Use the pytodoist.api library to add new tasks, getting the project_id and 
# label_id from the dicts created above.
コード例 #23
0
def main():
    """Shows basic usage of the Google Calendar API.

    Creates a Google Calendar API service object and outputs a list of the next
    10 events on the user's calendar.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    utc_now = datetime.datetime.now(timezone('UTC'))
    jst_now = utc_now.astimezone(timezone('Asia/Tokyo'))
    jst_now_iso=jst_now.isoformat()
    jst_next_week_iso=(jst_now + datetime.timedelta(days=7)).isoformat()

    # 今後5件を取得
    # eventsResult = service.events().list(
    #     calendarId='primary', timeMin=jst_now_iso, maxResults=5, singleEvents=True,
    #     orderBy='startTime').execute()

    # これから1週間のカレンダーを取得
    print("カレンダーを取得中..")
    eventsResult = service.events().list(
        calendarId='primary', timeMin=jst_now_iso, timeMax=jst_next_week_iso, singleEvents=True,
        orderBy='startTime').execute()
    events_gcal = eventsResult.get('items', [])


    # google calendarから取得したtodoをtodoistに追加
    df=pd.read_csv("secret/secret.csv")
    id_todoist=df["todoist_id"][0]
    password_todoist=df["todoist_password"][0]
    user = todoist.login(id_todoist, password_todoist)

    projects_todoist = user.get_projects()

    inbox_todoist = user.get_project('Inbox')


    tasks =[]
    if not events_gcal:
        print('No upcoming events found.')
    for event in events_gcal:
        print(event['start'].get('date'),event['summary'])

    print("todoistに追加中..")
    for i, event in enumerate(events_gcal):
        summary = event['summary']
        if "todo" in summary:
            # calendarでの開始時間(start)のdateをdue dateとする
            date = event['start'].get('date')
            print(summary, date)
            # todoistに追加
            # tasks.append(inbox_todoist.add_task(summary, date=date))

    # google calendarから取得したtodoをtrelloに追加
    df=pd.read_csv("secret/secret.csv")
    TRELLO_API_KEY=df["trello_key"][0]
    TRELLO_SECRET=df["trello_secret"][0]
    TRELLO_TOKEN=df["trello_token"][0]

    client = TrelloClient(TRELLO_API_KEY, token=TRELLO_TOKEN)
    # ボードの作成
    created_board = client.add_board("Create from Google Calendar")
    target_board_id = created_board.id

    # list idの取得
    lists = created_board.all_lists()

    print("trelloで追加するリストの選択..")
    for l in lists:
        print("list id: {}".format(l.id))
        print("list name: {}".format(l.name))
        if l.name == "To Do":
            target_list_id = l.id

    # カードを追加するボードやリストを決める
    board = client.get_board(target_board_id)
    target_list = board.get_list(target_list_id)

    print("trelloに追加中..")
    for i, event in enumerate(events_gcal):
        summary = event['summary']
        if "todo" in summary:
            due_datetime = datetime.datetime.strptime(event['start'].get('date'), '%Y-%m-%d') #str->datetime
            print(due_datetime)
            created_card = target_list.add_card(summary)
            created_card.set_due(due_datetime)
コード例 #24
0
ファイル: test_todoist.py プロジェクト: Garee/pytodoist
 def test_update(self):
     new_name = self.user.full_name + ' Jnr'
     self.user.full_name = new_name
     self.user.update()
     self.user = todoist.login(self.user.email, self.user.password)
     self.assertEqual(self.user.full_name, new_name)
コード例 #25
0
ファイル: tasks_module.py プロジェクト: GarryWalsh/Reflect
 def login(self):
     self.user = todoist.login(self.user_name, self.user_password)
コード例 #26
0
ファイル: main.py プロジェクト: dariusstrasel/todoist.py
 def __init__(self, name):
     self.name = name
     self.email = ""
     self.password = ""
     self.account = todoist.login(self.email, self.password)
コード例 #27
0
from pytodoist import todoist
from os.path import dirname, join

user1 = todoist.login('*****@*****.**', 'password')

import numpy as np
#  np.random.seed(1)
from bokeh.layouts import gridplot
from bokeh.models import AjaxDataSource, ColumnDataSource, DatetimeTickFormatter
from bokeh.plotting import figure
from bokeh.embed import components
from flask import Flask, request, render_template, abort, Response, jsonify
import pandas as pd

app = Flask(__name__)


@app.route('/')
def index():
    plot_script, plot_div = make_ajax_plot()
    kwargs = {'plot_script': plot_script, 'plot_div': plot_div}
    kwargs['title'] = 'Todoist'
    if request.method == 'GET':
        return render_template('index.html', **kwargs)
    abort(404)
    abort(Respone('Error'))


def _create_data():
    #  karma = np.random.uniform(0.05, 0.95, size=1)
    #  return karma[0]
コード例 #28
0
ファイル: timerwidget.py プロジェクト: saymiss/TimerWidget
import pickle
import datetime
from math import ceil, floor
from operator import itemgetter

# Creating the toggl API object
from toggl.TogglPy import Toggl

toggl_api = "api_key"
toggl = Toggl()
toggl.setAPIKey(toggl_api)

# Creating the Todoist API object
from pytodoist import todoist as Todoist

todoist = Todoist.login('email', 'password')

# Change this value to alter the number of columns in the grid of timers
COLS = 3


class TimerView(ui.View):
    """
    The TimerView Widget is the Toggl Today Widget that should really be in the app, but its even better. This widget
    interfaces with your Todoist account too, allowing you to track the amount of time spent on a given task in
    Todoist. It assumes you have corresponding Labels in Todoist for the projects you have in Toggl (as this is how
    my workflow is setup).

    When you click a timer in the widget, if there are no tasks associated with that Label in Todoist, it start the
    timer. If there are tasks, it opens a series of pages listing all the tasks (8 per page), and allows you to select
    one. If you do, it starts a Toggl timer in the correct project with the description as the content of the task,
コード例 #29
0
ファイル: grocery_list.py プロジェクト: aellahi/meal_planning
# List recipes to create grocery list from:
files = input("Enter comma separated list of recipe files: ")
recipe_list = files.split(',')

recipe_dfs = [pd.read_csv(File) for File in recipe_list]

# combine all ingredients
all_ingredients = pd.concat(recipe_dfs)
all_ingredients.sort_values(by='ingredient', inplace=True)
summed_ingredients = all_ingredients.groupby(['ingredient', 'unit']).sum()
summed_ingredients.reset_index(inplace=True)

# load ToDoist user and password
with open('todoist_login.json', 'r') as json_file:
    user_credentials = json.load(json_file)

# login to Todoist
user = todoist.login(user_credentials['user'], user_credentials['password'])

# Load Groceries project
groceries = user.get_project('Groceries')

# iterate through summed_ingredients and add to Groceries
for row in summed_ingredients.itertuples():
    tup = (row.ingredient, row.amt)
    str_list = [x for x in map(str, tup)]
    to_add = ' '.join(str_list)
    added = groceries.add_task(to_add)
    if added.content:
        print(f"Successfully added {to_add}.")
コード例 #30
0
# Communication: 	Please email [email protected] with "[CreateProjectsLabels Comment]" at the beginning for the subject line.

import csv
import time
from pytodoist import todoist

username = raw_input("Please enter username: "******"Please enter password: "******"./OmniFocus.csv"

# Since transactions with the todoist API are throttled, you will reach
# a limit before completing the list.  Change rowStart to one more than the
# last one completed -- tracked by 'print "Just Completed row: "' below.
rowCounter = 0
rowStart = 0

taskreader = csv.reader(open(file), delimiter=',')
for row in taskreader:

	if rowCounter < rowStart:
		rowCounter = rowCounter + 1
		continue
コード例 #31
0
ファイル: t01.py プロジェクト: oceanfokx/TodoHabit
            'todoist': {
                'email': '',
                'password': ''
            },
            'habitica': {
                'user': '',
                'key': ''
            }
        }
        yaml.dump(data_dict, f, default_flow_style=False)
    print('please input your account in account.yaml')
else:
    account_data = load_account_data(account_file)
    habitica_user = habitica(account_data['habitica']['user'],
                             account_data['habitica']['key'])
    user = todoist.login(account_data['todoist']['email'],
                         account_data['todoist']['password'])
    print('login Todoist')
    tasks = user.get_tasks()
    print('get todoist tasks')

    tomorrow = datetime.now() + timedelta(days=1)
    for task in tasks:
        t_priority = task.priority

        if t_priority == 4:
            h_priority = 2
        elif t_priority == 3:
            h_priority = 1.5
        else:
            h_priority = 1
コード例 #32
0
ファイル: pytodoist.py プロジェクト: kodai12/todoist_nvim
 def get_user(self) -> todoist.User:
     return todoist.login(self.email, self.password)
コード例 #33
0
ファイル: test_todoist.py プロジェクト: Danisan/pytodoist
 def test_is_logged_in(self):
     self.user.token = None
     self.assertFalse(self.user.is_logged_in())
     self.user = todoist.login(self.user.email, self.user.password)
     self.assertTrue(self.user.is_logged_in())
コード例 #34
0
ファイル: test_todoist.py プロジェクト: vpineda7/pytodoist
 def test_login_failure(self):
     with self.assertRaises(todoist.RequestError):
         todoist.login(self.user.email, '')
コード例 #35
0
ファイル: todoist.py プロジェクト: EQt/PyTodoist
 def test_login_failure(self):
     with self.assertRaises(todoist.RequestError):
         user = todoist.login('', '')
コード例 #36
0
    global user
    user = gotUser



try:
    userNameFile = open("user.txt", "r")
    userName = userNameFile.read()
    userNameFile.close()
    print(userName)
    if userName !="":
        returnedPassword = keyring.get_password("Pando", userName)
        if returnedPassword!=None:
            try:
                print("Username: "******"\n"+"Password: "+returnedPassword)
                user = todoist.login(userName, returnedPassword)
            # print(self.user)
            except Exception:
                print(Exception)
        else:
            root = Tk()
            listener = LoginListener(getUser)
            # login = ToDoLogin.tkLogin(root, listener)
            login = ttkLogin.tkLogin(root, listener)
            login.startGui()
    else:
        root = Tk()
        listener = LoginListener(getUser)
        # login = ToDoLogin.tkLogin(root, listener)
        login = ttkLogin.tkLogin(root, listener)
        login.startGui()
コード例 #37
0
ファイル: test_todoist.py プロジェクト: Danisan/pytodoist
 def test_login_success(self):
     self.user = todoist.login(self.user.email, _USER_PASSWORD)
     self.assertTrue(self.user.is_logged_in())
コード例 #38
0
ファイル: test_todoist.py プロジェクト: Garee/pytodoist
 def test_login_failure(self):
     with self.assertRaises(todoist.RequestError):
         todoist.login(self.user.email, '')
コード例 #39
0
import time
from pytodoist import todoist
from middleware import TaskManager

print("Starting middleware test")

print("\n========================================")
print("=========  Testing login  ==============")
print("========================================\n")

print("\t- Logging in")

user = todoist.login("*****@*****.**", "roeshulman")
taskManager = TaskManager('', user)

print("\t- Login successfull")

print("\n========================================")
print("========  Test getting tasks  ==========")
print("========================================\n")

print("\t- Getting tasks")

taskManager.set_project("Personal")
tasks = [t.content for t in taskManager.get_tasks()]
print("\t- Tasks: " + repr(tasks))

print("\t- Got tasks")

print("\n========================================")
print("=========  Test adding task  ===========")
コード例 #40
0
import sys
from pytodoist import todoist


user = todoist.login('*****@*****.**', 'secret_password')
project = user.get_project('Automata')

tasks = project.get_tasks()
for task in tasks:
    print(task.content)
コード例 #41
0
 def __init__(self, email, password):
     self.user = todoist.login(email, password)