Added command to /delete tasks

Added command to /check out tasks (until next notification)
Changed tasks from a list to a dictionary
Went to sleep and forgot to commit changes and push
This commit is contained in:
vylion 2017-10-15 10:18:39 +02:00
parent 5a62611267
commit f0e64a26da
2 changed files with 128 additions and 19 deletions

40
chat.py
View file

@ -3,17 +3,19 @@ from task import *
class Chat(object): class Chat(object):
def __init__(self, ident, name): def __init__(self, ident, name):
self.id = ident self.id = ident
self.tasks = [] self.tasks = {}
self.name = name self.name = name
def addTask(self, name, repeat=0, hour=0, day=0, month=0, year=0): def addTask(self, name, repeat=0, hour=0, day=0, month=0, year=0):
t = Task(name, repeat, hour, day, month, year) t = Task(name, repeat, hour, day, month, year)
self.tasks.append(t) if name in self.tasks:
raise ValueError('duplicate key "' + name + '" found')
self.tasks[name] = t
print('new task ' + t.name + ' added:') print('new task ' + t.name + ' added:')
print(str(t) + '\n') print(str(t) + '\n')
return t return t
def getTasks(self, y=0, d=0, m=0, y2=0, d2=0, m2=0): def getTasksRange(self, d=0, m=0, y=0, d2=0, m2=0, y2=0):
dateNow = datetime.now() dateNow = datetime.now()
if y == 0: if y == 0:
y = dateNow.year y = dateNow.year
@ -28,13 +30,33 @@ class Chat(object):
if d2 == 0: if d2 == 0:
d2 = dateNow.day d2 = dateNow.day
dateIni = datetime(y, m, d) dateIni = datetime(y, m, d)
dateEnd = datetime(y2, m2, d2) dateEnd = datetime(y2, m2, d2, 23)
resultTasks = [] resultTasks = []
for t in self.tasks: for t in self.tasks:
print(t) task = self.tasks[t]
if t.getDate() >= dateIni and t.getDate() <= dateEnd: print(task)
resultTasks.append(t) if task.getDate() >= dateIni and task.getDate() <= dateEnd:
resultTasks.append(task)
return resultTasks return resultTasks
def getChatName(self): def getTasks(self):
return self.name resultTasks = []
for _, v in self.tasks.items():
resultTasks.append(v)
return resultTasks
def deleteTask(self, name):
if name in self.tasks:
del self.tasks[name]
return True
return False
def markDone(self, name):
if name in self.tasks:
t = self.tasks[name]
if t.repeat > 0:
t.date += timedelta(t.repeat)
else:
del self.tasks[name]
return True
return False

105
main.py
View file

