Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Created November 7, 2014 19:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachallaun/1c7a1cfac8260bc47dbd to your computer and use it in GitHub Desktop.
Save zachallaun/1c7a1cfac8260bc47dbd to your computer and use it in GitHub Desktop.
Zulip TODO bot
import zulip
import os
import json
client = zulip.Client(config_file='.config', verbose=True)
class TodoManager(object):
def __init__(self, client):
self.client = client
self.todo_file = ".todos"
self.todos = self.init_todos()
def __call__(self, message):
self.handle_message(message)
def init_todos(self):
try:
with open(self.todo_file) as f:
try:
return json.load(f)
except ValueError:
return {}
except IOError:
return {}
def persist(self):
with open(self.todo_file, 'w') as f:
json.dump(self.todos, f)
def send_message(self, recipient, content):
self.client.send_message({
'type': 'private',
'to': recipient,
'content': content
})
def handle_message(self, message):
if message['sender_email'] == self.client.email:
return None
content = message['content']
id = str(message['sender_id'])
if content.startswith('todos'):
response = self.todos_for(id)
elif content.startswith('todo:'):
_, todo = content.split('todo: ')
self.add_todo(id, todo)
response = "Added."
elif content.startswith('done:'):
_, todo_index = content.split('done: ')
response = self.remove_todo(id, int(todo_index))
else:
response = "I don't understand."
self.send_message(message['sender_email'], response)
def add_todo(self, id, todo):
todos = self.todos.get(id, [])
todos.append(todo)
self.todos[id] = todos
self.persist()
def remove_todo(self, id, todo_index):
todos = self.todos.get(id, [])
try:
todo = todos.pop(todo_index)
self.todos[id] = todos
self.persist()
return "Done: {}".format(todo)
except IndexError:
return "Invalid todo index."
def todos_for(self, id):
todos = self.todos.get(id, [])
if len(todos) > 0:
todos_with_index = enumerate(todos)
return "**Todos:**\n" + "\n".join(map(self.format_todo_with_index, todos_with_index))
else:
return "You have no todos."
def format_todo_with_index(self, todo_with_index):
index, todo = todo_with_index
return "{}. {}".format(index, todo)
client.call_on_each_message(TodoManager(client))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment