publickey-bot/src/keyserver_bot/hooks.py
2025-04-06 01:17:44 +02:00

74 lines
2.1 KiB
Python

#!/usr/bin/env python3
from deltachat_rpc_client import events, run_bot_cli, EventType, Message
from email_validator import validate_email, EmailNotValidError
from keyserver_bot.wkd import request_from_wkd
from keyserver_bot.koo import request_from_koo
from keyserver_bot.vcard import construct_vcard, save_vcard
hooks = events.HookCollection()
HELP_MSG = (
"If you send me an email address, "
"I will fetch it's public PGP key "
"(from WKD and keys.openpgp.org) "
"and send you a contact you can encrypt to."
)
@hooks.on(events.NewMessage)
def command(event):
snapshot = event.message_snapshot
if snapshot.text == "/generate-invite":
return snapshot.chat.send_text(snapshot.chat.account.get_qr_code())
if snapshot.text == "Messages are guaranteed to be end-to-end encrypted from now on.":
return
email = snapshot.text
try:
validate_email(email, check_deliverability=False)
except EmailNotValidError:
return snapshot.chat.send_text(HELP_MSG + f"\n\n{email} is not an email address :/")
public_key = request_key_by_email(email)
if not public_key:
return snapshot.chat.send_text("Sorry, I could not find a key for this user.")
vcard = construct_vcard(email, public_key)
vcard_path = f"/tmp/{email}.vcf"
save_vcard(vcard_path, vcard)
return snapshot.chat.send_file(vcard_path)
def request_key_by_email(email) -> str:
domain = email.split("@")[1]
public_key = request_from_wkd(email, domain)
if not public_key:
public_key = request_from_wkd(email, f"openpgpkey.{domain}")
if not public_key:
public_key = request_from_koo(email)
return public_key
@hooks.on(events.RawEvent)
def cleanup(event):
print(event)
if event.kind == EventType.MSG_DELIVERED or event.kind == EventType.MSG_FAILED:
msg = Message(event.account, event.msg_id).get_snapshot()
delete_data(msg)
def delete_data(msg):
contacts = msg.chat.get_contacts()
msg.chat.delete()
for member in contacts:
member.delete()
def main():
run_bot_cli(hooks)
if __name__ == "__main__":
main()