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 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 btn_parser(bot, update): query = update.callback_query data = query.data user = update.effective_user username = query.from_user.username user_id = query.from_user.id texto = query.message.text chat_id = query.message.chat.id message_id = query.message.message_id message = query.message if are_banned(user_id, chat_id): return user = get_user(user_id) if user is None: return game = data[2:].split("_")[0] game_data = data[2:].split("_")[1:] game_data = "_".join(game_data) if game == "gra": grageas.grag_btn(bot, update, game_data) if game == "whosaid": whosaid.whosaid_btn(bot, update, game_data) if game == "rps": rps.rps_btn(bot, update, game_data)
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_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 list_btn(bot, update): 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 if are_banned(user_id, chat_id): return user = get_user(user_id) if user is None: return if user.profession is Professions.PROFESSOR.value: text_prof = "📚" elif user.profession is Professions.MAGIZOOLOGIST.value: text_prof = "🐾" elif user.profession is Professions.AUROR.value: text_prof = "⚔️" elif user.profession is Professions.NONE.value: text_prof = "🍮" if user.house is Houses.GRYFFINDOR.value: text_team = "🦁" elif user.house is Houses.HUFFLEPUFF.value: text_team = "🦡" elif user.house is Houses.RAVENCLAW.value: text_team = "🦅" elif user.house is Houses.SLYTHERIN.value: text_team = "🐍" elif user.house is Houses.NONE.value: text_team = "🙈" string = r'\n(.|🦁|🦡|🦅|🐍|🙈) - (\d\d|\d) - (.|📚|🐾|⚔️|🍮) - @{}'.format( username) text = re.sub(string, "", text) if data == "list_join": text = text + "\n{0} - {1} - {2} - @{3}".format( text_team, user.level, text_prof, username) button_list = [[ InlineKeyboardButton(text="🙋♀️ Me apunto!", callback_data='list_join'), InlineKeyboardButton(text="🙅♀️ Paso...", callback_data='list_left') ]] bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, reply_markup=InlineKeyboardMarkup(button_list), disable_web_page_preview=True)
def sighting_cmd(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) username = message.from_user.username support.delete_message(chat_id, message.message_id, bot) if are_banned(user_id, chat_id): 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 message.reply_to_message is not None: if message.reply_to_message.location is not None: support.delete_message(chat_id, message.reply_to_message.message_id, bot) lat = message.reply_to_message.location.latitude lon = message.reply_to_message.location.longitude group = get_group(chat_id) group_tz = group.timezone tz = pytz.timezone(group_tz) localTime = datetime.now().replace(tzinfo=pytz.utc) groupDateTime = localTime.astimezone(tz) groupTime = groupDateTime.time() button_list = [ [ InlineKeyboardButton( text="📍 Ubicación", callback_data='sighting_ubi_{0}_{1}'.format(lat, lon)) ], [ InlineKeyboardButton( text="🙋♀️ ¡Está!", callback_data='sighting_yes_{0}_{1}'.format(lat, lon)), InlineKeyboardButton( text="🙅♀️ No está...", callback_data='sighting_no_{0}_{1}'.format(lat, lon)) ] ] output = text.split(None, 1) out = "🐾 " + escape_markdown( output[1] ) + f"\n\n👤 Avistado por @{username} a las {groupTime.hour:02}:{groupTime.minute:02}\nℹ️ Información:" bot.sendMessage(chat_id=chat_id, text=out, reply_markup=InlineKeyboardMarkup(button_list))
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 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 plants_list_cmd(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 are_banned(chat_id, user_id): 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 text = "Lista de plantaciones en *{}*:\n".format(message.chat.title) plants_list = get_plant_list(chat_id) if not list(plants_list): bot.sendMessage(chat_id=user_id, text="❌ No hay plantaciones registradas.", parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True) return count = 0 for plant in plants_list: plantName = support.replace_plants(plant.plant_type) poi = get_poi(plant.portal) if plant.alerted: text = text + "\n- #{0} *{1}* - ⚠️ {2} ⚠️ - [{3}](https://maps.google.com/maps?q={4},{5})".format( plant.id, plantName, f"{plant.grow_end.hour:02}:{plant.grow_end.minute:02}", poi.name, poi.latitude, poi.longitude) else: text = text + "\n- #{0} *{1}* - {2} - [{3}](https://maps.google.com/maps?q={4},{5})".format( plant.id, plantName, f"{plant.grow_end.hour:02}:{plant.grow_end.minute:02}", poi.name, poi.latitude, poi.longitude) count += 1 if count == 100: pass bot.sendMessage(chat_id=user_id, text=text, parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True)
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 duel_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) user_username = message.from_user.username if are_banned(user_id, chat_id): return user = get_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 try: if user_username is None: bot.sendMessage( chat_id=chat_id, text="❌ Es necesario que configures un alias en Telegram antes de continuar usando el bot.", parse_mode=telegram.ParseMode.MARKDOWN ) return except: bot.sendMessage( chat_id=chat_id, text="❌ Es necesario que configures un alias en Telegram antes de continuar usando el bot.", parse_mode=telegram.ParseMode.MARKDOWN ) return text = f"@{message.from_user.username} Vs ???\n\n¿Quién aceptará el duelo?" markup = [[InlineKeyboardButton(text="Aceptar el duelo", callback_data=f"g*duel_accept_{user_id}")]] bot.sendMessage( chat_id=chat_id, text=text, disable_notification=True, reply_markup=InlineKeyboardMarkup(markup))
def games_cmd(bot, update): (chat_id, chat_type, user_id, text, message) = support.extract_update_info(update) if are_banned(user_id, chat_id): return group_message_counter(chat_id) cfg = config.get_config() if chat_id != int(cfg["telegram"]["spain_id"]): return user = get_user(user_id) if user is None: return if last_run(chat_id, 'games'): return if (group_message_counter(chat_id, read_only=True) is randrange(40, 70)) or (group_message_counter(chat_id, read_only=True) >= 70): group_message_counter(chat_id, reset=True) game_list = [grag_cmd, whosaid_cmd] choice(game_list)(bot, update)
def list_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 are_banned(user_id, chat_id): return button_list = [[ InlineKeyboardButton(text="🙋♀️ Me apunto!", callback_data='list_join'), InlineKeyboardButton(text="🙅♀️ Paso...", callback_data='list_left') ]] output = text.split(None, 1) out = escape_markdown(output[1]) + "\n\nApuntados:" bot.sendMessage(chat_id=chat_id, text=out, parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(button_list), disable_web_page_preview=True)
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 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 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 add_ingredients_cmd(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 are_banned(chat_id, user_id): 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 message.reply_to_message is not None: if message.reply_to_message.location is not None: support.delete_message(chat_id, message.reply_to_message.message_id, bot) lat = message.reply_to_message.location.latitude lon = message.reply_to_message.location.longitude reg = re.match( r"(([0-1]?[0-9])|([0-9])|([2][0-3])):([0-5][0-9])", args[0]).group() if reg: button_list = [ [ InlineKeyboardButton( "Ajenjo", callback_data='gh_addplant_1_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Campanilla de invierno", callback_data='gh_addplant_2_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Grano de sopóforo", callback_data='gh_addplant_3_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Raíz de jengibre", callback_data='gh_addplant_4_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Coclearia", callback_data='gh_addplant_5_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Raíz de valeriana", callback_data='gh_addplant_6_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Raíz amarga", callback_data='gh_addplant_7_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Ligústico", callback_data='gh_addplant_8_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Tármica", callback_data='gh_addplant_9_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Hongo saltarín", callback_data='gh_addplant_10_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Cristoforiana", callback_data='gh_addplant_11_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "Trompeta de ángel", callback_data='gh_addplant_12_{0}_{1}'.format( reg, user_id)) ], [ InlineKeyboardButton( "❌ Cancelar", callback_data='gh_cancel_._._{}'.format( user_id)) ] ] bot.send_venue( chat_id=chat_id, title=reg, address="¿Qué planta hay en el invernadero?", latitude=lat, longitude=lon, reply_markup=InlineKeyboardMarkup(button_list))
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 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 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)
def joined_chat(bot, update, job_queue): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) new_chat_member = message.new_chat_members[ 0] if message.new_chat_members else None config = get_config() bot_alias = config['telegram']['bot_alias'] if new_chat_member.username == bot_alias: if are_banned(user_id, chat_id): bot.leaveChat(chat_id=chat_id) return chat_title = message.chat.title chat_id = message.chat.id group = group_sql.get_real_group(chat_id) if group is None: group_sql.set_group(chat_id, message.chat.title) message_text = ("Si necesitais ayuda podéis lanzar chispas rojas c" "on vuestra varita o utilizando el comando `/help`" " para conocer todas las funciones. Aseguraos de v" "er la ayuda para prefectos de los grupos, donde s" "e explica en detalle todos los pasos que se deben" " seguir.".format(escape_markdown(chat_title))) admin = get_admin(chat_id) if admin is not None and admin.admin_bot is True: set_admin_settings(chat_id, "admin_bot") message_text = message_text + "\n\n*Fawkes emprendió el vuelo.*" bot.sendMessage(chat_id=chat_id, text=message_text, parse_mode=telegram.ParseMode.MARKDOWN) elif new_chat_member.username != bot_alias: chat_id = message.chat.id user_id = update.effective_message.new_chat_members[0].id group = get_join_settings(chat_id) if group is not None: if group.delete_header: support.delete_message(chat_id, message.message_id, bot) if are_banned(user_id, user_id): bot.kickChatMember(chat_id, user_id) return user = get_user(user_id) if user is None and group.requirment is not ValidationRequiered.NO_VALIDATION.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago sin registrarse expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") return elif group.requirment is ValidationRequiered.VALIDATION.value and user.level is None: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return elif group.requirment is ValidationRequiered.PROFESSOR.value and user.profession is not Professions.PROFESSOR.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return elif group.requirment is ValidationRequiered.MAGIZOOLOGIST.value and user.profession is not Professions.MAGIZOOLOGIST.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return elif group.requirment is ValidationRequiered.AUROR.value and user.profession is not Professions.AUROR.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return elif group.requirment is ValidationRequiered.GRYFFINDOR.value and user.house is not Houses.GRYFFINDOR.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return elif group.requirment is ValidationRequiered.HUFFLEPUFF.value and user.house is not Houses.HUFFLEPUFF.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return elif group.requirment is ValidationRequiered.RAVENCLAW.value and user.house is not Houses.RAVENCLAW.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return elif group.requirment is ValidationRequiered.SLYTHERIN.value and user.house is not Houses.SLYTHERIN.value: bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) if group.val_alert is False: output = "👌 Mago infiltrado expulsado!" bot.sendMessage(chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) good_luck(bot, chat_id, message, "El usuario no está registrado") try: bot.sendMessage( chat_id=user_id, text="❌ Debes validarte para entrar en este grupo", parse_mode=telegram.ParseMode.MARKDOWN) except Exception: pass return if group.max_members is not None and group.max_members > 0 and bot.get_chat_members_count( chat_id) >= group.max_members: if group.val_alert is False: output = "❌ El número máximo de integrantes en el grupo ha sido alcanzado" sent = bot.sendMessage( chat_id=chat_id, text=output, parse_mode=telegram.ParseMode.MARKDOWN) delete_object = support.DeleteContext( chat_id, sent.message_id) job_queue.run_once(support.callback_delete, 10, context=delete_object) time.sleep(2) bot.kickChatMember(chat_id=chat_id, user_id=user_id, until_date=time.time() + 31) return if (not exists_user_group(user_id, chat_id)): set_user_group(user_id, chat_id) else: join_group(user_id, chat_id) if has_rules(chat_id): bot.restrict_chat_member(chat_id, user_id, until_date=0, can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) if get_welc_pref(chat_id): sent = send_welcome(bot, update) if sent is not None and group.delete_cooldown is not None and group.delete_cooldown > 0: delete_object = support.DeleteContext( chat_id, sent.message_id) job_queue.run_once(support.callback_delete, group.delete_cooldown, context=delete_object) ''' if group.val_alert and (user is None or user.level is None): sent = bot.sendMessage( chat_id=chat_id, text="", parse_mode=telegram.ParseMode.MARKDOWN ) if sent is not None: delete_object = support.DeleteContext(chat_id, sent.message_id) job_queue.run_once( support.callback_delete, group.delete_cooldown or 60, context=delete_object ) ''' ladmin = get_particular_admin(chat_id) if ladmin is not None and ladmin.welcome: admin = get_admin_from_linked(chat_id) if admin is not None and admin.welcome and admin.admin_bot: config = get_config() adm_bot = Bot(token=config["telegram"]["admin_token"]) replace_pogo = support.replace( user_id, message.from_user.first_name, admin=True) message_text = ( "ℹ️ {}\n👤 {} ha entrado en el grupo").format( message.chat.title, replace_pogo) adm_bot.sendMessage(chat_id=admin.id, text=message_text, parse_mode=telegram.ParseMode.MARKDOWN) elif admin is not None and admin.welcome: replace_pogo = support.replace( user_id, message.from_user.first_name, admin=True) message_text = ( "ℹ️ {}\n👤 {} ha entrado en el grupo").format( message.chat.title, replace_pogo) bot.sendMessage(chat_id=admin.id, text=message_text, parse_mode=telegram.ParseMode.MARKDOWN)
def process_group_message(bot, update, job_queue): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) msg = update.effective_message if are_banned(user_id, chat_id): return group = group_sql.get_group(chat_id) if group is None: group_sql.set_group(chat_id, message.chat.title) if not exists_user_group(user_id, chat_id): set_user_group(user_id, chat_id) message_counter(user_id, chat_id) if get_group_settings(chat_id).games == True and (chat_type == 'supergroup' or chat_type == 'group'): games_cmd(bot, update) if text is None or msg.photo is None: if msg and msg.document: nanny.process_gif(bot, update, job_queue) return elif msg and msg.contact: nanny.process_contact(bot, update, job_queue) return elif msg and msg.game: nanny.process_game(bot, update, job_queue) return elif msg and msg.location or msg.venue: nanny.process_ubi(bot, update, job_queue) return elif msg and msg.photo: nanny.process_pic(bot, update, job_queue) return elif msg and msg.sticker: nanny.process_sticker(bot, update, job_queue) return elif msg and msg.voice or msg.audio: nanny.process_voice(bot, update, job_queue) return elif msg and msg.video or msg.video_note: nanny.process_video(bot, update, job_queue) return if msg and msg.entities and nanny.process_url(bot, update, job_queue): return if nanny.nanny_text(bot, user_id, chat_id, message, job_queue): return if text is not None and re.search("@admin(?!\w)", text) is not None: replace_pogo = support.replace(user_id, message.from_user.first_name, admin=True) chat_text = support.message_url(message, message.message_id, message.chat.title) message_text = ( "ℹ️ {}\n👤 {} ha enviado una alerta a los administradores\n\nMensaje: {}" ).format(chat_text, replace_pogo, text) for admin in bot.get_chat_administrators(chat_id): user = get_user(admin.user.id) if user is not None and user.alerts: bot.sendMessage(chat_id=admin.user.id, text=message_text, parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True) ladmin = get_particular_admin(chat_id) if ladmin is not None and ladmin.admin: admin = get_admin_from_linked(chat_id) if admin is not None and admin.admin and admin.admin_bot: config = get_config() adm_bot = Bot(token=config["telegram"]["admin_token"]) replace_pogo = support.replace(user_id, message.from_user.first_name, admin=True) message_text = ("ℹ️ {}\n👤 {} {}").format( chat_text, replace_pogo, text) adm_bot.sendMessage(chat_id=admin.id, text=message_text, parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True) elif admin is not None and admin.admin: replace_pogo = support.replace(user_id, message.from_user.first_name, admin=True) message_text = ("ℹ️ {}\n👤 {} {}").format( chat_text, replace_pogo, text) bot.sendMessage(chat_id=admin.id, text=message_text, parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True)
def sighting_btn(bot, update): 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 dataThings = data.split("_") lat = dataThings[2] lon = dataThings[3] 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 if re.match(r"^sighting_ubi_", data): bot.send_location( chat_id=user_id, latitude=lat, longitude=lon, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="📍 Google Maps", url='https://maps.google.com/maps?q={0},{1}'.format( lat, lon)) ]])) return string = r'\n🕚 (\d\d:\d\d) - @{} \| (🙋♀️ ¡Está!|🙅♀️ No está...)'.format( username) text = re.sub(string, "", text) group = get_group(chat_id) group_tz = group.timezone tz = pytz.timezone(group_tz) localTime = datetime.now().replace(tzinfo=pytz.utc) groupDateTime = localTime.astimezone(tz) groupTime = groupDateTime.time() if re.match(r"^sighting_yes_", data): text = text + f"\n🕚 {groupTime.hour:02}:{groupTime.minute:02} - @{username} | 🙋♀️ ¡Está!" if re.match(r"^sighting_no_", data): text = text + f"\n🕚 {groupTime.hour:02}:{groupTime.minute:02} - @{username} | 🙅♀️ No está..." button_list = [ [ InlineKeyboardButton(text="📍 Ubicación", callback_data='sighting_ubi_{0}_{1}'.format( lat, lon)) ], [ InlineKeyboardButton(text="🙋♀️ ¡Está!", callback_data='sighting_yes_{0}_{1}'.format( lat, lon)), InlineKeyboardButton(text="🙅♀️ No está...", callback_data='sighting_no_{0}_{1}'.format( lat, lon)) ] ] bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, reply_markup=InlineKeyboardMarkup(button_list), disable_web_page_preview=True)
def fort_list_cmd(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 are_banned(chat_id, user_id): 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 message.reply_to_message is not None: if message.reply_to_message.location is not None: support.delete_message(chat_id, message.reply_to_message.message_id, bot) lat = message.reply_to_message.location.latitude lon = message.reply_to_message.location.longitude coords = str(lat) + ", " + str(lon) if re.match(r"(([0-1]?[0-9])|([0-9])|([2][0-3])):([0-5][0-9])", args[0]): regDay = None reg = re.match( r"(([0-1]?[0-9])|([0-9])|([2][0-3])):([0-5][0-9])", args[0]).group() elif re.match( r"(([0-2][0-9])|([1-9])|([3][0-1]))\/(([0-1]?[0-9])|([0-9])|([2][0-3])):([0-5][0-9])", args[0]): reg = None regDay = re.match( r"(([0-2][0-9])|([1-9])|([3][0-1]))\/(([0-1]?[0-9])|([0-9])|([2][0-3])):([0-5][0-9])", args[0]).group() if reg: poi_list = get_poi_list(chat_id, PortalType.FORTRESS.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='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[0].id, user_id, reg)) ]) if len(poi_sorted) >= 2: button_list.append([ InlineKeyboardButton( poi_sorted[1].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[1].id, user_id, reg)) ]) if len(poi_sorted) >= 3: button_list.append([ InlineKeyboardButton( poi_sorted[2].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[2].id, user_id, reg)) ]) if len(poi_sorted) >= 4: button_list.append([ InlineKeyboardButton( poi_sorted[3].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[3].id, user_id, reg)) ]) if len(poi_sorted) >= 5: button_list.append([ InlineKeyboardButton( poi_sorted[4].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[4].id, user_id, reg)) ]) button_list.append([ InlineKeyboardButton( "❌ Cancelar", callback_data='fort_cancel_{}'.format(user_id)) ]) bot.send_venue( chat_id=chat_id, title=reg, address="¿En qué fortaleza vais a quedar?", latitude=lat, longitude=lon, reply_markup=InlineKeyboardMarkup(button_list)) return elif regDay: poi_list = get_poi_list(chat_id, PortalType.FORTRESS.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='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[0].id, user_id, regDay)) ]) if len(poi_sorted) >= 2: button_list.append([ InlineKeyboardButton( poi_sorted[1].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[1].id, user_id, regDay)) ]) if len(poi_sorted) >= 3: button_list.append([ InlineKeyboardButton( poi_sorted[2].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[2].id, user_id, regDay)) ]) if len(poi_sorted) >= 4: button_list.append([ InlineKeyboardButton( poi_sorted[3].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[3].id, user_id, regDay)) ]) if len(poi_sorted) >= 5: button_list.append([ InlineKeyboardButton( poi_sorted[4].name, callback_data='fort_addubi_{0}_{1}_{2}'.format( poi_sorted[4].id, user_id, regDay)) ]) button_list.append([ InlineKeyboardButton( "❌ Cancelar", callback_data='fort_cancel_{}'.format(user_id)) ]) bot.send_venue( chat_id=chat_id, title=regDay, address="¿En qué fortaleza vais a quedar?", latitude=lat, longitude=lon, reply_markup=InlineKeyboardMarkup(button_list)) return bot.sendMessage( chat_id=chat_id, text="❌ Debes responder a una ubicación para crear la fortaleza.", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text="❌ Debes indicar una hora para crear la fortaleza.", parse_mode=telegram.ParseMode.MARKDOWN)
def btn(bot, update): query = update.callback_query data = query.data user = update.effective_user username = query.from_user.username user_id = query.from_user.id texto = query.message.text chat_id = query.message.chat.id message_id = query.message.message_id message = query.message if are_banned(user_id, chat_id): return user = get_user(user_id) if user is None: return if re.match(r"^g\*gra_", data): if texto.find(username) != -1: bot.answer_callback_query(query.id, "Ya has cogido una, deja algo al resto del grupo.", show_alert=True) return listaPalabras = data.split("_") escogido = listaPalabras[1] sel1 = listaPalabras[2] sel2 = listaPalabras[3] sel3 = listaPalabras[4] sel4 = listaPalabras[5] sel5 = listaPalabras[6] #user_lang = get_lang(chat_id) user_lang = "es_ES" flavors = grageas_json[user_lang]["sabores"] flavor = randint(0, len(flavors)-1) texto = texto + "\n @" + username + " ha escogido la gragea " + escogido + " y sabía a... ¡" + flavors[flavor] + "!" b1 = "g*gra_" + sel1 + "_" + sel1 + "_" + sel2 + "_" + sel3 + "_" + sel4 + "_" + sel5 b2 = "g*gra_" + sel2 + "_" + sel1 + "_" + sel2 + "_" + sel3 + "_" + sel4 + "_" + sel5 b3 = "g*gra_" + sel3 + "_" + sel1 + "_" + sel2 + "_" + sel3 + "_" + sel4 + "_" + sel5 b4 = "g*gra_" + sel4 + "_" + sel1 + "_" + sel2 + "_" + sel3 + "_" + sel4 + "_" + sel5 b5 = "g*gra_" + sel5 + "_" + sel1 + "_" + sel2 + "_" + sel3 + "_" + sel4 + "_" + sel5 markup = [] if texto.find(sel1)== -1: markup.append([InlineKeyboardButton(text=sel1, callback_data=b1)]) if texto.find(sel2)== -1: markup.append([InlineKeyboardButton(text=sel2, callback_data=b2)]) if texto.find(sel3)== -1: markup.append([InlineKeyboardButton(text=sel3, callback_data=b3)]) if texto.find(sel4)== -1: markup.append([InlineKeyboardButton(text=sel4, callback_data=b4)]) if texto.find(sel5)== -1: markup.append([InlineKeyboardButton(text=sel5, callback_data=b5)]) update_user_points(user_id, 1) bot.edit_message_text( text=texto, chat_id=chat_id, message_id=message_id, reply_markup=InlineKeyboardMarkup(markup)) elif re.match(r"g\*whosaid_", data): if texto.find(username) != -1: return ent = message.parse_entities(["mention"]) if len(ent) > 0: bot.answer_callback_query(query.id, "Alguien ha respondido ya.", show_alert=True) return listaPalabras = data.split("_") if listaPalabras[1] == "success": update_user_points(user_id, 3) update_group_points(chat_id, 3) bot.edit_message_text( text=texto + "\n\n@" + username + " ha acertado!", chat_id=chat_id, message_id=message_id) return update_user_points(user_id, -1) bot.answer_callback_query(query.id, "Has fallado.", show_alert=True) elif re.match(r"g\*duel_", data): ''' if texto.find(username) != -1: return ''' listaPalabras = data.split("_") if listaPalabras[1] == "accept": if listaPalabras[2] == user_id: bot.answer_callback_query(query.id, "Busca a alguien con quien pelear.", show_alert=True) return ent = message.parse_entities(["mention"]) for mention in ent: userCreated = message.parse_entity(mention) replace = f"Hechizos {userCreated}: 0\nHechizos @{username}: 0\n\n ¡Empieza el duelo!" re1 = re.sub(r"(¿Quién aceptará el duelo\?)", replace, texto) re2 = re.sub(r"(\?\?\?)", f"@{username}", re1) buttons = [ [InlineKeyboardButton(text="Atacar", callback_data=f"g*duel_attack_0_0_{listaPalabras[2]}_{user_id}")], [InlineKeyboardButton(text="Defender", callback_data=f"g*duel_defend_0_0_{listaPalabras[2]}_{user_id}")], [InlineKeyboardButton(text="Pensar", callback_data=f"g*duel_think_0_0_{listaPalabras[2]}_{user_id}")]] bot.edit_message_text( text=re2, chat_id=chat_id, message_id=message_id, reply_markup=InlineKeyboardMarkup(buttons)) return elif listaPalabras[1] == "attack": createdUser = listaPalabras[4] otherUser = listaPalabras[5] user1magic = listaPalabras[2] user2magic = listaPalabras[3] ent = message.parse_entities(["mention"]) duelUsers = {} count = 0 for mention in ent: user = message.parse_entity(mention) if count == 0: duelUsers[createdUser] = user count += 1 elif count == 1: duelUsers[otherUser] = user count += 1 if user_id == int(createdUser) and int(user1magic) == 0: bot.answer_callback_query(query.id, "Antes de atacar debes pensar.", show_alert=True) return elif user_id == int(otherUser) and int(user2magic) == 0: bot.answer_callback_query(query.id, "Antes de atacar debes pensar.", show_alert=True) return replace = f"Hechizos {userCreated}: 0\nHechizos @{username}: 0\n\n ¡Empieza el duelo!" re1 = re.sub(r"(¿Quién aceptará el duelo\?)", replace, texto) re2 = re.sub(r"(\?\?\?)", f"@{username}", re1) buttons = [ [InlineKeyboardButton(text="Atacar", callback_data=f"g*duel_attack_0_0_{listaPalabras[2]}_{user_id}")], [InlineKeyboardButton(text="Defender", callback_data=f"g*duel_defend_0_0_{listaPalabras[2]}_{user_id}")], [InlineKeyboardButton(text="Pensar", callback_data=f"g*duel_think_0_0_{listaPalabras[2]}_{user_id}")]] bot.edit_message_text( text=re2, chat_id=chat_id, message_id=message_id, reply_markup=InlineKeyboardMarkup(buttons)) return update_user_points(user_id, -1) update_group_points(chat_id, -1) bot.answer_callback_query(query.id, "Has fallado.", show_alert=True)