implement basic run() CLI command which replies to commands

main
missytake 2023-05-19 21:29:29 +02:00
parent 3b770c3cc9
commit b52be982ba
1 changed files with 70 additions and 1 deletions

View File

@ -3,11 +3,12 @@ import time
import click
import deltachat
from deltachat.capi import lib as dclib
def get_control_group(ac: deltachat.account.Account) -> deltachat.chat.Chat | None:
for chat in ac.get_chats():
if len(chat.get_contacts()) == 1 and chat.is_protected() and chat.is_group():
if chat.num_contacts() == 1 and chat.is_protected() and chat.is_group():
if chat.get_name() == "verification bot control group":
return chat
return
@ -69,6 +70,73 @@ def init(ctx, db_path, from_backup) -> None:
click.secho(" verificationbot run\n")
def process_command(ac: deltachat.Account, command: deltachat.Message) -> deltachat.Message:
"""Handle incoming commands, increment the last_command_id.
:param ac: deltachat account object of the bot
:param command: the deltachat message to be handled
:returns the reply to the command
"""
replytext = "reply to " + command.text
reply = deltachat.Message.new_empty(ac, "text")
reply.set_text(replytext)
reply.quote = command
sent_id = dclib.dc_send_msg(ac._dc_context, command.chat.id, reply._dc_msg)
assert sent_id == reply.id
assert reply
def get_next_message_from_group(group: deltachat.Chat, last_message_id: int) -> deltachat.Message:
"""Get next message from a Delta Chat group from the ID of the last message.
:param group: the specific Delta Chat group
:param last_message_id: the ID of the last known message
:return: the next Delta Chat message in the group
"""
for msg in range(len(group.get_messages())):
if group.get_messages()[msg].id == last_message_id:
return group.get_messages()[msg + 1]
@click.command()
@click.option(
"--db-path",
type=str,
help="The directory where the Delta Chat database is stored",
default=os.getenv("HOME") + "/.config/DeltaChat/verificationbot/db.sqlite",
show_default=True,
)
@click.pass_context
def run(ctx, db_path):
ac = deltachat.account.Account(db_path)
if not ac.is_configured():
ctx.fail(
"Please run this first to initialize the bot:\n\n verificationbot init\n"
)
last_command_id = get_control_group(ac).get_messages()[-1].id
ac.start_io()
try:
while True:
control_group = get_control_group(ac)
if control_group.get_messages()[-1].id == last_command_id:
time.sleep(0.1)
continue
print(control_group.get_messages()[-1].id)
next_message = get_next_message_from_group(control_group, last_command_id)
if next_message.quote:
last_command_id = next_message.id
continue # skip replies, they could be ours
try:
reply = process_command(ac, next_message)
finally:
last_command_id = next_message.id
finally:
click.secho("Exiting.")
@click.command(
cls=click.Group, context_settings={"help_option_names": ["-h", "--help"]}
)
@ -79,6 +147,7 @@ def cli_main(ctx):
cli_main.add_command(init)
cli_main.add_command(run)
if __name__ == "__main__":