@ -1,4 +1,5 @@
from telegram import ParseMode
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.error import * from telegram.error import *
from chat import * from chat import *
@ -31,11 +32,11 @@ def start(bot, update):
def help(bot, update): def help(bot, update):
message = 'The task must be stated like this:\n' message = 'The task must be stated like this:\n'
message += '/new repeat hour day/month/year\n\n' message += '/new name repeat hour day/month/year\n\n'
message += 'where __repeat__ is how many days are between each repetition, ' message += 'where _repeat_ is how many days are between each repetition, '
message += '__year__ is optional, __month__ is optional, and __day__ is ' message += '_year_ is optional, _month_ is optional, and _day_ is '
message += 'optional if month is omitted (but the slashes aren\'t)' message += 'optional if month is omitted (but the slashes aren\'t)'
update.message.reply_text(message) update.message.reply_text(message, parse_mode=ParseMode.MARKDOWN)
def addTask(bot, update, args): def addTask(bot, update, args):
global chats global chats
@ -46,7 +47,6 @@ def addTask(bot, update, args):
chat = Chat(tchat.id, title) chat = Chat(tchat.id, title)
else: else:
chat = chats[ident] chat = chats[ident]
# Args: name repeat hour day/month/year # Args: name repeat hour day/month/year
if len(args) > 2: if len(args) > 2:
args[2] = args[2].strip('h') args[2] = args[2].strip('h')
@ -65,10 +65,17 @@ def addTask(bot, update, args):
update.message.reply_text('Task ' + t.name + ' added') update.message.reply_text('Task ' + t.name + ' added')
chats[ident] = chat chats[ident] = chat
"""
except ValueError as ve:
update.message.reply_text('A task already exists under this name')
except Exception as e:
update.message.reply_text('Wrong format. Send /help for more details')
"""
# except: # except:
# update.message.reply_text('Wrong format') # update.message.reply_text('Wrong format')
def getTasksToday(bot,update): def getTasks(bot, update, time):
global chats global chats
tchat = update.message.chat tchat = update.message.chat
ident = str(tchat.id) ident = str(tchat.id)
@ -77,16 +84,90 @@ def getTasksToday(bot,update):
chat = Chat(tchat.id, title) chat = Chat(tchat.id, title)
else: else:
chat = chats[ident] chat = chats[ident]
update.message.reply_text('Today\'s tasks:')
dateNow = datetime.now() dateNow = datetime.now()
if time is 'today':
tasks = chat.getTasksRange()
elif time == 'all':
tasks = chat.getTasks() tasks = chat.getTasks()
for task in tasks: elif time == 'week':
update.message.reply_text(t) now = datetime.now()
week = now + timedelta(7)
tasks = chat.getTasksRange(now.day, now.month, now.year, week.day, week.month, week.year)
elif time == 'month':
now = datetime.now()
_, delta = monthrange(now.year, now.month)
month = now + timedelta(delta)
tasks = chat.getTasksRange(now.day, now.month, now.year, month.day, month.month, month.year)
elif time == 'fortnight':
now = datetime.now()
fort = now + timedelta(14)
tasks = chat.getTasksRange(now.day, now.month, now.year, fort.day, fort.month, fort.year)
if len(tasks) == 0:
update.message.reply_text('There are no tasks under this criteria.')
else:
for t in tasks:
update.message.reply_text(str(t))
chats[ident] = chat chats[ident] = chat
def getTasksToday(bot,update):
update.message.reply_text('Today\'s tasks:')
getTasks(bot, update, 'today')
def getTasksAll(bot,update):
update.message.reply_text('All tasks:')
getTasks(bot, update, 'all')
def getTasksWeek(bot, update):
update.message.reply_text('Tasks on a week from now:')
getTasks(bot, update, 'week')
def getTasksMonth(bot, update):
update.message.reply_text('Tasks on a month from now:')
getTasks(bot, update, 'month')
def getTasksFort(bot, update):
update.message.reply_text('Tasks on 2 weeks from now:')
getTasks(bot, update, 'fortnight')
def stop(bot, update): def stop(bot, update):
pass pass
def deleteTask(bot, update, args):
global chats
tchat = update.message.chat
ident = str(tchat.id)
if not ident in chats:
title = get_chatname(tchat)
chat = Chat(tchat.id, title)
else:
chat = chats[ident]
for name in args:
if chat.deleteTask(name):
update.message.reply_text('Task ' + name + ' deleted succesfully.')
else:
update.message.reply_text('There is no task with name ' + name + '.')
chats[ident] = chat
def checkTask(bot, update, args):
global chats
tchat = update.message.chat
ident = str(tchat.id)
if not ident in chats:
title = get_chatname(tchat)
chat = Chat(tchat.id, title)
else:
chat = chats[ident]
for name in args:
if chat.markDone(name):
update.message.reply_text('Task ' + name + ' checked out.')
else:
update.message.reply_text('There is no task with name ' + name + '.')
chats[ident] = chat
def main(): def main():
parser = argparse.ArgumentParser(description='A Telegram task manager bot.') parser = argparse.ArgumentParser(description='A Telegram task manager bot.')
parser.add_argument('token', metavar='TOKEN', help='The Bot Token to work with the Telegram Bot API') parser.add_argument('token', metavar='TOKEN', help='The Bot Token to work with the Telegram Bot API')
@ -102,7 +183,13 @@ def main():
# on different commands - answer in Telegram # on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("today", getTasksToday)) dp.add_handler(CommandHandler("today", getTasksToday))
dp.add_handler(CommandHandler("all", getTasksAll))
dp.add_handler(CommandHandler("month", getTasksMonth))
dp.add_handler(CommandHandler("week", getTasksWeek))
dp.add_handler(CommandHandler("fortnight", getTasksFort))
dp.add_handler(CommandHandler("new", addTask, pass_args=True)) dp.add_handler(CommandHandler("new", addTask, pass_args=True))
dp.add_handler(CommandHandler("delete", deleteTask, pass_args=True))
dp.add_handler(CommandHandler("check", checkTask, pass_args=True))
#dp.add_handler(CommandHandler("about", about)) #dp.add_handler(CommandHandler("about", about))
dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("stop", stop)) dp.add_handler(CommandHandler("stop", stop))