def send_notification(self, send_imgs=True): print self.template() if self.img and send_imgs: if args.printall: print "Sending {} images..".format(len(self.img)) sendmsg.send_to_me("", img=self.img) # summary on the bottom sendmsg.send_to_me(self.template())
def notify(d, new): if not new: return if d['type'] == 'episode': text = "new: {title} S{season} E{episode}".format(**d) sendmsg.send_to_me(text) else: text = "new: " + d['title'] sendmsg.send_to_me(text)
def send_summary(self, count=3): last = self.last_flats_like_mine(count) if not last: print "I don't know about any flats" return summary = "\n".join([a.short_template() for a in last]) if self.printall: print summary sendmsg.send_to_me(summary)
def notifier(addr, timeout, max_delay): topic = b"temp" context = zmq.Context() socket = context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, topic) socket.setsockopt(zmq.RCVTIMEO, timeout) socket.connect(addr) logger.info(f"Connected to: '{addr}'") while True: try: msg = socket.recv_multipart() except zmq.error.Again: secs = timeout // 1000 logger.warning(f"no messages after {secs} seconds") socket.close() context.destroy() raise j = json.loads(msg[1]) if j.get('type', '') == "weather": main = j['weather']['main'] desc = j['weather']['desc'] name = j['name'] # this is getting the temper_sub config, which is set to logging # INFO to a file (more to syslog i think?) and this is a debug # exercise anyway so its fine to include this i think # logger.debug(f"weather update for {name}") if j['weather']['precipitation']['any']: state['is_raining'] = True if not state['notified'] or main != state[ 'main'] or desc != state['desc']: notification = f"{name} is raining: {main} - {desc}" logger.info(notification) state['notified'] = True state['desc'] = desc state['main'] = main send_to_me(notification) else: logger.debug("still raining, no change") else: if state['is_raining']: notification = f"{name} stopped raining: {main} - {desc}" logger.info(notification) # unset state state['is_raining'] = False state['notified'] = False state['main'] = '' state['desc'] = '' send_to_me(notification)
def onerror(e): # squawk to telegram, runs after error has been logged if os.environ.get("SUDOISBOT_SYSTEMD"): name = sys.argv[0] msg = f"{name} | {type(e).__name__}: {e}" logger.debug("sending notification of my impending death") try: send_to_me(f"``` {msg} ```") except Exception as e: logger.error(f"failed to send message: {e}") logger.debug("Exiting with '1'") sys.exit(1)
def listener(config): configured_handlers = ConfiguredBotHandlers(config) # Start the bot updater = Updater(config['telegram']['api_key'], use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher # add a handler that will only allow certain users dp.add_handler(MessageHandler(Filters.all, configured_handlers.auth), -1) cmdhandlers = [("start", start), ("help", help), ("ruok", ruok), ("where", where), ("sync", sync), ("whitelight", whitelight), ("bluelight", bluelight), ("temp", configured_handlers.temp24h), ("temp1h", configured_handlers.temp1h), ("temp3h", configured_handlers.temp3h), ("temp2d", configured_handlers.temp2d), ("temp3d", configured_handlers.temp3d), ("temp1w", configured_handlers.temp1w), ("temp1m", configured_handlers.temp1m), ("wificlients", configured_handlers.wificlients)] # on different commands - answer in Telegram for cmd, handler in cmdhandlers: dp.add_handler(CommandHandler(cmd, handler)) # on noncommand i.e message - print help dp.add_handler(MessageHandler(Filters.text, unknown_help)) # log all errors dp.add_error_handler(error) # Start the Bot # if the bot cant connect this throws a lot of # nested exceptions ("excception caused while handling # exception"). It's handler in tglistener.py right now updater.start_polling() logger.info("Idling..") send_to_me("Listener started and ready..") # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
def auth(self, update, context: CallbackContext): # if this function raises an error withotu handling it # then the error handler is responsible for stopping # processing the request. user = update.message.from_user name = get_user_name(user) if user.username in self.authorized: logger.debug(user) if user.username != self.me['username']: send_to_me(f"{name}: `{update.message.text}`") else: logger.warning("Unauthorized user: {}", user) # stay silent and ignore the user #update.message.reply_text(unauthed_text) # then notify me, but only once if user.id not in self.unauthed_attemps: send_to_me(f"`{user}`") send_to_me(f"unauthorized: {name} tried talking to me") self.unauthed_attemps.add(user.id) else: logger.debug("already informed") # finally stop processing the request raise DispatcherHandlerStop
def main(): parser = argparse.ArgumentParser( description="Send messages with as @sudoisbot", add_help=False) parser.add_argument("message", help="Message to send, read stdin otherwise", nargs='?') parser.add_argument("-m", action="store_true", help="ignored, legacy") parser.add_argument( "-t", "--to", help="Whom to message, send to myself if not otherwise specified", ) parser.add_argument("--code", help="format markdown as code", action='store_true', default=False) config, args = init("telegram", parser) if not args.message and args.code: parser.error("--code not valid when using stdin") # use position arg if given, otherwise use stdin if args.message: if args.code: text = codeblock(args.message) else: text = args.message elif args.m: text = "-m" else: stdin = fileinput.input('-') text = codeblock("\n".join(stdin)) # use --to if given, or send to me if args.to: send_msg(args.to, text) else: send_to_me(text)
def sendtelegram_rep(dealer): context = zmq.Context() socket = context.socket(zmq.REP) socket.connect(dealer) logger.info(f"Connected to '{dealer}'") while True: bytedata = socket.recv() j = json.loads(bytedata) # super simple for now logger.debug(j) msg = send_to_me(j['message']) reply = {'timtestamp': datetime.now().isoformat(), 'sent': True, 'tg_message_id': msg['mesage_id']} socket.send_string(json.dumps(reply))
parser.add_argument("--search", default="breidholt", type=str) parser.add_argument("--printall", action="store_true") parser.add_argument("--summary", action="store_true") parser.add_argument("--summary-count", type=int, default=3) args = parser.parse_args() searches = { 'breidholt': "http://www.mbl.is/fasteignir/leit/?q=e09ddca032a239798b5f3c4ac91beb50", 'test': "http://www.mbl.is/fasteignir/leit/?q=80f323c5382397611e72800316f250d1" } try: f = MblFasteign(args.filename, printall=args.printall) if args.summary: f.send_summary(args.summary_count) sys.exit(0) if args.printall: print "Looking up flats from search results.." newflats = f.parse_new_flats(searches[args.search]) if newflats or args.printall: f.send_summary() except Exception as e: sendmsg.send_to_me("fasteign.py: {}".format(e)) raise finally: f.write_json()