def bote3(update: Update, context: CallbackContext): data = db.select("data") bote = db.select("botes") persona = data[data.id == update.effective_user.id].squeeze() logger.warning( f"{update.effective_chat.type} -> {update.effective_user.first_name} ha enviado el motivo {update.message.text}" ) if context.user_data["tipo"] == "GASTO": cantidad = float(context.user_data["cantidad"]) db.insert_gastos(persona.id, update.message.text, cantidad, datetime.today().strftime('%d/%m/%Y'), persona.apodo) mensaje_tesorera = f"{persona.apodo} ha gastado {cantidad}€ en {update.message.text}" mensaje_usuario = f"Has metido el gasto de {cantidad}€ con el concepto '{update.message.text}'" else: cantidad = float(context.user_data["tipo"] + context.user_data["cantidad"]) bote_actual = bote.iloc[-1].total + cantidad db.insert_bote(update.effective_user.id, cantidad, bote_actual, update.message.text) if context.user_data["tipo"] == "+": mensaje_tesorera = f"{persona.apodo} ha metido {context.user_data['cantidad']}€ " \ f"en el bote con el concepto '{update.message.text}'.\nHay {bote_actual}€ en el bote" else: mensaje_tesorera = f"{persona.apodo} ha sacado {context.user_data['cantidad']}€ " \ f"del bote con el concepto '{update.message.text}'.\nHay {bote_actual}€ en el bote" mensaje_usuario = f"Bote actualizado.\nHay {bote_actual}€ en el bote" context.bot.deleteMessage(update.effective_chat.id, context.user_data["oldMessage"].message_id) context.bot.deleteMessage(update.effective_chat.id, update.message.message_id) context.bot.sendMessage(update.effective_chat.id, mensaje_usuario) context.bot.sendMessage(ID_TESORERIA, mensaje_tesorera) return ConversationHandler.END
def recoradar_tareas(context: CallbackContext): all_tareas = db.select("tareas") data = db.select("data") for _, tarea in all_tareas.iterrows(): for persona in tarea.personas: context.bot.sendMessage(chat_id=persona, parse_mode="HTML", text=f"Tienes esta tarea pendiente:\n{tarea_to_text(tarea, data)}")
def democracia(update: Update, context: CallbackContext) -> None: update.callback_query.delete_message() logger.warning(f"{update.effective_user.first_name} ha ejecutado el comando democracia") data = db.select("data") encuestas = db.select("encuestas") encuestas = encuestas[~encuestas.end] texto = "Estos son los miserables que odian la democracia:\n" for _, persona in data.iterrows(): questions = "" total = 0 for _, encuesta in encuestas.iterrows(): if persona.id not in encuesta.votes: questions += f"- <a href='{encuesta.url}'>{encuesta.question}</a>\n" total += 1 if questions: texto += f"- <a href='tg://user?id={persona.id}'>{persona.apodo}</a>" if total == 1: texto += "\n" else: texto += f"x{total}\n" text = f"{persona.apodo}, al vivir en una democracia tienes derecho a votar en las encuestas\n" + questions try: context.bot.sendMessage(chat_id=persona.id, parse_mode="HTML", text=text) except: print(f"{persona.apodo} con id {persona.id} NO tiene activado el bot") context.bot.sendMessage(update.effective_chat.id, parse_mode="HTML", text=texto)
async def rank(self,ctx,member : Member = None): if member != None: what = ["xp","lvl","repo"] result = select("Members",what,f"id = '{member.id}'") for row in result: xp = int(row[0]) lvl = int(row[1]) repo = int(row[2]) em = Embed( colour = Colour.purple() ) em.set_author(name = member.name,icon_url = member.avatar_url) em.add_field(name='Уровень:',value=lvl) em.add_field(name='Xp:',value=xp) em.add_field(name="Осталось до следушего уровня:",value=str(lvl*(lvl * 50)- xp)+ ' xp') em.add_field(name='Количество "Спасибо":',value=repo) await ctx.send(embed = em) else: what = ["xp","lvl","repo"] result = select("Members",what,f"id = '{ctx.message.author.id}'") for row in result: xp = int(row[0]) lvl = int(row[1]) repo = int(row[2]) em = Embed( colour = Colour.purple() ) em.set_author(name = ctx.message.author.name,icon_url = ctx.message.author.avatar_url) em.add_field(name='Ваш уровень:',value=lvl) em.add_field(name='Ваш Xp:',value=xp) em.add_field(name="Вам осталось до следушего уровня:",value=str(lvl*(lvl * 50)- xp)+ ' xp') em.add_field(name='Ваше количество "Спасибо":',value=repo) await ctx.send(embed = em)
def pagar(update: Update, context: CallbackContext): gastos = db.select("gastos").sort_values(by=["pagado", "id_persona"], ignore_index=True) keyboard = [] texto = f"A soltar el dinero polssssss 💰💶💵💷💸\n" for i, gasto in gastos.iterrows(): keyboardline = [] texto += f" {i + 1}. {gasto.nombre_persona}({gasto.fecha.strftime('%d/%m')}) {gasto.cantidad}€ -> {gasto.motivo}\n" keyboardline.append(InlineKeyboardButton(i + 1, callback_data="NADA")) if gasto.pagado: keyboardline.append( InlineKeyboardButton("🧾", callback_data="NADA")) else: keyboardline.append( InlineKeyboardButton("💰", callback_data="PAGAR" + str(gasto.id))) keyboard.append(keyboardline) keyboard.append( [InlineKeyboardButton("Terminar", callback_data=str("TERMINAR"))]) reply_markup = InlineKeyboardMarkup(keyboard) update.callback_query.edit_message_text(text=texto, parse_mode="HTML", reply_markup=reply_markup) return PAGAR
def start(update: Update, context: CallbackContext): data = db.select("data") context.bot.deleteMessage(update.message.chat_id, update.message.message_id) user_id = int(update.effective_user.id) chat_id = int(update.effective_chat.id) nombre = update.effective_user.first_name fila = data.loc[data.id == user_id] if len(fila) == 1: fila = fila.iloc[0] logger.info( f"{update.effective_chat.type} -> {fila.apodo} ha iniciado el bot") else: logger.info( f"{update.effective_chat.type} -> {nombre} con id: {user_id} ha iniciado el bot sin estar en el grupo" ) context.bot.sendMessage( chat_id, "Lo siento, pero no perteneces al grupo de Manitoba") return context.user_data["oldMessage2"] = context.bot.sendMessage( update.effective_chat.id, 'Antes de empezar, necesito que me respondas un par de preguntas') context.user_data["oldMessage"] = context.bot.sendMessage( update.effective_chat.id, '¿Cuál es tu nombre?') return ELEGIR_NOMBRE
def editar_lista_manual(update: Update, context: CallbackContext): all_listas = db.select("listas") logger.warning( f"{update.effective_user.name} ha editado la lista con el mensaje\n{update.message.text} " ) poll_name = (update.message.text.split(":\n"))[1] lista = all_listas[all_listas.nombre == poll_name].squeeze() elementos = (update.message.text.split(":\n", 2))[2].split("\n") elementos2 = [ re.sub(r"^[\t]*[ ]*[0-9]*[.]*[ ]*", r"", element) for element in elementos ] lista.elementos = elementos2 lista.tipo_elementos = [0] * len(elementos2) context.bot.deleteMessage(update.effective_chat.id, update.message.message_id) try: context.bot.deleteMessage(ID_MANITOBA, int(lista.id_mensaje)) except: logger.error(f"Fallo al eliminar el mensaje {lista.id_mensaje}") texto = f"{update.effective_user.first_name} ha editado la lista:\n{lista_to_text(lista)}" new_message = context.bot.sendMessage(chat_id=ID_MANITOBA, parse_mode="HTML", text=texto) lista.id_mensaje = new_message.message_id db.update_lista(lista)
def encuestas(update: Update, context: CallbackContext) -> None: polls = db.select("encuestas") polls = polls[~polls.end].reset_index() chat_id = update.effective_chat.id user = update.effective_user logger.warning(f"{update.effective_chat.type} -> {user.first_name} entró en el comando encuestas") keyboard = [] text = f"{user.first_name} ¿Qué quieres hacer?\n" if polls.empty: keyboard.append([InlineKeyboardButton("No hay encuestas activas 😢", callback_data="NADA")]) else: for i, poll in polls.iterrows(): keyboardline = [] text += f" {i + 1}. {poll.question}\n" keyboardline.append(InlineKeyboardButton(i + 1, callback_data="NADA")) # keyboardline.append(InlineKeyboardButton("👀", callback_data="VER" + str(poll.id))) keyboardline.append(InlineKeyboardButton("🗑", callback_data="ELIMINAR" + str(poll.id))) keyboardline.append(InlineKeyboardButton("📯", callback_data="FINALIZAR" + str(poll.id))) keyboard.append(keyboardline) keyboard.append([InlineKeyboardButton("Democracia 🗳️", callback_data=str("DEMOCRACIA"))]) keyboard.append([InlineKeyboardButton("Terminar", callback_data=str("TERMINAR"))]) reply_markup = InlineKeyboardMarkup(keyboard) context.user_data["query_listas"] = context.bot.sendMessage(chat_id, text, reply_markup=reply_markup) if update.message: context.bot.deleteMessage(chat_id, update.message.message_id) return ELEGIR_ENCUESTA
def birthday(context: CallbackContext): data = db.select("data") fecha = datetime.today().strftime('%d/%m') cumpleaneros = data[data.cumple == fecha] for _, cumpleanero in cumpleaneros.iterrows(): # tts = gTTS(cumpleanero.cumple_song, lang=cumpleanero.cumple_lang) # tts.save(f"Felicitacion de su majestad para {cumpleanero.apodo}.mp3") context.bot.sendMessage( chat_id=ID_MANITOBA, parse_mode="HTML", text=f"Felicidades <b>{cumpleanero.apodo}</b>!!!!!") context.bot.sendSticker(chat_id=ID_MANITOBA, sticker=STICKERS[random.randint( 0, len(STICKERS) - 1)]) # context.bot.sendAudio(chat_id=ID_MANITOBA, # audio=open(f"Felicitacion de su majestad para {cumpleanero.apodo}.mp3", "rb")) if cumpleanero.genero == "F": context.bot.sendMessage( chat_id=ID_MANITOBA, parse_mode="HTML", text= f"Por seeeeerrrr tan bueeeennaa muchaaaaachaaaaa 🎉🎊🎈") else: context.bot.sendMessage( chat_id=ID_MANITOBA, parse_mode="HTML", text= f"Por seeeeerrrr tan bueeeenn muchaaaaachaooooo 🎉🎊🎈")
async def updeconomybd(self, ctx): """Обновляет список пользователей в БД Полезно когда бот долго был на тех. работах""" await ctx.message.delete() i = 0 i_new = 0 text = "Обновляем список пользователей\n" msg = await ctx.send(text) for member in ctx.guild.members: i += 1 name = "Members" what = ["id"] criterion = f"id = '{member.id}'" rezults = select(name, what, criterion) if str(rezults) == "[]" and member.bot == False: name = "Members" into = ["id", "xp", "lvl", "money"] values = [member.id, "0", "1", "0"] insert(name, into, values) i_new += 1 else: name = "Members" into = ["id_bot"] values = [member.id] insert(name, into, values) i_new += 1 if i % 300 == 0: await msg.edit(text + f"Проверено {i} пользователей") await sleep(0.9) await msg.edit(f"Всего проверено: {i}\nДобавлено новых: {i_new}") text = "Второй этап. Удаляю лишних пользователей из бд\n" msg = await ctx.send(text) name = "Members" what = ["id"] rezults = select(name, what) bd_users = [] for row in rezults: bd_users.append(int(row[0])) i = 0 for member in ctx.guild.members: bd_users.remove(member.id) text += f"id людей которых нет на сервере, но есть в бд:\n{bd_users}\nудаление сделаю после проверки" await msg.edit(text)
def finalizar_encuesta(update: Update, context: CallbackContext): id_encuesta = int(update.callback_query.data.replace("FINALIZAR", "")) data = db.select("data") polls = db.select("encuestas") poll = polls[polls.id == id_encuesta].squeeze() update.callback_query.delete_message() logger.warning(f"{update.effective_user.first_name} ha ejecutado el comando democracia") texto = f"La encuesta {poll.question} ha finalizado.\nEstos son los miserables que odian la democracia:\n" for _, persona in data.iterrows(): if persona.id not in poll.votes: texto += f"<a href='tg://user?id={persona.id}'>{persona.apodo}</a>\n" db.end_poll(poll.id) context.bot.stopPoll(int(poll.chat_id), int(poll.message_id)) context.bot.forwardMessage(int(poll.chat_id), int(poll.chat_id), int(poll.message_id), ) context.bot.sendMessage(ID_MANITOBA, texto, parse_mode="HTML") encuestas(update, context)
def bot_activado(update: Update, context: CallbackContext) -> None: logger.warning(f"{update.effective_user.first_name} ha ejecutado el comando bot_activado") data = db.select("data") for _, persona in data.iterrows(): try: mensaje = context.bot.sendMessage(chat_id=persona.id, parse_mode="HTML", text="prueba") context.bot.deleteMessage(mensaje.chat_id, mensaje.message_id) # print(f"{persona.apodo} con id {persona.id} tiene activado el bot") except: print(f"{persona.apodo} con id {persona.id} NO tiene activado el bot")
def muditos(context: CallbackContext): data = db.select("data") hoy = datetime.today() data.ultimo_mensaje = pd.to_datetime(data.ultimo_mensaje) for _, persona in data[data.ultimo_mensaje < (hoy - timedelta(23))].iterrows(): context.bot.sendMessage( ID_MANITOBA, parse_mode="HTML", text= f"""Te echamos de menos <a href="tg://user?id={persona.id}">{persona.apodo}</a>""" )
def tareas(update: Update, context: CallbackContext): if update.message: context.user_data["ediciones"] = [] context.bot.deleteMessage(update.effective_chat.id, update.message.message_id) else: context.bot.deleteMessage(update.effective_chat.id, update.callback_query.message.message_id) user = update.effective_user context.user_data["creador_tarea"] = user["id"] logger.warning(f"{update.effective_chat.type} -> {user.first_name} entro en el comando tareas") all_tareas = db.select("tareas") data = db.select("data") context.user_data["data"] = data context.user_data["all_tareas"] = all_tareas text = f"{update.effective_user.first_name}: ¿Qué quieres hacer?\n" keyboard = [] for i, tarea in all_tareas.iterrows(): part_keyboard = [] text += f"{i + 1}. {tarea.descripcion}\n" part_keyboard.append(InlineKeyboardButton(str(i + 1), callback_data="NADA")) part_keyboard.append(InlineKeyboardButton("👀", callback_data="VER" + str(i))) if tarea.completada: part_keyboard.append(InlineKeyboardButton("🏁", callback_data="NADA")) else: if user.id in tarea.personas or user.id == tarea.creador: part_keyboard.append(InlineKeyboardButton("‼", callback_data="COMPLETAR" + str(i))) else: part_keyboard.append(InlineKeyboardButton(" ", callback_data="NADA")) # part_keyboard.append(InlineKeyboardButton("🖋", callback_data="EDITAR" + str(i))) part_keyboard.append(InlineKeyboardButton("🗑", callback_data="ELIMINAR" + str(i))) keyboard.append(part_keyboard) keyboard.append([InlineKeyboardButton("Crear nueva tarea", callback_data="CREAR")]) keyboard.append([InlineKeyboardButton("Terminar", callback_data="TERMINAR")]) reply_markup = InlineKeyboardMarkup(keyboard) # Send message with text and appended InlineKeyboard context.bot.sendMessage(update.effective_chat.id, text, reply_markup=reply_markup) # Tell ConversationHandler that we're in state `FIRST` now context.user_data["personas_asignadas"] = [] return ELEGIR_TAREA
def get_birthday(update: Update, context: CallbackContext): chat_id = update.effective_chat.id context.bot.deleteMessage(chat_id, update.message.message_id) data = db.select("data") year = datetime.now().year data.cumple = pd.to_datetime( data.cumple, format='%d/%m').apply(lambda dt: dt.replace(year=year)) a = data[data.cumple > datetime.today()].sort_values("cumple")[0:4] texto = "" for _, persona in a.iterrows(): texto += f"{persona.nombre} {persona.apellidos} | {persona.cumple.strftime('%d/%m')}/{str(persona.cumple_ano)}\n" context.bot.sendMessage(chat_id, texto)
def eliminar_encuesta(update: Update, context: CallbackContext): id_encuesta = int(update.callback_query.data.replace("ELIMINAR", "")) polls = db.select("encuestas") poll = polls[polls.id == id_encuesta].squeeze() chat = int(poll.chat_id) id_mensaje = int(poll.message_id) db.delete("encuestas", poll.id) update.callback_query.delete_message() try: context.bot.deleteMessage(chat, id_mensaje) # print(f"{persona.apodo} con id {persona.id} tiene activado el bot") except: print(f"No se puede eliminar el mensaje") encuestas(update, context)
def receive_poll_answer(update: Update, context: CallbackContext) -> None: """Summarize a users poll vote""" polls = db.select("encuestas") poll_id = int(update.poll_answer.poll_id) poll = polls[polls.id == poll_id].squeeze() votes = poll.votes respuesta = update.poll_answer if not respuesta.option_ids: logger.warning(f"{update.effective_user.first_name} quito su voto de la encuesta {poll.question}") votes.remove(int(update.poll_answer.user.id)) db.update_poll(poll_id, votes) else: votos = [poll.options[i] for i in respuesta.option_ids] logger.warning(f"{update.effective_user.first_name} ha votado {votos} en la encuesta {poll.question}") votes.append(int(update.poll_answer.user.id)) db.update_poll(poll_id, votes)
def editar_lista(update: Update, context: CallbackContext): query = update.callback_query all_listas = db.select("listas") if query.data == "CONTINUAR_EDITAR": lista = all_listas[all_listas.id == context.user_data["id_lista"]].iloc[0] else: id_lista = int(query.data.replace("EDITAR", "")) lista = all_listas[all_listas.id == id_lista].iloc[0] context.user_data["lista"] = lista context.user_data["id_lista"] = id_lista logger.warning( f"{update.effective_chat.type} -> {update.effective_user.first_name} ha elegido editar la lista '{lista.nombre}'" ) keyboard = [] for i, (elem, tipo) in enumerate(zip(lista.elementos, lista.tipo_elementos)): line_keyboard = [ InlineKeyboardButton(str(i + 1), callback_data="NADA"), InlineKeyboardButton("📝", callback_data="EDITAR" + str(i)) ] # if tipo == 0: # line_keyboard.append(InlineKeyboardButton("⬜", callback_data="MARCAR" + str(i))) # else: # line_keyboard.append(InlineKeyboardButton("👌🏽", callback_data="NADA")) line_keyboard.append( InlineKeyboardButton("🗑", callback_data="ELIMINAR" + str(i))) keyboard.append(line_keyboard) keyboard.append([ InlineKeyboardButton("Añadir nuevo elemento", callback_data=str("AÑADIR")) ]) keyboard.append([ InlineKeyboardButton("Atras", callback_data=str("ATRAS")), InlineKeyboardButton("Terminar", callback_data=str("TERMINAR")) ]) reply_markup = InlineKeyboardMarkup(keyboard) query.delete_message() texto = f"{update.effective_user.first_name}: ¿Que quieres hacer?:\n{lista_to_text(lista)}" context.user_data["query_elementos"] = context.bot.sendMessage( update.effective_chat.id, parse_mode="HTML", text=texto, reply_markup=reply_markup) return EDITAR_LISTA2
def terminar_pagar(update: Update, context: CallbackContext): gastos = db.select("gastos") id_gasto = int(update.callback_query.data.replace("PAGAR", "")) gasto = gastos[gastos.id == id_gasto].squeeze() db.update_gasto(id_gasto) texto = f"Se te ha pagado el gasto '{gasto.motivo}' por valor de {gasto.cantidad}€ en la fecha {gasto.fecha.strftime('%d/%m/%Y')}" context.bot.sendMessage(chat_id=int(gasto.id_persona), text=texto) update.callback_query.delete_message() keyboard = [[ InlineKeyboardButton("Continuar", callback_data=str("CONTINUAR")), InlineKeyboardButton("Terminar", callback_data=str("TERMINAR")) ]] context.bot.sendMessage(update.effective_chat.id, text="Quieres pagar a alguien mas?", reply_markup=InlineKeyboardMarkup(keyboard)) return FINAL_OPTION
def set_birthday(update: Update, context: CallbackContext): chat_id = update.effective_chat.id data = db.select("data") context.bot.deleteMessage(chat_id, update.message.message_id) keyboard = [] part_keyboard = [] for i, persona in data.sort_values(by="apodo", ignore_index=True).iterrows(): part_keyboard.append( InlineKeyboardButton(persona.apodo, callback_data=str(persona.id))) if i % 3 == 2 or i == len(data) - 1: keyboard.append(part_keyboard) part_keyboard = [] reply_markup = InlineKeyboardMarkup(keyboard) context.bot.sendMessage(chat_id, "Elige", reply_markup=reply_markup) return CUMPLE1
def listas(update: Update, context: CallbackContext): all_listas = db.select("listas") context.user_data["all_listas"] = all_listas if update.message: id_mensaje = update.message.message_id context.user_data["ediciones"] = [] else: id_mensaje = update.callback_query.message.message_id chat_id = update.effective_chat.id user = update.effective_user logger.warning( f"{update.effective_chat.type} -> {user.first_name} entró en el comando listas" ) keyboard = [] text = f"{user.first_name} ¿Qué quieres hacer?\n" for i, lista in all_listas.iterrows(): keyboardline = [] text += f" {i + 1}. {lista.nombre}\n" keyboardline.append(InlineKeyboardButton(i + 1, callback_data="NADA")) keyboardline.append( InlineKeyboardButton("👀", callback_data="VER" + str(lista.id))) # keyboardline.append(InlineKeyboardButton("🖋", callback_data="EDITAR" + str(lista.id))) keyboardline.append( InlineKeyboardButton("🗑", callback_data="ELIMINAR" + str(lista.id))) keyboard.append(keyboardline) keyboard.append([ InlineKeyboardButton("Crear nueva lista", callback_data=str("CREAR")) ]) keyboard.append( [InlineKeyboardButton("Terminar", callback_data=str("TERMINAR"))]) reply_markup = InlineKeyboardMarkup(keyboard) context.user_data["query_listas"] = context.bot.sendMessage( chat_id, text, reply_markup=reply_markup) context.bot.deleteMessage(chat_id, id_mensaje) return ELEGIR_LISTA
def echo(update: Update, context: CallbackContext): data = db.select("data") user_id = int(update.effective_user.id) chat_id = int(update.effective_chat.id) if chat_id == ID_CONVERSACIONES: conversaciones = db.select("conversaciones") if user_id == ID_TELEGRAM: if update.message.text: texto = update.message.text elif update.message.poll: texto = update.message.poll.question else: texto = "Nueva conversación" mensaje = context.bot.sendMessage( chat_id=ID_MANITOBA, parse_mode="HTML", text= f"Se ha iniciado una conversacion: <a f='https://t.me/c/1462256012/{update.message.message_id}?thread={update.message.message_id}'>{texto}</a>" ) db.insert_conversacion(update.message.message_id, mensaje.message_id, texto) else: reply_id = update.message.reply_to_message.message_id conversacion = conversaciones[conversaciones.id == reply_id].iloc[0] conversacion.total_mensajes += 1 db.update_conversacion(conversacion) try: context.bot.deleteMessage(chat_id=ID_MANITOBA, message_id=int( conversacion.mensaje_id)) except: logger.error( f"Fallo al eliminar el mensaje {conversacion.mensaje_id}") mensaje = context.bot.sendMessage( chat_id=ID_MANITOBA, parse_mode="HTML", text= f"La conversacion <a href='https://t.me/c/1462256012/{conversacion.id}?thread={conversacion.id}'>{conversacion.nombre}</a> tiene un total de {conversacion.total_mensajes} mensajes" ) conversacion.mensaje_id = mensaje.message_id db.update_conversacion(conversacion) nombre = update.effective_user.first_name fila = data.loc[data.id == user_id] if len(fila) == 1: fila = fila.iloc[0] fila.total_mensajes += 1 fila.ultimo_mensaje = datetime.today().strftime('%d/%m/%Y %H:%M:S') if update.message: if update.message.text: # logger.info(f"{update.effective_chat.type} -> {fila.apodo} ha enviado {update.message.text}. Con un total de {fila.total_mensajes} mensajes") if "la lista:\n" in update.message.text: listas.editar_lista_manual(update, context) elif update.message.sticker: fila.sticker += 1 logger.info( f"{update.effective_chat.type} -> {fila.apodo} ha enviado el sticker {update.message.sticker.emoji}. Con un total de {fila.total_mensajes} mensajes" ) elif update.message.photo: logger.info( f"{update.effective_chat.type} -> {fila.apodo} ha enviado una foto. Con un total de {fila.total_mensajes} mensajes" ) elif update.message.animation: fila.gif += 1 logger.info( f"{update.effective_chat.type} -> {fila.apodo} ha enviado un gif. Con un total de {fila.total_mensajes} mensajes" ) elif update.message.document: doc = update.message.document # if "acta" in doc.file_name.lower() and doc.mime_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': # file = context.bot.get_file(doc.file_id) # file.download(doc.file_name) # path = os.path.dirname(os.path.realpath(__file__)) # docx2pdf.convert(doc.file_name) # file_name = doc.file_name.replace(".docx", ".pdf") # # client_drive.upload_file(file_name, parent_id='1V34ehU4iaHgadWCRSl9hlvZUIn62qWSM') # client_drive.upload_file(doc.file_name, parent_id='1V34ehU4iaHgadWCRSl9hlvZUIn62qWSM') # logger.info( # f"{update.effective_chat.type} -> {fila.apodo} ha enviado el documento {update.message.document.file_name} tipo " # f"{update.message.document.mime_type}. Con un total de {fila.total_mensajes} mensajes") elif update.message.new_chat_members: new_member.new_member(update, context) logger.info( f"{update.effective_chat.type} -> {update.message.new_chat_members[0]} ha entrado al grupo " ) elif update.message.left_chat_member: new_member.left_member(update, context) logger.info( f"{update.effective_chat.type} -> {update.message.left_chat_member} ha salido del grupo " ) else: logger.info( f"{update.effective_chat.type} -> update.message desconocido: {update.message}" ) db.update_data1(fila) elif update.edited_message: logger.warning( f"{update.effective_chat.type} -> {fila.apodo} ha editado el mensaje por {update.edited_message.text}. Con un total de {fila.total_mensajes} mensajes" ) else: logger.info( f"{update.effective_chat.type} ->update desconocido: {update}") else: logger.info( f"{update.effective_chat.type} -> {nombre} con id: {user_id} ha enviado {update.message.text}" )
async def on_message(self,message): if not message.author.bot: is_help = False ID_bot_mention = '<@!613269904963141643>' ID_bot_mention_without_exclamation_mark = '<@613269904963141643>' role_bot = '<@&698575036310618222>' was_already = False if ID_bot_mention or ID_bot_mention_without_exclamation_mark or role_bot in message.content: I = message.guild.get_member(506438836943978496) if ID_bot_mention in message.content: result = select("Question",["question","answer"],f"question = '{message.content.replace(ID_bot_mention,'')}'") elif ID_bot_mention_without_exclamation_mark in message.content: result = select("Question",["question","answer"],f"question = '{message.content.replace(ID_bot_mention_without_exclamation_mark,'')}'") else: result = select("Question",["question","answer"],f"question = '{message.content.replace(role_bot,'')}'") for row in result: if row[0] == message.content.replace(ID_bot_mention,'') or message.content.replace(ID_bot_mention_without_exclamation_mark,'') or message.content.replace(role_bot,''): was_already = True if message.content == ".rank" or message.content == ".card": is_help = True print(f"{message.author} : {message.content} channel {message.channel}") channel_logs = message.guild.get_channel(688373372945694725) em = Embed(description = f"{message.author} : `{message.content}` channel {message.channel}", colour = Colour.from_rgb(0, 0, 201)) await channel_logs.send(embed = em) plus_lvl = 0 if len(message.content) >= 5 and not is_help: result = select("Members",["xp","lvl"],f"id = {message.author.id}") for row in result: if len(message.content) >= 15: exp_plus = int(row[0]) + randint(10,19) update("Members",["xp"],[f"{exp_plus}"],f"id = {message.author.id}") lvl_up = exp_plus/(int(row[1]) * 50) if int(row[1]) <= lvl_up: plus_lvl = int(row[1]) + 1 await message.channel.send(f'Ура <@!{message.author.id}>, у тебя новый лвл. Теперь у тебя {plus_lvl} лвл. Ты можешь это проверить при помоши `.rank`.') update("Members",["lvl"],[f"{plus_lvl}"],f"id = {message.author.id}") else: exp_plus = int(row[0]) + randint(3,7) update("Members",["xp"],[f"{exp_plus}"],f"id = {message.author.id}") lvl_up = exp_plus/(int(row[1]) * 50) if int(row[1]) <= lvl_up: plus_lvl = int(row[1]) + 1 await message.channel.send(f'Ура <@!{message.author.id}>, у тебя новый лвл. Теперь у тебя {plus_lvl} лвл. Ты можешь это проверить при помоши `.rank`.') update("Members",["lvl"],[f"{plus_lvl}"],f"id = {message.author.id}") if plus_lvl == 5: mem5 = message.guild.get_member(message.author.id) role5 = message.guild.get_role(643949984194101273) role_del5 = message.guild.get_role(643902599661223951) await mem5.add_roles(role5) await mem5.remove_roles(role_del5) await message.channel.send(f"Вам выдана роль `{str(role5).lower()}`") if plus_lvl == 10: mem6 = message.guild.get_member(message.author.id) role6 = message.guild.get_role(643902599468285962) role_del6 = message.guild.get_role(643949984194101273) await mem6.add_roles(role6) await mem6.remove_roles(role_del6) await message.channel.send(f"Вам выдана роль `{str(role6).lower()}`") if plus_lvl == 25: mem7 = message.guild.get_member(message.author.id) role7 = message.guild.get_role(680859240583266509) role_del7 = message.guild.get_role(643902599468285962) await mem7.add_roles(role7) await mem7.remove_roles(role_del7) await message.channel.send(f"Вам выдана роль `{str(role7).lower()}`") if plus_lvl == 100: mem8 = message.guild.get_member(message.author.id) role8 = message.guild.get_role(643902598289686556) role_del8 = message.guild.get_role(680859240583266509) await mem8.add_roles(role8) await mem8.remove_roles(role_del8) await message.channel.send(f"Вам выдана роль `{str(role8).lower()}`") while True: try: member = 0 members = message.guild.members for i in range(len(members)): if members[i].status == Status.online: member += 1 elif members[i].status == Status.idle: member += 1 elif members[i].status == Status.dnd: member += 1 elif members[i].status == Status.invisible: member += 1 in_online = message.guild.get_channel(703248000839057459) await in_online.edit(name=f'Людей в сети: {member}') except: pass