def process_request(self, goip): if not self.has_request(): log.info("[ProcessRequest] No request to process") return update = self.request.update context = self.request.context try: threading.Thread(target=start_over, args=( update, context, )).start() send_bot_msg(update, context, msg="Виконую запит") result = self.request.process(goip) if result: bot.send(result) send_bot_msg(update, context, msg="Тринь, ісполнєно!") except Exception as e: try: send_bot_msg(update, context, msg="Трапилась помилка") log.error( "[Personal bot] Exception while processing request: %s" % e) except Exception as e1: log.error( "[Personal bot] Exception while handling exception: %s\noriginal exception: %s" % (e1, e)) finally: self.request = None
def __init__(self, url, uname, pwd, sip, spwd): if not url.startswith("http"): url = "http://%s" % url self.url = url self.uname = uname self.pwd = pwd self.sip = sip self.spwd = spwd self.init_browser() self.init_sms() # if daily call duration is from today if vs.daily_calls_duration(field="date", default="1970-01-01 00:00:00.000").date( ) != current_date().date(): vs.increase_weekly_call_duration( vs.daily_calls_duration()) # as we will reset this value reset_daily_values() # set default values for the daily status else: log.info( "[GoipMonitor] Recent restart - do not reset daily calls duration." ) if passed_more_that_sec(vs.monitor_slept_at(notify=True), 30 * 60): # if not restarted within 20-30 minutes bot.send(random_list_item(GREETING_PHRASES)) else: log.info("[GoipMonitor] Regular restart - no greeting was sent")
def process_sent_msg(pdu): log.info('[Process Sent SMS] Sent {} {} {}\n'.format( pdu.sequence, pdu.message_id, pdu.__dir__())) if pdu.status != 0: log.info("[Process Sent SMS] Error sending SMS") bot.send("Помилка при надсиланні СМС") return log.info("[Process Sent SMS] Sent successfully") bot.send("СМС надіслано")
def monitor(self): log.info("[CallMonitor] Started monitor") BrowserWrapper.b.open_menu("Status") waiting_from = None while True: if pbot.has_request(): skip_processing = False request = pbot.request log.info("[CallMonitor] Has personal bot request: %s" % request) # reboot and reset/restore are still possible while in the call # as we have a confirmation message before running each of them if self.call_or_dialing_started(): if isinstance(request, BalanceRequest)\ or isinstance(request, SendSmsRequest)\ or isinstance(request, SendUssdRequest): log.info( "[CallMonitor] Could not process the request while in a call. Waiting..." ) skip_processing = True if isinstance(request, RebootRequest) or isinstance( request, ResetRestoreRequest): waiting_from = None if not skip_processing: log.info("[CallMonitor] Processing personal bot request") pbot.process_request(self.goip) log.info("[CallMonitor] Processed personal bot request") BrowserWrapper.b.open_menu("Status") # send daily status every day once at 23:XX when no-one is using GoIP caller if current_time().hour == 23 and not self.call_or_dialing_started() and\ (not self.daily_status_sent_at or self.daily_status_sent_at.date() != current_date().date()): self.daily_status_sent_at = current_time( ) # using in-memory var to decrease amt of calls to DB vs.set_daily_status_sent(self.daily_status_sent_at) bot.send(daily_status()) # this should be checked every time, so no var defined above sleep_for_sec = 2 if self.call_or_dialing_started( ) else LAST_CALL_SLEEP_SECONDS # if not authorised for < 5 minutes - just wait for this issue to get fixed (with reset/restore?) if not BrowserWrapper.b.is_authorized( ) and not passed_more_that_sec(waiting_from, 5 * 60): log.warning( "[CallMonitor] Browser is not ok - session is not authorised" ) if waiting_from is None: waiting_from = current_time() sleep(sleep_for_sec) continue waiting_from = None # this is the way to get up-to-day info from the page BrowserWrapper.b.driver.refresh() if self.goip.goip_monitor(): # if all is fine with GoIP self.call_monitor() # run call monitor logic else: log.info("[CallMonitor] GoIP monitor is not ok") sleep(sleep_for_sec, print_log=False)
def reboot(self): log.info("[Reboot] Rebooting caller") SmsWrapper.kill() bot.send("Перезавантажую дзвонилку.") BrowserWrapper.b.go_relative_url("reboot.html") sleep(30) self.init_browser() self.init_sms(notify=True) log.info("[Reboot] Finished reboot") bot.send("Перезавантажено дзвонилку.")
def send_caller_status(self, status): seconds_up_sec = BrowserWrapper.b.uptime_sec() up_str = seconds_to_time_str(seconds_up_sec) talk_time_sec = vs.overall_call_duration() talk_str = seconds_to_time_str(talk_time_sec) BrowserWrapper.b.screenshot(name="before-reset", force=True) add_status = "\n%s\n" % status if status else "" bot.send( "Дзвонилка <b>не фуричить</b>.%sЗапущена вже %s\nНаговорили %s\nПереналаштовую..." % (add_status, up_str, talk_str))
def process_received_msg(pdu): frm = pdu.source_addr.decode() content = decode_msg(pdu.short_message) if not content or len(content) == 0: log.info( "[Process Received SMS] Got long message. Using alternative logic") content = decode_msg(pdu.message_payload) content = content or "<empty>" log.info("[Process Received SMS] Message from: %s, content: %s" % (frm, content)) bot.send("Отримано СМС від %s\n%s" % (frm, content), escape=True)
def f_safe(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: try: log.error("[Safe] Exception occurred while running safe() method:") log.error(e) if msg: from src.bot.common import bot bot.send(msg) except Exception as e1: log.error("[Safe] Some really bad exception has happened while handling method exception:") log.error(e1)
def send_ussd(self, num, bot_msg=False): if bot_msg: bot.send("Надсилаю USSD: %s" % num) key = '%d' % randint(10000, 1000000) requests.post(url=self.SEND_USSD % (self.uname, self.pwd, self.ip), data={ 'line1': '1', 'smskey': key, 'action': 'USSD', 'telnum': num, 'send': 'Send' }) return self.process_ussd_response(num, key)
def reset_and_restore(self): last_reg_status = vs.last_reg_status(None) log.info("[Reset and restore] Caller stopped working. %s" % last_reg_status) self.send_caller_status(last_reg_status) vs.set_overall_call_duration(0) # reset it as caller is not working self.reset_config() self.restore_config() if self.statuses_ok(): log.info("[Reset and restore] Caller is working now") bot.send("Дзвонилка <b>працює</b>. Просто крутизна!") else: log.info("[Reset and restore] Caller is not working after fix") bot.send("Дзвонилка <b>не працює</b>. Спробую ще пізніше.")
def goip_monitor(self): # we couldn't afford sleep(600) because we are working with browser in the single thread # instead - just skip method' body till the sleep time is elapsed if self.goip_slept_at and not passed_more_that_sec( self.goip_slept_at, GOIP_MONITOR_SLEEP_SECONDS): return True cdr_started = BrowserWrapper.b.by_id("l1_cdrt").text.strip() if cdr_started.startswith("1970-01"): log.error( "[GoipMonitor] Have internal GoIP issue (1970 year at clock).") if vs.last_date_cdr_restart() == current_time().date( ): # if we had the same problem today bot.send( "Переналаштовую дзвонилку бо вона ґеґнула (1970 рік надворі)!" ) self.reset_and_restore() else: vs.set_last_date_cdr_restart(current_time().date( )) # if this is the first problem occurrence bot.send( "Перезавантажую дзвонилку бо вона знову ні-гугу (1970 рік надворі)!" ) self.reboot() # open the 'Status' tab again to support the logic in rest of the cycle BrowserWrapper.b.open_menu("Status") # just waiting for the fix to be applied. Nothing could be done now return False # reason for the status check is doing fix only if GoIP problem persists for >1 cycle goip_is_working = self.statuses_ok() if not goip_is_working and vs.last_reg_status( ) == self.voip_connection_status: self.reset_and_restore() # open the 'Status' tab again to support the logic in rest of the cycle BrowserWrapper.b.open_menu("Status") self.voip_connection_status = vs.last_reg_status() self.goip_slept_at = current_time( ) # we have this in-memory var to decrease amt of calls to the DB vs.set_monitor_slept_at( self.goip_slept_at ) # we are using this value as heartbeat for the whole GoIP monitor log.info("[GoipMonitor] Sleeping for %d sec..." % GOIP_MONITOR_SLEEP_SECONDS) if not goip_is_working: # just waiting for the fix to be applied. Nothing could be done now log.error( "[GoipMonitor] Patient is not ok. Will check again soon.") return False return True
def send_sms(self, num, msg): log.info("[Send SMS] Number '%s', message '%s'" % (num, msg)) # Two parts, UCS2, SMS with UDH parts, encoding_flag, msg_type_flag = gsm.make_parts(msg) for part in parts: pdu = self.client.send_message( source_addr_ton=consts.SMPP_TON_INTL, dest_addr_ton=consts.SMPP_TON_INTL, source_addr=SENDER_PHONE, destination_addr=num, short_message=part, data_coding=encoding_flag, esm_class=msg_type_flag, registered_delivery=True, ) log.debug("[Send SMS] PDU Sequence # %d" % pdu.sequence) bot.send("Надсилаю СМС до %s\n%s" % num, msg)
def __init__(self, url, uname, pwd, notify_module_is_up=False): self.url = url self.ip = url.split('://')[1] if url.startswith('http') else url self.uname = uname self.pwd = pwd log.info("[SMS Monitoring] Started") try: client = smpp_client.Client(self.ip, SMPP_PORT) client.set_message_received_handler( lambda pdu: process_received_msg(pdu)) client.set_message_sent_handler(lambda pdu: process_sent_msg(pdu)) client.connect() client.bind_transceiver(system_id=SMPP_USER, password=SMPP_SECRET) log.info("[SMS Monitoring] Attempting to listen...") process = multiprocessing.Process(target=client.listen) process.start() self._all_processes.append(process) log.info("[SMS Monitoring] Listening") if notify_module_is_up: bot.send("СМС моніторинг працює") self.client = client except exceptions.ConnectionError as e: bot.send("СМС моніторинг не працює.") raise Exception("SMS module is down", e)
def bot_message(self, text): text = text.format(number=self.any_call_number()) if self.last_msg: return bot.edit(msg=self.last_msg, text=text) return bot.send(text=text)