async def callback_read(event): app_log.debug(event) chat_info = {'ID': event.max_id, 'Status': 'read'} if 'original_update' in event: try: if event.outbox: chat_info.update(await get_outgoing_info(client, app_log, event.original_update.peer)) else: chat_info.update(await get_incoming_info(client, app_log, event.original_update.peer)) app_log.info(chat_info) sink_sms.send_dict(IDENTIFIER, None, chat_info) except Exception as e: event = event.stringify() trace = traceback.format_exc() app_log.warning(event, exc_info=True) app_log.warning(str(chat_info)) sink_sms.send_notif( "Telegram read-message parsing failed!\n%s" % '\n'.join([event, trace, str(chat_info)])) else: app_log.warning("MessageRead-Event has no 'original_update'!:\n" + event.stringify())
def run(lines): init() cmd = lines[0] # print("Command RE matches!") m = command_regex.match(cmd) c = m.groupdict()['command'] ret = None if c in commands: # print("Command: %s" % c) if c.startswith('stat'): ret = status(cmd == 'stat full') elif c == 'daemon-reload': (res, out) = run_cmd([SUDO_PATH, SYSTEMCTL_PATH], "daemon-reload") ret = "daemon-reload: " ret += "OK!" if res else "failed:" ret += "\n%s" % out elif c == 'shutdown now': print("Shutdown initiated..") print("Sending last SMS to %s" % CONTROL_PHONES[0]) sink_sms.send_to(CONTROL_PHONES[0], "SMSGateway: Shutdown initiated.") ret = "SMSGateway: Shutdown initiated." subprocess.call([SUDO_PATH, SYSTEMCTL_PATH, 'poweroff']) print("Good bye!") return elif c == 'reboot': sink_sms.send_notif("SMSGateway: rebooting!") (res, out) = run_cmd([SUDO_PATH, REBOOT_PATH], "Reboot") ret = out elif c == 'apt update': (res, out) = run_cmd([SUDO_PATH, APT_PATH, 'update'], "Apt update") if res == 0: ret = "Apt update:\n%s" % out else: ret = out elif c == 'apt upgrade': (res, out) = run_cmd([SUDO_PATH, APT_PATH, 'upgrade', '-y'], "Apt upgrade", maxlines=12) if res == 0: ret = "Apt upgrade:\n%s" % out else: ret = out else: ret = "Command not implemented:\n%s" % cmd else: ret = "Unknown command:\n%s" % cmd return ret
def handleCommand(mods, text): if conf.KEY and text.startswith("%8%"): text = text.strip()[3:] print(f'Trying to decrypt "{text}"') f = Fernet(conf.KEY) decrypted = f.decrypt(text.encode("utf-8")) text = decrypted.decode("utf-8") lines = text.strip().split('\n') cmd = lines[0].lower().strip() ret = "Unknown Command:\n%s" % text to = conf.CONTROL_PHONES[0] app_log.info("Message has %s lines" % len(lines)) #if len(lines) == 1: app_log.info("Commands: %s" % str(mods)) multiline = len(lines) > 1 for c in mods: if c.check(cmd, multiline): print(f"Mod {c} matched :)") try: ret = c.run(lines) except Exception as e: trace = traceback.format_exc() msg = "Run failed for command %s:\n%s\n%s" % (cmd, e, trace) app_log.error(msg) sink_sms.send_notif(msg) break # elif len(lines) > 2: # if cmd == "SMS": # print("Forwarding SMS") # toL = lines[1] # m = re.match("To: ([0-9 +]+)", toL) # if m: # to = m.group(1).replace(' ', '') # print("Matched To: %s" % to) # ret = '\n'.join(lines[2:]) # else: # print("Couldn't match To: %s" % to) if ret: sink_sms.send_to(to, ret)
def resendSMS(f): # textStarted = False # To = None # textStarted = None # wholeText = '' # text = '' # with open(f, 'r', encoding="8859") as f: # app_log.info("Opened failed SMS") # for line in f: # line = line.rstrip() # wholeText += line # if textStarted == True: # text += "%s\n" % line # else: # m = re.match("To: ([0-9]+)", line) # m_fail = re.match("Fail_reason: (.*)", line) # if m: # To = "+%s" % m.group(1) # elif m_fail: # fail_reason = m_fail.group(1) # app_log.warning("Fail reason: %s" % fail_reason) # elif line == "": # textStarted = True data = readSMS(f, received=False) To = data['address'] text = data['text'] fail_reason = "N/A" if 'Fail_reason' in data: fail_reason = data['Fail_reason'] if To and text: if To in conf.CONTROL_PHONES: app_log.warning("Resending SMS to CONTROL_PHONE") new_text = "RESEND: %s\n%s" % (fail_reason, text) sink_sms.send_notif(new_text) else: app_log.warning("Resending SMS to %s" % To) sink_sms.send_to(To, text) new_text = "RESEND: %s\n%s" % (fail_reason, text) sink_sms.send_notif(new_text) else: new_text = "Invalid failed SMS:\n%s" % '\n'.join(data['lines']) app_log.error(new_text) sink_sms.send_notif(new_text)
async def callback(event): chat_info = {'ID': event.message.id} try: if event.message.out: if not event.message.to_id: raise Exception("No to_id given, but messsage is going out!") chat_info.update(await get_outgoing_info(client, app_log, event.message.to_id)) else: # in chat_info.update(await get_incoming_info(client, app_log, event.message.from_id, event.message.to_id)) if event.message.edit_date: chat_info['edit'] = "True" if event.message.date: date = event.message.date app_log.debug(date) date_utc = date.replace(tzinfo=timezone.utc) chat_info['date'] = date_utc.timestamp() #..strftime('%s') msg = "" if event.message.fwd_from: fwd_from = event.message.fwd_from user_info = {} if fwd_from.from_id: entity = await client.get_entity(fwd_from.from_id) (user_id, name, phone) = get_user_info(entity) user_info['user_id'] = user_id if name: user_info['name'] = name elif fwd_from.channel_id: entity = await client.get_entity(client, fwd_from.channel_id) user_info['name'] = entity.title if 'name' in user_info: msg += f"Forwarded from {user_info['name']}:\n" chat_info.update({'fwd': json.dumps(user_info)}) if event.message.reply_to_msg_id: try: msg += await parse_reply_to(client, app_log, event) except Exception as e: msg += f"Reply parsing failed: {e}\n\n" app_log.warning(e, exc_info=True) app_log.warning(event.stringify()) if event.message.reply_markup: try: chat_info.update(parse_buttons(event.message.reply_markup)) except Exception as e: msg += f"Button parsing failed: {e}\n\n" app_log.warning(e, exc_info=True) app_log.warning(event.stringify()) msg += event.message.message media = event.message.media if media: if msg: msg += "\n" try: msg += parse_media(media) except Exception as e: msg += f"Media parsing failed: {e}" if event.message.out: if 'to' in chat_info: app_log.info("New message to %s!" % chat_info['to']) sink_sms.send_dict(IDENTIFIER, msg, chat_info) # sink_sms.send_from_me(IDENTIFIER, msg, chat_info['to']) else: if 'from' in chat_info: app_log.info("New message from %s!" % chat_info['from']) sink_sms.send_dict(IDENTIFIER, msg, chat_info) # sink_sms.send(IDENTIFIER, msg, user_name, user_number, group_name) app_log.debug(msg) except Exception as e: event = event.stringify() trace = traceback.format_exc() app_log.warning(event, exc_info=True) app_log.warning(str(chat_info)) sink_sms.send_notif( "Telegram message parsing failed!\n%s" % '\n'.join([event, trace, str(chat_info)])) try: client.session.save() except Exception as e: app_log.warning("Could not save session:\n" + e)
from smsgateway import sink_sms import argparse parser = argparse.ArgumentParser() parser.add_argument("unit", help="The unit that failed") args = parser.parse_args() msg = "%s failed, restarting.." % args.unit print("Sending SMS:\n%s" % msg) sink_sms.send_notif(msg)