remember-remember-bot/src/remember_remember_bot/commands.py

98 lines
3.2 KiB
Python

import os
import deltachat
from remember_remember_bot.util import (
chat_is_active,
get_file_path,
get_lines_from_file,
today_lines,
)
def setup(email: str, password: str, db: str, debug: bool) -> deltachat.Account:
"""Set up the Delta Chat account of the bot.
:param email: the email account for the bot, e.g. bot@example.org
:param password: the password for the email account
:param db: the path to the database
:param debug: whether to show low-level deltachat FFI events
:return: a configured and running Delta Chat account object
"""
ac = deltachat.account.Account(db_path=db)
ac.set_config("delete_server_after", "2")
ac.set_config("displayname", "remember, remember")
ac.run_account(email, password, show_ffi=debug)
return ac
def remind_chat(chat: deltachat.Chat):
"""Remind a chat from the last sent file, with all lines which fit today's date."""
if chat_is_active(chat):
file_path = get_file_path(chat)
lines = get_lines_from_file(file_path)
message_text = "\n".join(today_lines(lines))
print(message_text)
chat.send_text(message_text)
def activate_chat(msg: deltachat.Message):
"""Activate a Chat after the user sent /start"""
file_path = get_file_path(msg.chat)
if not os.path.exists(file_path):
reply(
msg.chat,
"You first need to send me a file path with the /file command.",
quote=msg,
)
msg.mark_seen()
return
if msg.chat.get_ephemeral_timer():
msg.chat.set_ephemeral_timer(0)
reply(msg.chat, f"I will send you daily reminders from the file {file_path}.")
msg.chat.set_ephemeral_timer(60 * 60 * 24)
remind_chat(msg.get_sender_contact().create_chat())
def store_file(msg: deltachat.Message):
"""Store a received file and reply without timer to the chat where it was stored"""
new_filename = "./files/" + str(msg.chat.id)
with open(msg.filename, "r") as read_file:
os.makedirs(os.path.dirname(new_filename), exist_ok=True)
with open(new_filename, "w+") as write_file:
write_file.write(read_file.read())
reply(msg.chat, f"Thanks, I will use this file for daily reminders now.", quote=msg)
def send_help(msg: deltachat.Message):
"""Reply to the user with a help message."""
help_text = """
/start\tStart getting daily reminders.
/stop\tStop getting daily reminders.
/file\t(with an attachment) Add a list of entries which I can remind you of at specific dates.
"""
reply(msg.chat, help_text, quote=msg)
def reply(
chat: deltachat.Chat,
text: str,
quote: deltachat.Message = None,
attachment: str = None,
):
"""Reply to a message from a user.
:param chat: the chat where the user's message appeared
:param text: the text of the reply
:param quote: (optional) if you want it as a reply to a specific message
:param attachment: the file path of an attachment
"""
print(str(chat.id), text)
our_reply = deltachat.message.Message.new_empty(chat.account, "text")
our_reply.set_text(text)
if quote:
our_reply.quote = quote
if attachment:
our_reply.set_file(attachment)
chat.send_msg(our_reply)