#!/usr/bin/env python3 import os import sys import getopt import requests from libs.pysignald.signald import Signal from configparser import ConfigParser def usage(): print(os.path.basename(sys.argv[0]) + " [-h|--help] [-r|--register]") print("Runs the signal frontend to N. Reads the number to use from n_signal.ini") print(" -h|--help prints this help and exits") print(" -r|--register register the number with signal") def read_config(): config_object = ConfigParser() # config_object.read(os.environ.get('XDG_CONFIG_HOME') + "/n_signal.ini") config_object.read("n_signal.ini") info = config_object["INFO"] return info["number"] def register_signald(number): s = Signal(number) s.register(voice=False) code = input(f"Please input register code send via sms to {number}: ") s.verify(code) def handle_replies(replies): answer = "" for reply in replies: answer = reply['text'] for annotation in reply["annotations"]: a_type = annotation["type"] a_extra = annotation["extra"] if a_type == "command": answer = f"/{answer}: {handle_replies(a_extra)}\n" elif a_type == "link": answer = f"{a_extra} ({answer})" elif a_type == "bold": answer = f"*{answer}*" elif a_type == "italic": answer = f"_{answer}_" elif a_type == "strikethrough": answer = f"~{answer}~" return answer def handle_response(response): replies = response.json()['reply'] return handle_replies(replies) def startup(number): s = Signal(number) # with args @s.chat_handler("^/([^\\s]+)\\s+([^$]*)$", order=10) # This is case-insensitive. def klinger(message, match): # Returning `False` as the first argument will cause matching to continue # after this handler runs. stop = True # TODO: try catch response = requests.post('http://localhost:18080', json={"command": match.group(1), "arguments": match.group(2).strip()}) answer = handle_response(response) return stop, answer # no args @s.chat_handler("^/(.+)$", order=20) # This is case-insensitive. def klinger(message, match): # Returning `False` as the first argument will cause matching to continue # after this handler runs. stop = True # TODO: try catch response = requests.post('http://localhost:18080', json={"command": match.group(1), "arguments": ""}) answer = handle_response(response) return stop, answer s.run_chat() def main(): number = read_config() try: opts, args = getopt.getopt(sys.argv[1:], "hr", ["help", "register"]) except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" usage() sys.exit(2) for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-r", "--register"): register_signald(number) sys.exit() else: assert False, "unhandled option: " + o startup(number) if __name__ == "__main__": main()