def set_maxmembers(bot, update, args=None): chat_id, chat_type, user_id, text, message = support.extract_update_info(update) support.delete_message(chat_id, message.message_id, bot) if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False: return group = get_group(chat_id) if group is None: bot.sendMessage( chat_id=chat_id, text="❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.", parse_mode=telegram.ParseMode.MARKDOWN ) return if args is None or len(args) != 1 or not args[0].isdigit() or int(args[0])<0: bot.sendMessage( chat_id=chat_id, text="❌ No he reconocido el parámetro introducido. Por favor, revisa el comando e intenta de nuevo.") return if int(args[0]) is 0: set_max_members(chat_id, None) output = "👌 Número máximo de miembros en el grupo desactivado correctamente." else: set_max_members(chat_id, int(args[0])) output = "👌 Número máximo de miembros en el grupo establecido a {}".format(args[0]) bot.sendMessage( chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) return
def set_cooldown(bot, update, args=None): chat_id, chat_type, user_id, text, message = support.extract_update_info(update) support.delete_message(chat_id, message.message_id, bot) if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False: return group = get_group(chat_id) if group is None: bot.sendMessage( chat_id=chat_id, text="❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.", parse_mode=telegram.ParseMode.MARKDOWN ) return if args is None or len(args) != 1 or not args[0].isdigit() or int(args[0])<0: bot.sendMessage( chat_id=chat_id, text="❌ No he reconocido el parámetro introducido. Por favor, revisa el comando e intenta de nuevo.") return if int(args[0]) is 0: set_welcome_cooldown(chat_id, None) output = "👌 El mensaje de bienvenida no se eliminará automáticamente." else: set_welcome_cooldown(chat_id, int(args[0])) output = "👌 El mensaje de bienvenida se eliminará automáticamente en {} segundos".format(args[0]) bot.sendMessage( chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) return
def listrefloat_cmd(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if message.reply_to_message is None or message.reply_to_message.chat.id != chat_id: return if message.reply_to_message.from_user.id != bot.id: return if are_banned(user_id, chat_id) or not support.is_admin(chat_id, user_id, bot): return text = message.reply_to_message.text if REGLIST.search(text) is None: return text = message.reply_to_message.text button_list = [[ InlineKeyboardButton(text="🙋♀️ Me apunto!", callback_data='list_join'), InlineKeyboardButton(text="🙅♀️ Paso...", callback_data='list_left') ]] bot.sendMessage(chat_id=chat_id, text=text, parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(button_list), disable_web_page_preview=True) support.delete_message(chat_id, message.reply_to_message.message_id, bot)
def listopen_cmd(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if message.reply_to_message is None or message.reply_to_message.chat.id != chat_id: return if message.reply_to_message.from_user.id != bot.id: return if are_banned(user_id, chat_id) or not support.is_admin(chat_id, user_id, bot): return text = message.reply_to_message.text if REGLIST.search(text) is None: return button_list = [[ InlineKeyboardButton(text="🙋♀️ Me apunto!", callback_data='list_join'), InlineKeyboardButton(text="🙅♀️ Paso...", callback_data='list_left') ]] bot.edit_message_reply_markup( chat_id=chat_id, message_id=message.reply_to_message.message_id, reply_markup=InlineKeyboardMarkup(button_list))
def list_news(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if not support.is_admin(chat_id, user_id, bot) or are_banned( user_id, chat_id): return active_news = news_sql.get_news_subscribed(chat_id) verified_out = "" def_out = "" if active_news is None: output = "❌ No hay suscrpiciones activas en este grupo." else: for k in active_news: provider = news_sql.get_news_provider(k.news_id) if provider.active: verified_out = "🔰 @{}\n".format(provider.alias) + verified_out else: def_out = "📰 {} - `{}`\n".format(provider.alias, provider.id) + def_out output = "Listado de canales activos:\n" + verified_out + def_out bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN)
def set_welcome(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) text, data_type, content, buttons = support.get_welcome_type(message) if not support.is_admin(chat_id, user_id, bot) or are_banned( user_id, chat_id): return group = get_group(chat_id) if group is None: bot.sendMessage( chat_id=chat_id, text= "❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.", parse_mode=telegram.ParseMode.MARKDOWN) return if data_type is None: set_welc_preference(chat_id, False) bot.sendMessage( chat_id=chat_id, text="👌 Mensaje de bienvenida desactivado correctamente") return set_welc_preference(chat_id, True) set_custom_welcome(chat_id, content or text, data_type, buttons) bot.sendMessage(chat_id=chat_id, text="👌 Mensaje de bienvenida guardado correctamente")
def set_zone(bot, update, args=None): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if not support.is_admin(chat_id, user_id, bot) or are_banned( user_id, chat_id): return group = get_group(chat_id) if group is None: bot.sendMessage( chat_id=chat_id, text= "❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.", parse_mode=telegram.ParseMode.MARKDOWN) return if args is None or len(args) != 1 or len(args[0]) < 3 or len(args[0]) > 60: bot.sendMessage( chat_id=chat_id, text= ("❌ Me siento un poco perdido ahora mismo. Debes pasarme un nombre de zona horaria en inglés, por ejemplo, `America/Montevideo` o `Europe/Madrid`." ), parse_mode=telegram.ParseMode.MARKDOWN) return tz = support.get_unified_timezone(args[0]) if len(tz) == 1: commit_group(chat_id, timezone=tz[0]) bot.sendMessage( chat_id=chat_id, text="👌 Perfecto! Zona horaria cambiada de *{0}* a *{1}*.".format( group.timezone, tz[0]), parse_mode=telegram.ParseMode.MARKDOWN) now = datetime.now(timezone(tz[0])).strftime("%H:%M") bot.sendMessage( chat_id=chat_id, text="🕒 Por favor, comprueba que la hora sea correcta: {}".format( now)) elif len(tz) == 0: bot.sendMessage( chat_id=chat_id, text="❌ Uy, no he encontrado ninguna zona horaria con ese nombre") else: bot.sendMessage( chat_id=chat_id, text= "❌ Has sido demasiado genérico con el nombre de la zona horaria. Intenta concretar más." )
def clear_rules(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if not support.is_admin(chat_id, user_id, bot) or are_banned( user_id, chat_id): return rul_sql.add_rules(chat_id, "") update.effective_message.reply_text( "❌ Normas del grupo eliminadas correctamente.")
def process_gif(bot, update, job_queue): (chat_id, chat_type, user_id, text, message) = support.extract_update_info(update) nanny = get_nanny_settings(chat_id) if nanny and nanny.animation: if support.is_admin(chat_id, user_id, bot) and not nanny.admin_too: return support.delete_message(chat_id, message.message_id, bot) if nanny.warn: send_warn(bot, chat_id, user_id, job_queue, nanny.reply) else: send_alert(bot, chat_id, job_queue, nanny.reply)
def nanny_text(bot, user_id, chat_id, message, job_queue): nanny = get_nanny_settings(chat_id) if nanny and nanny.text: if support.is_admin(chat_id, user_id, bot) and not nanny.admin_too: return False support.delete_message(chat_id, message.message_id, bot) if nanny and nanny.warn: send_warn(bot, chat_id, user_id, job_queue, nanny.reply) else: send_alert(bot, chat_id, job_queue, nanny.reply) return True return False
def add_news(bot, update, args=None): chat_id, chat_type, user_id, text, message = support.extract_update_info(update) support.delete_message(chat_id, message.message_id, bot) if not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id): return if args is None or len(args)!=1: return output = "❌ No he reconocido este canal como proveedor de noticias." if news_sql.is_news_provider(args[0]) and not news_sql.is_news_subscribed(chat_id, args[0]): news_sql.set_news_subscription(chat_id, args[0]) output = "✅ ¡Suscripción realizada correctamente!" bot.sendMessage(chat_id=chat_id, text=output)
def settings(bot, update, args=None): chat_id, chat_type, user_id, text, message = support.extract_update_info(update) support.delete_message(chat_id, message.message_id, bot) if (not support.is_admin(chat_id, user_id, bot) or are_banned(user_id, chat_id)) and is_staff(user_id) is False: return group = get_group(chat_id) if group is None: bot.sendMessage( chat_id=chat_id, text="❌ No puedo reconocer este grupo. Si estaba funcionando hasta ahora, pregunta en @profesordumbledoreayuda.", parse_mode=telegram.ParseMode.MARKDOWN ) return message = bot.sendMessage(chat_id=chat_id, text="Oído cocina!...") support.update_settings_message(chat_id, bot, message.message_id, keyboard="main")
def set_rules(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if not support.is_admin(chat_id, user_id, bot) or are_banned( user_id, chat_id): return args = text.split(None, 1) if len(args) == 2: txt = args[1] offset = len(txt) - len(text) markdown_rules = support.markdown_parser( txt, entities=message.parse_entities(), offset=offset) rul_sql.add_rules(chat_id, markdown_rules) update.effective_message.reply_text( "✅ Normas del grupo establecidas correctamente.".format(chat_id))
def set_nanny(bot, update, args=None): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) chat = update.effective_chat user = update.effective_user msg = update.effective_message if not support.is_admin(chat_id, user_id, bot): return args = msg.text.split(None, 1) if len(args) >= 2: offset = len(args[1]) - len(msg.text) text, buttons = support.button_markdown_parser( args[1], entities=msg.parse_entities(), offset=offset) set_nanny_reply(chat_id, text) msg.reply_text("Mensaje del modo biblioteca guardado correctamente") else: set_nanny_reply(chat_id, None) msg.reply_text("Mensaje del modo biblioteca por defecto activado")
def process_cmd(bot, update, job_queue): (chat_id, chat_type, user_id, text, message) = support.extract_update_info(update) try: args = re.sub(r"^/[a-zA-Z0-9_]+", "", text).strip().split(" ") if len(args) == 1 and args[0] == "": args = [] except Exception: args = None m = re.match("/([a-zA-Z0-9_]+)", text) if m is not None: command = m.group(1).lower() if command == "init_news": init_news(bot, update, args) return elif command == "stop_news": stop_news(bot, update, job_queue) return nanny = get_nanny_settings(chat_id) if nanny and nanny.command: if support.is_admin(chat_id, user_id, bot) and not nanny.admin_too: return support.delete_message(chat_id, message.message_id, bot) if nanny and nanny.warn: send_warn(bot, chat_id, user_id, job_queue, nanny.reply) else: send_alert(bot, chat_id, job_queue, nanny.reply)
def listclose_cmd(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if message.reply_to_message is None or message.reply_to_message.chat.id != chat_id: return if message.reply_to_message.from_user.id != bot.id: return if are_banned(user_id, chat_id) or not support.is_admin(chat_id, user_id, bot): return text = message.reply_to_message.text if REGLIST.search(text) is None: return bot.edit_message_reply_markup( chat_id=chat_id, message_id=message.reply_to_message.message_id, reply_markup=None)
def fort_btn(bot, update, job_queue): query = update.callback_query data = query.data user = update.effective_user username = query.from_user.username user_id = query.from_user.id text = query.message.text chat_id = query.message.chat.id message_id = query.message.message_id message = query.message markdown_text = query.message.text_markdown_urled if are_banned(user_id, chat_id): return user = get_user(user_id) if user is None: bot.answer_callback_query( query.id, "❌ Debes registrarte para usar esta función.", show_alert=True) return queryData = data.split("_") if len(queryData) == 5: if queryData[3] == str(user_id) or support.is_admin( chat_id, user_id, bot): if queryData[1] == "addubi": group = get_group(chat_id) group_tz = group.timezone tz = pytz.timezone(group_tz) try: userTime = datetime.strptime(queryData[4], '%d/%H:%M') userDatetime = datetime.now().replace( day=userTime.day, hour=userTime.hour, minute=userTime.minute, second=0) dateText = f"el *{userDatetime.day}/{userDatetime.month}* a las *{userDatetime.hour:02}:{userDatetime.minute:02}*" except: userTime = datetime.strptime(queryData[4], '%H:%M') userDatetime = datetime.now().replace( hour=userTime.hour, minute=userTime.minute, second=0) dateText = f"a las *{userDatetime.hour:02}:{userDatetime.minute:02}*" userAsLocal = tz.localize(userDatetime) userAsLocal = userAsLocal.astimezone(pytz.utc) if datetime.now(pytz.utc) > userAsLocal: userAsLocal = userAsLocal + timedelta(days=1) userDatetime = userDatetime + timedelta(days=1) dateText = f"el *{userDatetime.day}/{userDatetime.month}* a las *{userDatetime.hour:02}:{userDatetime.minute:02}*" userAsLocal30 = userAsLocal - timedelta(minutes=30) #userAsLocal30 = userAsLocal30.time() #userAsLocalTime = userAsLocal.time() userAsLocal = userAsLocal.replace(tzinfo=None) poi = get_poi(queryData[2]) lat = poi.latitude lon = poi.longitude button_list = [[ (InlineKeyboardButton("🙋♀️ Voy", callback_data=f'fort_yes_{poi.id}')), (InlineKeyboardButton( "🕒 Tardo", callback_data=f'fort_late_{poi.id}')), (InlineKeyboardButton("❌ No voy", callback_data=f'fort_no_{poi.id}')) ], [(InlineKeyboardButton( "✅ Estoy", callback_data=f'fort_here_{poi.id}')), (InlineKeyboardButton( "📍 Ubicación", callback_data=f'fort_ubi_{poi.id}')), (InlineKeyboardButton( "⚠️ Aviso", callback_data=f'fort_alert_{poi.id}'))]] text = "Fortaleza en [{0}](https://maps.google.com/maps?q={1},{2}) {3}\n\nLista:".format( poi.name, lat, lon, dateText) fort_msg = bot.sendMessage( chat_id=chat_id, text=text, parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup(button_list)) chat_url = support.message_url(message, fort_msg.message_id, "desafío") f_object = support.AlertFortressContext( chat_id, f"¡Mago de *{message.chat.title}*, en 30 minutos tendrá lugar un {chat_url} que pondrá a prueba tus habilidades como mago en [{poi.name}](https://maps.google.com/maps?q={lat},{lon})!", fort_msg.message_id, poi.id) job_queue.run_once(support.callback_AlertFortress, userAsLocal, context=f_object) support.save_jobs(job_queue) bot.delete_message(chat_id=chat_id, message_id=message_id) return else: bot.answer_callback_query( callback_query_id=query.id, text= "Sólo un administrador o el usuario que ha creado el aviso puede pulsar ese botón.", show_alert=True) return if queryData[1] == "cancel": if queryData[2] == str(user_id) or support.is_admin( chat_id, user_id, bot): bot.delete_message(chat_id=chat_id, message_id=message_id) return else: bot.answer_callback_query( callback_query_id=query.id, text= "Sólo un administrador o el usuario que ha creado el aviso puede pulsar ese botón.", show_alert=True) return poi_id = queryData[2] poi = get_poi(poi_id) lat = poi.latitude lon = poi.longitude button_list = [ [(InlineKeyboardButton("🙋♀️ Voy", callback_data=f'fort_yes_{poi.id}')), (InlineKeyboardButton("🕒 Tardo", callback_data=f'fort_late_{poi.id}')), (InlineKeyboardButton("❌ No voy", callback_data=f'fort_no_{poi.id}'))], [(InlineKeyboardButton("✅ Estoy", callback_data=f'fort_here_{poi.id}')), (InlineKeyboardButton("📍 Ubicación", callback_data=f'fort_ubi_{poi.id}')), (InlineKeyboardButton("⚠️ Aviso", callback_data=f'fort_alert_{poi.id}'))] ] string = r'\n(🙋♀️|✅|🕒|❌) 🧙(\d|\d\d|\?\?) (🍮|⚔|🐾|📚)(\d|\d\d|\?\?) @{}'.format( username) if queryData[1] == "ubi": bot.send_venue( chat_id=user_id, title=poi.name, address=" ", latitude=lat, longitude=lon, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="📍 Google Maps", url='https://maps.google.com/maps?q={0},{1}'.format( lat, lon)) ]])) return elif queryData[1] == "alert": if last_run( str(user_id) + str(chat_id) + str(message_id), 'fort_alert'): bot.answer_callback_query( callback_query_id=query.id, text= "Ya has enviado un ⚠️ Aviso, espera un rato para enviar otro.", show_alert=True) return if re.search(string, markdown_text): ent = message.parse_entities(["mention"]) chat_url = support.message_url(message, message_id, "fortaleza") for mention in ent: username = message.parse_entity(mention) string = r'\n(🙋♀️|✅|🕒|❌) 🧙(\d|\d\d|\?\?) (🍮|⚔|🐾|📚)(\d|\d\d|\?\?) {}'.format( username) search = re.search(string, markdown_text) if search.group(1) == "❌": continue user = get_user_by_name(username[1:]) btn_user = get_user(user_id) bot.sendMessage( chat_id=user.id, text= f"Alerta para la {chat_url} en [{poi.name}](https://maps.google.com/maps?q={lat},{lon}) enviada por @{btn_user.alias}", parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True) bot.answer_callback_query( callback_query_id=query.id, text= "⚠️ Aviso enviado a todos los magos apuntados en la lista.", show_alert=True) else: bot.answer_callback_query( query.id, "❌ Debes apuntarte para poder enviar una alerta.", show_alert=True) return markdown_text = re.sub(string, "", markdown_text) if user is None or user.profession is Professions.NONE.value: text_prof = "🍮" elif user.profession is Professions.AUROR.value: text_prof = "⚔" elif user.profession is Professions.MAGIZOOLOGIST.value: text_prof = "🐾" elif user.profession is Professions.PROFESSOR.value: text_prof = "📚" text_level = ("{}".format(user.level) if user and user.level else "??") text_profession_level = ("{}".format(user.profession_level) if user and user.profession_level else "??") if queryData[1] == "yes": text = markdown_text + f"\n🙋♀️ 🧙{text_level} {text_prof}{text_profession_level} @{username}" elif queryData[1] == "here": text = markdown_text + f"\n✅ 🧙{text_level} {text_prof}{text_profession_level} @{username}" elif queryData[1] == "late": text = markdown_text + f"\n🕒 🧙{text_level} {text_prof}{text_profession_level} @{username}" elif queryData[1] == "no": text = markdown_text + f"\n❌ 🧙{text_level} {text_prof}{text_profession_level} @{username}" bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(button_list), disable_web_page_preview=True)
def settingsbutton(bot, update): logging.debug("%s %s", bot, update) query = update.callback_query data = query.data user = update.effective_user user_id = query.from_user.id user_username = query.from_user.username chat_id = query.message.chat.id message_id = query.message.message_id are_banned(user_id, chat_id) settings_goto = { "settings_goto_general": "general", "settings_goto_join": "join", "settings_goto_news": "news", "settings_goto_welcome": "welcome", "settings_goto_nanny": "nanny", "settings_goto_ladmin": "ladmin", "settings_goto_main": "main" } settings_general = { "settings_general_games": "games", "settings_general_hard": "hard", "settings_general_reply": "reply", "settings_general_warn": "warn" } settings_join = { "settings_join_mute": "silence", "settings_join_silence": "mute", "settings_join_val": "val" } settings_welcome = {"settings_welcome_welcome": "should_welcome"} settings_nanny = { "settings_nanny_command": "cmd", "settings_nanny_animation": "animation", "settings_nanny_contact": "contact", "settings_nanny_photo": "photo", "settings_nanny_games": "games", "settings_nanny_text": "text", "settings_nanny_sticker": "sticker", "settings_nanny_location": "location", "settings_nanny_url": "url", "settings_nanny_video": "video", "settings_nanny_warn": "warn", "settings_nanny_admin_too": "admin_too", "settings_nanny_voice": "voice" } settings_ladmin = { "settings_ladmin_welcome": "welcome", "settings_ladmin_admin": "admin", "settings_ladmin_ejections": "ejections" } settings_admin = { "settings_admin_welcome": "welcome", "settings_admin_goodbye": "goodbye", "settings_admin_admin": "admin", "settings_admin_ejections": "ejections" } if re.match("^settings_.+$", data) is not None: match = re.match(r"settings_news_([-0-9]*)", query.data) if not support.is_admin(chat_id, user_id, bot): bot.answerCallbackQuery( text= "Solo los administradores del grupo pueden configurar el bot.", callback_query_id=update.callback_query.id, show_alert="true") return if data in settings_goto: support.update_settings_message(chat_id, bot, message_id, keyboard=settings_goto[data]) elif data == "settings_done": support.delete_message(chat_id, message_id, bot) elif data in settings_general: set_general_settings(chat_id, settings_general[data]) support.update_settings_message(chat_id, bot, message_id, keyboard="general") elif data in settings_join: set_join_settings(chat_id, settings_join[data]) support.update_settings_message(chat_id, bot, message_id, keyboard="join") elif data in settings_welcome: set_welcome_settings(chat_id, settings_welcome[data]) support.update_settings_message(chat_id, bot, message_id, keyboard="welcome") elif data in settings_nanny: set_nanny_settings(chat_id, settings_nanny[data]) support.update_settings_message(chat_id, bot, message_id, keyboard="nanny") elif data in settings_admin: set_admin_settings(chat_id, settings_admin[data]) support.update_settings_message(chat_id, bot, message_id, keyboard="admin") elif data in settings_ladmin: set_ladmin_settings(chat_id, settings_ladmin[data]) support.update_settings_message(chat_id, bot, message_id, keyboard="ladmin") elif data == "settings_admin_spy": set_ladmin_settings(chat_id, "admin_bot") support.delete_message(chat_id, message_id, bot) output = "Antes de nada administradores quiero daros las gracias. Debeis haber demostrado verdadera lealtad hacia mi en el grupo, y solo eso ha podido lograr que acuda Fawkes a vuestro grupo.\nÉl no puede leer nada de lo que suceda en el grupo, simplemente enviará las alertas que hayais configurado. Si necesitais configurar de nuevo las alertas o quereis usar los comandos, invitadme de nuevo al grupo y cuando acabeis volved a activar a Fawkes." bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) bot.leaveChat(chat_id=chat_id) elif match: news_id = match.group(1) if is_news_subscribed(chat_id, news_id): rm_news_subscription(chat_id, news_id) else: set_news_subscription(chat_id, news_id) support.update_settings_message(chat_id, bot, message_id, keyboard="news") return match = re.match(r"rm_warn\((.+?)\)", query.data) if match: if not support.is_admin(chat_id, user_id, bot): bot.answerCallbackQuery( text="Solo los administradores del grupo pueden retirar warns.", callback_query_id=update.callback_query.id, show_alert="true") return user_id = match.group(1) res = remove_warn(user_id, chat_id) if res: text = "Aviso eliminado por @{}.".format(user_username) bot.answerCallbackQuery(text="Has eliminado un warn.", callback_query_id=update.callback_query.id, show_alert="true") else: bot.answerCallbackQuery( text= "En estos momentos no puedo eliminar el warn, prueba mas tarde.", callback_query_id=update.callback_query.id, show_alert="true") return bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True) return match = re.match(r"rm_ban\((.+?)\)", query.data) if match: if not support.is_admin(chat_id, user_id, bot): bot.answerCallbackQuery( text="Solo los administradores del grupo pueden retirar bans.", callback_query_id=update.callback_query.id, show_alert="true") return us_id = match.group(1) bot.unbanChatMember(chat_id, us_id) bot.answerCallbackQuery(text="Has eliminado un ban.", callback_query_id=update.callback_query.id, show_alert="true") text = "Ban retirado por @{}.".format(user_username) bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True) return match = re.match(r"rm_mute\((.+?)\)", query.data) if match: if not support.is_admin(chat_id, user_id, bot): bot.answerCallbackQuery( text= "Solo los administradores del grupo pueden desmutear usuarios.", callback_query_id=update.callback_query.id, show_alert="true") return us_id = match.group(1) bot.restrict_chat_member(chat_id, us_id, can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True) bot.answerCallbackQuery(text="El usuario ha sido desmuteado.", callback_query_id=update.callback_query.id, show_alert="true") text = "Usuario desmuteado por @{}.".format(user_username) bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True) return else: logging.error('settingsbutton:%s is not a expected settings command', data)
def rem_plant_cmd(bot, update, job_queue, args=None): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) support.delete_message(chat_id, message.message_id, bot) if are_banned(chat_id, user_id) or not support.is_admin(chat_id, user_id, bot): return user = get_real_user(user_id) if user is None: bot.sendMessage(chat_id=chat_id, text="❌ Debes registrarte para usar este comando.", parse_mode=telegram.ParseMode.MARKDOWN) return if args is not None and len(args) != 0: if re.match(r"^[0-9]{0,10}$", args[0]): try: alert15PlantJob = job_queue.get_jobs_by_name( "{}_plantJob15".format(args[0])) alert15PlantJob[0].schedule_removal() except: pass try: alertPlantJob = job_queue.get_jobs_by_name( "{}_plantJob".format(args[0])) alertPlantJob[0].schedule_removal() except: pass try: deletePlantJob = job_queue.get_jobs_by_name( "{}_plantJobDelete".format(args[0])) deletePlantJob[0].schedule_removal() except: pass support.save_jobs(job_queue) if delete_plant(plant_id=args[0], group_id=chat_id): text = "Plantación eliminada correctamente." else: text = "❌ No se pudo eliminar la plantación." bot.sendMessage(chat_id=chat_id, text=text, parse_mode=telegram.ParseMode.MARKDOWN) elif args[0] == "all": plants = delete_plant(group_id=chat_id, group=True) for plant in plants: try: alert15PlantJob = job_queue.get_jobs_by_name( "{}_plantJob15".format(plant.id)) alert15PlantJob[0].schedule_removal() except: continue try: alertPlantJob = job_queue.get_jobs_by_name( "{}_plantJob".format(plant.id)) alertPlantJob[0].schedule_removal() except: continue try: deletePlantJob = job_queue.get_jobs_by_name( "{}_plantJobDelete".format(plant.id)) deletePlantJob[0].schedule_removal() except: continue support.save_jobs(job_queue) bot.sendMessage( chat_id=chat_id, text="Todas las plantaciones eliminadas correctamente.", parse_mode=telegram.ParseMode.MARKDOWN)
def test_welcome(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) chat = update.effective_chat first_name = update.message.from_user.first_name last_name = update.message.from_user.last_name username = update.message.from_user.username support.delete_message(chat_id, message.message_id, bot) if not support.is_admin(chat_id, user_id, bot) or are_banned( user_id, chat_id): return ENUM_FUNC_MAP = { Types.TEXT.value: bot.sendMessage, Types.BUTTON_TEXT.value: bot.sendMessage, Types.STICKER.value: bot.sendSticker, Types.DOCUMENT.value: bot.sendDocument, Types.PHOTO.value: bot.sendPhoto, Types.AUDIO.value: bot.sendAudio, Types.VOICE.value: bot.sendVoice, Types.VIDEO.value: bot.sendVideo } should_welc, cust_welcome, welc_type = welcome_sql.get_welc_pref(chat.id) sent = None if welc_type != Types.TEXT and welc_type != Types.BUTTON_TEXT: msg = ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome) return msg first_name = first_name or "" if cust_welcome: if last_name: fullname = "{} {}".format(first_name, last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_markdown(user_id, first_name) if username: username = "******" + escape_markdown(username) else: username = mention valid_format = support.escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format(nombre=escape_markdown(first_name), apellido=escape_markdown(last_name or first_name), hpwu=support.replace(user_id, first_name), nombrecompleto=escape_markdown(fullname), usuario=username, mention=mention, count=count, title=escape_markdown(chat.title), id=user_id) buttons = welcome_sql.get_welc_buttons(chat.id) keyb = support.build_keyboard(buttons) if has_rules(chat.id): config = get_config() url = "t.me/{}?start={}".format(config["telegram"]["bot_alias"], chat.id) keyb.append([InlineKeyboardButton("Normas", url=url)]) else: return keyboard = InlineKeyboardMarkup(keyb) send(bot, chat_id, res, keyboard)
def gh_btn(bot, update, job_queue): query = update.callback_query data = query.data user = update.effective_user user_id = query.from_user.id text = query.message.text chat_id = query.message.chat.id message_id = query.message.message_id name = query.message.venue.title lat = query.message.location.latitude lon = query.message.location.longitude coords = str(lat) + ", " + str(lon) if are_banned(user_id, chat_id): return queryData = data.split("_") userBtn = queryData[4] if userBtn == str(user_id) or support.is_admin(chat_id, user_id, bot): if queryData[1] == "addplant": bot.delete_message(chat_id=chat_id, message_id=message_id) poi_list = get_poi_list(chat_id, PortalType.GREENHOUSE.value) poi_sorted = sort_list(poi_list, coords) button_list = [] if len(poi_sorted) >= 1: button_list.append([ InlineKeyboardButton( poi_sorted[0].name, callback_data='gh_addubi_{0}_{1}_{2}_{3}'.format( poi_sorted[0].id, queryData[2], user_id, queryData[3])) ]) if len(poi_sorted) >= 2: button_list.append([ InlineKeyboardButton( poi_sorted[1].name, callback_data='gh_addubi_{0}_{1}_{2}_{3}'.format( poi_sorted[1].id, queryData[2], user_id, queryData[3])) ]) if len(poi_sorted) >= 3: button_list.append([ InlineKeyboardButton( poi_sorted[2].name, callback_data='gh_addubi_{0}_{1}_{2}_{3}'.format( poi_sorted[2].id, queryData[2], user_id, queryData[3])) ]) if len(poi_sorted) >= 4: button_list.append([ InlineKeyboardButton( poi_sorted[3].name, callback_data='gh_addubi_{0}_{1}_{2}_{3}'.format( poi_sorted[3].id, queryData[2], user_id, queryData[3])) ]) if len(poi_sorted) >= 5: button_list.append([ InlineKeyboardButton( poi_sorted[4].name, callback_data='gh_addubi_{0}_{1}_{2}_{3}'.format( poi_sorted[4].id, queryData[2], user_id, queryData[3])) ]) button_list.append([ InlineKeyboardButton( "❌ Cancelar", callback_data='gh_cancel_._._{}'.format(user_id)) ]) plant = support.replace_plants(int(queryData[2])) bot.send_venue(chat_id=chat_id, title=plant + " " + queryData[3], address="¿En qué invernadero está plantado?", latitude=lat, longitude=lon, reply_markup=InlineKeyboardMarkup(button_list)) return elif queryData[1] == "addubi": userTime = datetime.strptime(queryData[5], '%H:%M') group = get_group(chat_id) group_tz = group.timezone tz = pytz.timezone(group_tz) userDatetime = datetime.now().replace(hour=userTime.hour, minute=userTime.minute, second=0) userAsLocal = tz.localize(userDatetime) userAsLocal = userAsLocal.astimezone(pytz.utc) ''' if datetime.now(pytz.utc) > userAsLocal: userAsLocal = userAsLocal + timedelta(days=1) ''' userAsLocal15 = userAsLocal - timedelta(minutes=15) userAsLocalDeletePlant = userAsLocal + timedelta(minutes=30) userAsLocal15 = userAsLocal15.time() userAsLocalTime = userAsLocal.time() userAsLocalDPTime = userAsLocalDeletePlant.time() plant = support.replace_plants(int(queryData[3])) setPlant = set_plant(queryData[2], queryData[3], chat_id, userDatetime, userAsLocalDeletePlant) thePlant = get_plant(setPlant) poi = get_poi(queryData[2]) ap_object = support.AlertPlantContext( chat_id, "¡Magos de *{0}*, en 15 minutos se podrá recoger *{1}* en [{2}](https://maps.google.com/maps?q={3},{4})!" .format(query.message.chat.title, plant, poi.name, poi.latitude, poi.longitude), False, thePlant.id) job_queue.run_once(support.callback_AlertPlant, userAsLocal15, context=ap_object, name="{}_plantJob15".format(thePlant.id)) ap_object = support.AlertPlantContext( chat_id, "¡Magos de *{0}*, ya se puede recoger *{1}* en [{2}](https://maps.google.com/maps?q={3},{4})!" .format(query.message.chat.title, plant, poi.name, poi.latitude, poi.longitude), True, thePlant.id) job_queue.run_once(support.callback_AlertPlant, userAsLocalTime, context=ap_object, name="{}_plantJob".format(thePlant.id)) dp_object = support.DeletePlantContext(thePlant.id) job_queue.run_once(support.callback_DeletePlant, userAsLocalDPTime, context=dp_object, name="{}_plantJobDelete".format(thePlant.id)) bot.delete_message(chat_id=chat_id, message_id=message_id) success_message = bot.sendMessage( chat_id=chat_id, text="🌱 Plantación añadida correctamente.", parse_mode=telegram.ParseMode.MARKDOWN) delete_object = support.DeleteContext(chat_id, success_message.message_id) job_queue.run_once(support.callback_delete, 10, context=delete_object) support.save_jobs(job_queue) return elif queryData[1] == "cancel": bot.delete_message(chat_id=chat_id, message_id=message_id) return else: bot.answer_callback_query( callback_query_id=query.id, text= "Sólo un administrador o el usuario que ha creado el aviso puede pulsar ese botón.", show_alert=True)