def update(self, noticia: Noticia) -> dict: update_autor = False try: noticia_doc = NoticiaModel.objects.get(id=noticia.oid) except ValidationErrorMongo: raise InvalidNoticiaID(noticia.oid) except DoesNotExist: log.info( 'Tentativa de atualização de notícia com ID inexistente na base.' ) return {} for k, v in noticia.dict().items(): # verificando se o autor possui nome para update if k == 'autor': if isinstance(v, dict) and v['nome'] is not None: noticia_doc.autor.nome = v['nome'] update_autor = True continue # setando novos valores para atualizacao if v is not None: setattr(noticia_doc, k, v) if update_autor: noticia_doc.autor.save() noticia_doc.save() return noticia_doc.to_dict()
def create_app(): app_flask = Flask(__name__) secret = secrets.token_urlsafe(32) app_flask.secret_key = secret app_flask.config.from_object('src.custom_config.DevelopmentConfig') # path = src.config['PATH_CONFIG'] os.environ['PATH_CONFIG']='./config/Dashboard_dev.yaml' yml = init_properties(os.environ['PATH_CONFIG']) PropertiesDb(yml['db']) PropertiesGenerales(yml['generales']) PropertiesDf(yml['df']) PropertiesSQL(yml['sql']) PropertiesQueries(yml['queries']) PropertiesQueriesHistorico(yml['queries_historicos']) PropertiesDemanda(yml['queries_distribucion_demanda']) PropertiesTendencia(yml['queries_tendencia_venta']) PropertiesEstancia(yml['queries_estancia']) PropertiesUsuario(yml['nuevo_usuario']) PropertiesCostos(yml['costos']) app_flask.register_blueprint(controller_module) app_flask.register_blueprint(errors) db = Db() db.create_session() log.info("Empieza la aplicacion") return app_flask
def secret_yaml(self, config): """Update secret.yaml""" if config.version == "0.0.1": if FF.is_enabled("WALBOT_FEATURE_NEW_CONFIG") == "1": os.makedirs("db", exist_ok=True) sqlite3 = importlib.import_module("sqlite3") con = sqlite3.connect(os.path.join("db", "secret.db")) cur = con.cursor() cur.execute("CREATE TABLE db_info (key text, value text)") cur.execute("INSERT INTO db_info VALUES ('version', '0.1.0')") cur.execute("CREATE TABLE tokens (key text, value text)") cur.execute("INSERT INTO tokens VALUES ('discord', ?)", (config.token, )) con.commit() con.close() os.remove(self.config_name + '.yaml') log.info("Successfully migrated contig.yaml to db/config.db!") else: config.__dict__["mail"] = { "smtp_server": None, "email": None, "password": None, } config.__dict__["admin_email_list"] = list() self._bump_version(config, "0.0.2") if config.version == "0.0.2": log.info(f"Version of {self.config_name} is up to date!") else: log.error( f"Unknown version {config.version} for {self.config_name}!")
async def on_message(self, message: discord.Message) -> None: try: if self.config.guilds[message.channel.guild.id].ignored: return log.info(str(message.author) + " -> " + message.content) if message.author.id == self.user.id: return if isinstance(message.channel, discord.DMChannel): return if message.channel.guild.id is None: return if self.config.guilds[message.channel.guild.id].is_whitelisted: if message.channel.id not in self.config.guilds[ message.channel.guild.id].whitelist: return if message.author.id not in self.config.users.keys(): self.config.users[message.author.id] = User(message.author.id) if self.config.users[ message.author. id].permission_level < const.Permission.USER.value: return if not message.content.startswith( self.config.commands_prefix ) and not self.user.mentioned_in(message): return await message.channel.send(self.bot_response) except Exception: log.error("on_message failed", exc_info=True)
def markov_yaml(self, config): """Update markov.yaml""" if config.version == "0.0.1": config.__dict__["min_chars"] = 1 config.__dict__["min_words"] = 1 self._bump_version(config, "0.0.2") if config.version == "0.0.2": config.__dict__["chains_generated"] = 0 self._bump_version(config, "0.0.3") if config.version == "0.0.3": config.__dict__["max_chars"] = 2000 config.__dict__["max_words"] = 500 self._bump_version(config, "0.0.4") if config.version == "0.0.4": config.model[""].__dict__["word"] = None self._bump_version(config, "0.0.5") if config.version == "0.0.5": for i, _ in enumerate(config.filters): config.__dict__["filters"][i] = re.compile( config.filters[i].pattern, re.DOTALL) self._bump_version(config, "0.0.6") if config.version == "0.0.6": config.__dict__["ignored_prefixes"] = dict() self._bump_version(config, "0.0.7") if config.version == "0.0.7": log.info(f"Version of {self.config_name} is up to date!") else: log.error( f"Unknown version {config.version} for {self.config_name}!")
def stop(self, _, main_bot=True): if not BotCache(main_bot).exists(): return log.error( "Could not stop the bot (cache file does not exist)") bot_cache = BotCache(main_bot).parse() pid = bot_cache["pid"] if pid is None: return log.error( "Could not stop the bot (cache file does not contain pid)") if psutil.pid_exists(pid): if sys.platform == "win32": # Reference to the original solution: # https://stackoverflow.com/a/64357453 import ctypes kernel = ctypes.windll.kernel32 kernel.FreeConsole() kernel.AttachConsole(pid) kernel.SetConsoleCtrlHandler(None, 1) kernel.GenerateConsoleCtrlEvent(0, 0) else: os.kill(pid, signal.SIGINT) while psutil.pid_exists(pid): log.debug("Bot is still running. Please, wait...") time.sleep(0.5) log.info("Bot is stopped!") else: log.error("Could not stop the bot (bot is not running)") BotCache(main_bot).remove()
async def on_ready(self) -> None: log.info( f"Logged in as: {self.user.name} {self.user.id} ({self.__class__.__name__}), " f"instance: {self.instance_name}") for guild in self.guilds: if guild.id not in self.config.guilds.keys(): self.config.guilds[guild.id] = GuildSettings(guild.id)
def _handle_mentions(self, update: Update, context: CallbackContext) -> None: text = update.message.text log.info("(" + update.message.chat.title + ") " + update.message.from_user.username + ": " + text) if not check_auth(update): return result = bc.markov.generate() reply(update, result)
def __init__(self, name: str, config: Config, secret_config: SecretConfig, intents: discord.Intents) -> None: super().__init__(intents=intents) self.repl = None bc.instance_name = self.instance_name = name self.config = config self.secret_config = secret_config self.bot_cache = BotCache(True) self.loop.create_task(self._process_reminders()) self.loop.create_task(VoiceRoutine(self.bot_cache).start()) self.loop.create_task(self._repl_routine()) bc.config = self.config bc.commands = self.config.commands bc.background_loop = self.loop bc.latency = lambda: self.latency bc.change_status = self._change_status bc.change_presence = self.change_presence bc.close = self.close bc.secret_config = self.secret_config bc.info = BotInfo() bc.plugin_manager.register() bc.fetch_channel = self.fetch_channel if not bc.args.fast_start: log.debug("Started Markov model checks...") if bc.markov.check(): log.info("Markov model has passed all checks") else: log.info( "Markov model has not passed checks, but all errors were fixed" )
async def on_message_edit(self, old_message: discord.Message, message: discord.Message) -> None: if message.embeds != old_message.embeds: log.info( f"<{message.id}> (edit, embed update) {message.author} -> {message.content}" ) return if self.config.guilds[message.channel.guild.id].ignored: return bc.message_buffer.push(message) log.info( f"<{message.id}> (edit) {message.author} -> {message.content}") if message.author.id == self.user.id: return if isinstance(message.channel, discord.DMChannel): return if message.channel.guild.id is None: return if self.config.guilds[message.channel.guild.id].is_whitelisted: if message.channel.id not in self.config.guilds[ message.channel.guild.id].whitelist: return if message.author.id not in self.config.users.keys(): self.config.users[message.author.id] = User(message.author.id) if self.config.users[message.author.id].permission_level < 0: return if message.content.startswith(self.config.commands_prefix): await self._process_command(message)
async def on_message(self, message: discord.Message) -> None: await bc.plugin_manager.broadcast_command("on_message", message) if self.config.guilds[message.channel.guild.id].ignored: return bc.message_buffer.push(message) log.info(f"<{message.id}> {message.author} -> {message.content}") if message.author.id == self.user.id: return if isinstance(message.channel, discord.DMChannel): return if message.channel.guild.id is None: return if self.config.guilds[message.channel.guild.id].is_whitelisted: if message.channel.id not in self.config.guilds[ message.channel.guild.id].whitelist: return if message.author.id not in self.config.users.keys(): self.config.users[message.author.id] = User(message.author.id) if self.config.users[message.author.id].permission_level < 0: return if message.content.startswith(self.config.commands_prefix): await self._process_command(message) else: await self._process_regular_message(message) await self._process_repetitions(message)
def home(): # if session['logged_in']==True: log.info("Consulta API Indicadores Actuales") dictionary_index = srv.return_final_response() dictionary_index_json = json.dumps(dictionary_index.__dict__) log.info("Termina Consulta API Indicadores Actuales") return render_template("index.html", index_dictionary=dictionary_index_json)
def main(args): log.info("Reading config.yaml") config = Util.read_config_file(const.CONFIG_PATH) if config is None: config = Config() config.commands.update() log.info(f"Exporting help to {args.out_file}") config.commands.export_help(args.out_file)
def nuevo_usuario(): nombre = request.json["nombre"] apellido = request.json["apellido"] username = request.json["username"] password = request.json["password"] srv_usuario.nuevo_usuario(nombre, apellido, username, password) log.info("Consulta API nuevo usario") return "Usuario Creado"
def query_costos_inventario(): lista_diccionario = [] engine = db.create_session() consulta = engine.execute(sqlalchemy.text(queries.QUERY_COSTOS_INVENTARIO)) for x in consulta: lista_diccionario.append(x) log.info("Consulta Dao Costos") return lista_diccionario
def serialize(self, filename: str, dumper: type = yaml.Dumper) -> None: with open(filename, 'wb') as markov_file: markov_file.write( yaml.dump(self, Dumper=dumper, encoding='utf-8', allow_unicode=True)) log.info("Saving of Markov module data is finished")
def return_final_response(): log.info("Consulta Service Final Response") fecha = ultima_fecha('fecha') bebidas, platillos, vinos = producto_mas_vendido_query(fecha) return Response(producto_mas_vendido_bebidas=bebidas,\ producto_mas_vendido_platillos=platillos, producto_mas_vendido_vinos=vinos,\ utilidad_por_hora=utilidad_por_hora_query(fecha),costo_por_hora=costo_por_hora_query(fecha),\ venta_por_hora=venta_por_hora_query(fecha),mesero=mesero_query(fecha),monto_volumen=monto_volumen(fecha))
async def on_raw_message_edit( self, payload: discord.RawMessageUpdateEvent) -> None: try: log.info( f"<{payload.message_id}> (raw_edit) {payload.data['author']['username']}#" f"{payload.data['author']['discriminator']} -> {payload.data['content']}" ) except KeyError: pass
def query_costos(fecha_menor, fecha_mayor): lista_diccionario = [] engine = db.create_session() consulta = engine.execute( sqlalchemy.text(queries.QUERY_COSTOS.format(fecha_menor, fecha_mayor))) for x in consulta: lista_diccionario.append(x) log.info("Consulta Dao Costos") return lista_diccionario
def return_final_response(fecha_menor, fecha_mayor): log.info("Consulta Service Historicos Final Response") bebidas, platillos, vinos = producto_mas_vendido_query_historico( fecha_menor, fecha_mayor) return Response(producto_mas_vendido_bebidas=bebidas,\ producto_mas_vendido_platillos=platillos, producto_mas_vendido_vinos=vinos,\ utilidad_por_hora=utilidad_por_hora_query_historico(fecha_menor,fecha_mayor),costo_por_hora=costo_por_hora_query_historico(fecha_menor,fecha_mayor),\ venta_por_hora=venta_por_hora_query_historico(fecha_menor,fecha_mayor),mesero=mesero_query_historico(fecha_menor,fecha_mayor),monto_volumen=monto_volumen_historico(fecha_menor,fecha_mayor))
def check_updates(context: AutoUpdateContext) -> bool: """Function that performs updates check. It is called periodically""" old_sha = context.repo.head.object.hexsha try: context.repo.remotes.origin.fetch() except Exception as e: return log.error( f"Fetch failed: {e}. Skipping this cycle, will try to update on the next one" ) new_sha = context.repo.remotes.origin.refs['master'].object.name_rev.split( )[0] log.debug(f"{old_sha} {new_sha}") if old_sha == new_sha: return log.debug("No new updates") bot_cache = importlib.import_module("src.bot_cache").BotCache(True).parse() if bot_cache is None: return log.warning( "Could not read bot cache. Skipping this cycle, will try to update on the next one" ) if "do_not_update" not in bot_cache.keys(): return log.warning( "Could not find 'do_not_update' field in bot cache. " "Skipping this cycle, will try to update on the next one") if bot_cache["do_not_update"]: return log.debug( "Automatic update is not permitted. Skipping this cycle, will try to update on the next one" ) context.repo.git.reset("--hard") try: g = git.cmd.Git(os.getcwd()) g.pull() except git.exc.GitCommandError as e: if "Connection timed out" in e.stderr or "Could not resolve host" in e.stderr: log.warning(f"{e.command}: {e.stderr}") else: raise e subprocess.call(f"{sys.executable} -m pip install -r requirements.txt", shell=True) minibot_response = "WalBot automatic update is in progress. Please, wait..." subprocess.call( f"{sys.executable} walbot.py startmini --message '{minibot_response}' --nohup &", shell=True) subprocess.call(f"{sys.executable} walbot.py stop", shell=True) if context.check_versions(): subprocess.call(f"{sys.executable} walbot.py patch", shell=True) subprocess.call(f"{sys.executable} walbot.py start --fast_start --nohup &", shell=True) while True: time.sleep(1) bot_cache = importlib.import_module("src.bot_cache").BotCache( True).parse() if bot_cache is not None and bot_cache["ready"]: subprocess.call(f"{sys.executable} walbot.py stopmini", shell=True) log.info("Bot is fully loaded. MiniWalBot is stopped.") break log.debug("Bot is not fully loaded yet. Waiting...") return True
def get_fecha(): log.info("Consulta API Historicos") fecha_menor = request.json["fecha_menor"] fecha_mayor = request.json["fecha_mayor"] dictionary_index = srv_historicos.return_final_response( fecha_menor, fecha_mayor) dictionary_index_json = json.dumps(dictionary_index.__dict__) log.info("Termina Consulta API Historicos") return dictionary_index_json
def monto_volumen_historico(fecha_menor, fecha_mayor): log.info("Consulta Service Historicos Monto Volumen Historico") lista_valores = [] diccionario = dao.query_monto_volumen_historico(fecha_menor, fecha_mayor) for d in diccionario: val=MontoVolumen(monto='{0:,.2f}'.format(d['monto']),volumen='{0:,.2f}'.format(d['volumen']),utilidad='{0:,.2f}'.format(d['utilidad']),\ costo='{0:,.2f}'.format(d['costo']),personas=d['personas'],venta=d['monto']) lista_valores.append(val.__dict__) log.info(len(lista_valores)) return lista_valores
def utilidad_por_hora_query(fecha): log.info("Consulta Service Utilidad Por Hora") lista_utilidad_por_hora = [] diccionario = dao.query_utilidad_por_hora(fecha) for d in diccionario: u=UtilidadPorHora(hora=d['hora_vendido'],utilidad=d['utilidad_total'],utilidad_bebidas_hora=d['utilidad_bebidas'],\ utilidad_platillos_hora=d['utilidad_platillos'],utilidad_vinos_hora=d['utilidad_vinos']) lista_utilidad_por_hora.append(u.__dict__) log.info(len(lista_utilidad_por_hora)) return lista_utilidad_por_hora
def query_estancia(fecha_menor, fecha_mayor): engine = db.create_session() consulta = engine.execute( sqlalchemy.text(queries.QUERY_ESTANCIA.format(fecha_menor, fecha_mayor))) lista_diccionario = [] for c in consulta: lista_diccionario.append(c) log.info("Consulta Dao Distribucion Demanda") return lista_diccionario
def costo_por_hora_query_historico(fecha_menor, fecha_mayor): log.info("Consulta Service Historicos Costo Por Hora Historico") lista_costo_por_hora = [] diccionario = dao.query_costo_por_hora_historico(fecha_menor, fecha_mayor) for d in diccionario: c=CostoPorHora(hora=d['hora_vendido'],costo=d['costo_total'],costo_bebidas_hora=d['costo_bebidas'],\ costo_platillos_hora=d['costo_platillos'],costo_vinos_hora=d['costo_vinos']) lista_costo_por_hora.append(c.__dict__) log.info(len(lista_costo_por_hora)) return lista_costo_por_hora
def costos(): log.info("Consulta API Costos") fecha_menor = request.json["fecha_menor"] fecha_mayor = request.json["fecha_mayor"] try: service_response = srv_costos.costos(fecha_menor, fecha_mayor) log.info("Termina Consulta API Costos") return json.dumps(service_response) except: return json.dumps("Error")
def estancia(): log.info("Consulta API Tendencia Venta") fecha_menor = request.json["fecha_menor"] fecha_mayor = request.json["fecha_mayor"] try: service_response = srv_estancia.estancia(fecha_menor, fecha_mayor) log.info("Termina Consulta API Tendencia Venta") return json.dumps(service_response) except: return json.dumps("Error")
def distribucion_demada(): log.info("Consulta API Distribucion Demanda") fecha_menor = request.json["fecha_menor"] fecha_mayor = request.json["fecha_mayor"] try: service_response = srv_demanda.distribucion_demanda_mes( fecha_menor, fecha_mayor) log.info("Termina Consulta API Distribucion Demanda") return json.dumps(service_response.__dict__) except: return json.dumps("Error")
def venta_por_hora_query_historico(fecha_menor, fecha_mayor): log.info("Consulta Service Historicos Venta Por Hora") lista_venta_por_hora = [] diccionario = dao.query_venta_por_hora_historico(fecha_menor, fecha_mayor) for d in diccionario: v=VentaPorHora(dinero=d['dinero'],hora=d['hora'],volumen_venta=d['volumen_venta'],\ volumen_venta_bebidas_hora=d['volumen_venta_bebidas_hora'],volumen_venta_platillos_hora=d['volumen_venta_platillos_hora'],\ volumen_venta_vinos_hora=d['volumen_venta_vinos_hora'],monto_venta_bebidas_hora=d['monto_venta_bebidas_hora'],monto_venta_platillos_hora=d['monto_venta_platillos_hora'],\ monto_venta_vinos_hora=d['monto_venta_vinos_hora']) lista_venta_por_hora.append(v.__dict__) log.info(len(lista_venta_por_hora)) return lista_venta_por_hora