def create_and_store(self): entity = Accumulator_Entity() entity.dt = ceil_dt(utcnow(), 15) filename = self.get_filename(entity.dt) blob = self.bucket.blob(filename) pickle_dump = pickle.dumps(entity) blob.upload_from_string(data=pickle_dump) a = Accumulator.A(entity, blob) return a
def add_temperature2(self, d, value_dict={}): value_dict = scan_and_apply_tz(value_dict) df_t = pd.DataFrame(value_dict, index=[d]) df_t = df_t.applymap(lambda x: np.nan if x is None else x) if "occupancy_flag" in self.temperature: self.temperature["occupancy_flag"].apply(lambda x: 0 if x.isnan() else x) if self.temperature is not None: df_t = check_index(df_t) self.temperature = check_index(self.temperature) self.temperature = self.temperature.append(df_t) else: self.dt = ceil_dt(d, 15) self.temperature = df_t
def add_temperature(self, d, temp=None, humidity=None, motion=None, stove_exhaust_temp=None, temp_basement=None): warnings.warn( "add_temperature(self, d, temp=None, humidity=None, motion=None, stove_exhaust_temp=None, temp_basement=None) is deprecated", DeprecationWarning, stacklevel=2) t = self.temp_dict(temp, humidity, motion, stove_exhaust_temp, temp_basement) df_t = pd.DataFrame(t, index=[d]) if self.temperature is not None: self.temperature = self.temperature.append(df_t) else: self.dt = ceil_dt(d, 15) self.temperature = df_t
def add_temperature(self, d, temp=None, humidity=None, motion=None, stove_exhaust_temp=None, temp_basement=None): """ Deprecated Please use add_temperature(self, d, value_dict={}): """ warnings.warn( "add_temperature(self, d, temp=None, humidity=None, motion=None, stove_exhaust_temp=None, temp_basement=None) is deprecated", DeprecationWarning, stacklevel=2) if temp is None and humidity == None and motion == None and stove_exhaust_temp == None and temp_basement == None: raise ValueError self.load(n=1, hold=True) part = ceil_dt(d, 15) if self.entities[0].entity.dt < part: self.logger.info( "Last partition was for {}. Now we need a new one for {}.". format(self.entities[0].entity.dt.isoformat(), part.isoformat())) self.entities = [self.create_and_store()] self.entities[0].entity.add_temperature(d, temp, humidity, motion, stove_exhaust_temp, temp_basement) self.store_and_release() try: self.entities[0].blob.temporary_hold = True self.entities[0].blob.patch() except Exception as ex: self.logger.warn("Blob HOLD failed : {}".format(ex))
def add_temperature2(self, d, value_dict={}): value_present = False for k in list(value_dict.keys()): if value_dict.get(k) is not None: if isinstance(value_dict.get(k), (bool)): value_dict[k] = int(value_dict.get(k)) if not isinstance(value_dict.get(k), (int, float)) or k == 'timestamp': self.logger.warn( "Accumulator only accepts int, float or boolean - {} : {}" .format(k, value_dict.get(k))) del value_dict[k] else: value_present = True if not value_present: raise ValueError self.load(n=1, hold=True) part = ceil_dt(d, 15) if self.entities[0].entity.dt < part: self.logger.info( "Last partition was for {}. Now we need a new one for {}.". format(self.entities[0].entity.dt.isoformat(), part.isoformat())) self.entities = [self.create_and_store()] self.entities[0].entity.add_temperature2(d, value_dict=value_dict) self.store_and_release() try: self.entities[0].blob.temporary_hold = True self.entities[0].blob.patch() except Exception as ex: self.logger.warn("Blob HOLD failed : {}".format(ex))
def main(): updater = Updater(token=TELEGRAM, use_context=True, request_kwargs={ 'read_timeout': 10, 'connect_timeout': 10 }) dp = updater.dispatcher # group handlers dp.add_handler( MessageHandler(Filters.status_update.new_chat_members, group.added)) # thanks to https://t.me/dotvhs, who likes regex (weird). test: https://regex101.com/r/h4oH0X/2 dp.add_handler( MessageHandler( Filters.regex(r"(\s|^)(/report|@admins?)(\s|$)") & Filters.group, group.report)) dp.add_handler( CommandHandler("reload_admins", group.reload_admins, Filters.group)) # private handlers dp.add_handler(CommandHandler("start", private.start, Filters.private)) dp.add_handler( CommandHandler("settings", private.settings, Filters.private)) dp.add_handler( CallbackQueryHandler(private.select_group, pattern="settings")) dp.add_handler( CallbackQueryHandler(private.group_report, pattern="set_report")) dp.add_handler( CallbackQueryHandler(private.group_reply_confirmation, pattern="set_reply")) dp.add_handler( CallbackQueryHandler(private.group_mention, pattern="set_mention")) dp.add_handler(CallbackQueryHandler(private.back, pattern="set_back")) dp.add_handler( CommandHandler("timeout", private.timeout_command, Filters.private)) dp.add_handler( CommandHandler("help", private.help_command, Filters.private)) dp.add_handler( MessageHandler(Filters.private & Filters.text, private.timeout)) dp.add_handler( CommandHandler("timeoff", private.timeoff_command, Filters.private)) dp.add_handler( MessageHandler(Filters.private & Filters.text, private.timeoff), 1) dp.add_handler( CommandHandler("timeoff_del", private.timeoff_del, Filters.private)) dp.add_error_handler(private.error_handler) # just for the sake of it (BLUE TEXT) dp.add_handler( CommandHandler("reload_admins", private.reload_admins, Filters.private)) updater.start_polling() now = datetime.datetime.now() dt = ceil_dt(now, datetime.timedelta(minutes=30)) # temporary fix td = dt - now updater.job_queue.run_repeating(half_hourly, 60 * 30, first=td.total_seconds(), name="half-hourly", context={ "admins": {}, "date": now.strftime("%d.%m") }) updater.job_queue.run_daily(group_check, datetime.time(12, 0, 0), name="Group check") updater.idle()
def test_ceil_dt_00(): dt = utcnow().replace(minute=46) test = ceil_dt(dt, 15) assert test.minute == 0 assert test.tzinfo == tz
def test_ceil_dt_45(): dt = utcnow().replace(minute=33) test = ceil_dt(dt, 15) assert test.minute == 45 assert test.tzinfo == tz
def test_ceil_dt_15(): dt = utcnow().replace(minute=12) test = ceil_dt(dt, 15) assert test.minute == 15 assert test.tzinfo == tz
def main(): updater = Updater( token=TELEGRAM, use_context=True, request_kwargs={ "read_timeout": 10, "connect_timeout": 10 }, ) dp = updater.dispatcher # group handlers dp.add_handler( ChatMemberHandler(group.chat_member_update, ChatMemberHandler.CHAT_MEMBER)) dp.add_handler( ChatMemberHandler(group.my_chat_member_update, ChatMemberHandler.MY_CHAT_MEMBER)) # thanks to https://t.me/dotvhs and https://t.me/twitface, both of them like regex (weird). # test: https://regex101.com/r/Amrm07/1 dp.add_handler( MessageHandler( Filters.regex(r"^/report\b|(^|\s)@admin[a-z_]{0,27}\b") & Filters.chat_type.groups, group.report, )) dp.add_handler( CommandHandler("reload_admins", group.reload_admins, Filters.chat_type.groups)) dp.add_handler( MessageHandler(Filters.status_update.new_chat_title, group.update_title)) dp.add_handler( MessageHandler(Filters.status_update.migrate, group.update_id)) # this is the administration mode where the bot can kick and restrict members dp.add_handler( CallbackQueryHandler(report_callback.ignore, pattern="report_ignore")) dp.add_handler( CallbackQueryHandler(report_callback.delete, pattern="report_del")) dp.add_handler( CallbackQueryHandler(report_callback.restrict, pattern="report_restrict")) dp.add_handler( CallbackQueryHandler(report_callback.ban, pattern="report_ban")) dp.add_error_handler(private.error_handler) # private handlers, basic setup dp.add_handler( CommandHandler("start", private.start, Filters.chat_type.private)) dp.add_handler( CommandHandler("settings", private.settings, Filters.chat_type.private)) dp.add_handler( CommandHandler("help", private.help_command, Filters.chat_type.private)) # private setting callbacks dp.add_handler( CallbackQueryHandler(private.select_group, pattern="settings")) dp.add_handler( CallbackQueryHandler(private.group_report, pattern="set_report")) dp.add_handler( CallbackQueryHandler(private.group_reply_confirmation, pattern="set_reply")) dp.add_handler( CallbackQueryHandler(private.group_mention, pattern="set_mention")) dp.add_handler( CallbackQueryHandler(private.group_administration, pattern="set_administration")) dp.add_handler( CallbackQueryHandler(private.group_link_back, pattern="set_linked_back")) dp.add_handler( CallbackQueryHandler(private.group_do_link, pattern="set_linked")) dp.add_handler(CallbackQueryHandler(private.group_link, pattern="set_link")) dp.add_handler(CallbackQueryHandler(private.back, pattern="set_back")) # private timeout/timeoff convs timeout_conv = ConversationHandler( entry_points=[ CommandHandler("timeout", private.timeout_command, Filters.chat_type.private), ], states={ private.TIMEOUT_REPLY: [ MessageHandler( Filters.text & (~Filters.command), private.timeout, ) ] }, fallbacks=[CommandHandler("cancel", private.cancel)], ) dp.add_handler(timeout_conv) timeoff_conv = ConversationHandler( entry_points=[ CommandHandler("timeoff", private.timeoff_command, Filters.chat_type.private) ], states={ private.TIMEOFF_REPLY: [ MessageHandler( Filters.text & (~Filters.command), private.timeoff, ) ] }, fallbacks=[CommandHandler("cancel", private.cancel)], ) dp.add_handler(timeoff_conv) dp.add_handler( CommandHandler("timeoff_del", private.timeoff_del, Filters.chat_type.private)) dp.add_handler( CommandHandler("cancel", private.cancel, Filters.chat_type.private)) # just for the sake of it (BLUE TEXT), do not use it in private dp.add_handler( CommandHandler("reload_admins", private.reload_admins, Filters.chat_type.private)) # registering to group member updates updater.start_polling(allowed_updates=[ Update.MESSAGE, Update.CHAT_MEMBER, Update.MY_CHAT_MEMBER, Update.CALLBACK_QUERY, ]) now = datetime.datetime.now() dt = ceil_dt(now, datetime.timedelta(minutes=30)) # temporary fix td = dt - now updater.job_queue.run_repeating( half_hourly, 60 * 30, first=td.total_seconds(), name="half-hourly", context={ "admins": {}, "date": now.strftime("%d.%m") }, ) updater.job_queue.run_daily(backup_job, datetime.time(12, 0, 0), name="Backup database") # set private commands dp.bot.set_my_commands( [ BotCommand("start", "Short greeting message"), BotCommand("settings", "change settings of administrated groups"), BotCommand("help", "Long help message"), BotCommand( "timeout", "set a timeout for some time between now and sometime in the next 24 hours", ), BotCommand( "timeoff", "Specifiy do not disturb times for each day of the week"), BotCommand("timeoff_del", "Delete yourself from the timeoff list"), BotCommand("cancel", "Cancel the current action"), ], scope=BotCommandScopeAllPrivateChats(), ) updater.idle()