def good_luck(bot, chat_id, message, text): ladmin = get_particular_admin(chat_id) user_id = message.from_user.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👤 {} {}").format(message.chat.title, replace_pogo, text) 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👤 {} {}").format(message.chat.title, replace_pogo, text) bot.sendMessage(chat_id=admin.id, text=message_text, parse_mode=telegram.ParseMode.MARKDOWN)
def create_needed_paths(): config = get_config() if not config: logging.error( 'Not configuration loaded. Please, use `create_needed_paths` ' 'only after loading a valid configuration') raise ConfigurationNotLoaded() needed_dirs = [] needed_dirs.append( os.path.dirname(os.path.expanduser(config['general'].get('log'))) or os.getcwd()) needed_dirs.append( os.path.dirname(os.path.expanduser(config['general']['jsondir']))) needed_dirs.append( os.path.dirname(os.path.expanduser(config['general']['mediadir']))) for directory in needed_dirs: if not os.path.exists(directory): os.makedirs(directory) return True
def get_db_engine(): global __ENGINE if __ENGINE is None: config = get_config() try: db_url = config['database']['db-url'] except KeyError: db_url = 'mysql://{user}:{password}@{host}:{port}/{schema}?charset=utf8mb4'.format( **config['database']) debug = config['database'].get('debug', "false") if debug.lower() == "false": debug = False else: try: debug = bool(int(debug)) # numeric values except ValueError: debug = bool(debug) if debug: print('DB URL: ', db_url) __ENGINE = create_engine(db_url, pool_size=35, max_overflow=50, echo=False, pool_pre_ping=True) return __ENGINE
def tablas_btn(bot, update): logging.debug("%s %s" % (bot, update)) query = update.callback_query data = query.data chat_id = query.message.chat.id config = get_config() news_id = int(config["telegram"]["news_id"]) message_id = query.message.message_id match_new = re.match(r"tabla_new_(.*)", query.data) if match_new: text = "Ha sido añadida la tabla {0} a nuestros archivos. Solicítala ya mediante `@ProfesorDumbledoreBot {0}`\n\n¡Suerte en tu búsqueda, mago!".format( match_new.group(1)) bot.sendMessage(chat_id=news_id, text=text, parse_mode=telegram.ParseMode.MARKDOWN) match_edit = re.match(r"tabla_edit_(.*)", query.data) if match_new is None and match_edit: text = "Ha sido modificada la tabla {0}. Recuerda que puedes solicitarla mediante `@ProfesorDumbledoreBot {0}`\n\n¡Suerte en tu búsqueda, mago!".format( match_edit.group(1)) bot.sendMessage(chat_id=news_id, text=text, parse_mode=telegram.ParseMode.MARKDOWN) bot.edit_message_reply_markup(chat_id=chat_id, message_id=message_id, reply_markup=None) return
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 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 start_bot(): signal.signal(signal.SIGINT, support.cleanup) parser = argparse.ArgumentParser() parser.add_argument( '-c', '--cfg', default=config_file.get_default_config_path(), type=str, help='path to the Dumbledore bot config file (Default: %(default)s') parser.add_argument('--create-config', default=False, action='store_true', help='') args = parser.parse_args() if args.create_config: config_file.create_default_config(args.cfg) sys.exit(0) config = config_file.get_config(args.cfg) support.create_needed_paths() model.create_databases() log = (os.path.expanduser(config['general'].get('log')) or os.path.join(os.getcwd(), 'debug.log')) log_handler = TimedRotatingFileHandler(log, when='d', interval=1, backupCount=5) logging.basicConfig( format= "%(asctime)s %(name)s %(module)s:%(funcName)s:%(lineno)s - %(message)s", handlers=[log_handler], level=logging.DEBUG) logging.info("--------------------- Starting bot! -----------------------") updater = Updater(token=config["telegram"]["token"], workers=24, request_kwargs={ 'read_timeout': 15, 'connect_timeout': 15 }) dispatcher = updater.dispatcher dispatcher.add_error_handler(support.error_callback) dispatcher.add_handler( CommandHandler('games', games.game_spawn_cmd, Filters.group, pass_args=True)) #dispatcher.add_handler(CommandHandler('duel', games.duel_cmd, Filters.group)) dispatcher.add_handler(CallbackQueryHandler(games.btn, pattern=r"^g\*")) #Juego Cumple Nelu #dispatcher.add_handler(CommandHandler('nelu', nelu.nelu_cmd, Filters.user(int(config["telegram"]["saray"])), pass_job_queue=True)) #dispatcher.add_handler(CallbackQueryHandler(nelu.nelu_btn, pattern=r"^nelu_")) dispatcher.add_handler( CommandHandler(['fort', 'fortaleza'], fortress.fort_list_cmd, Filters.group, pass_args=True)) #dispatcher.add_handler(CommandHandler(['fort_refloat', 'fortrefloat'], fortress.fort_refloat_cmd, Filters.group)) #dispatcher.add_handler(CommandHandler(['fort_delete', 'fortremove', 'rm_fort'], fortress.fort_remove_cmd, Filters.group)) dispatcher.add_handler( CallbackQueryHandler(fortress.fort_btn, pattern=r"^fort_", pass_job_queue=True)) #TBRdispatcher.add_handler(CommandHandler('avistamiento', sighting.sighting_cmd, Filters.group)) dispatcher.add_handler( CallbackQueryHandler(sighting.sighting_btn, pattern=r"^sighting_")) dispatcher.add_handler( CommandHandler(['add_plant', 'addplant'], greenhouses.add_ingredients_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler(['rm_plant', 'rmplant'], greenhouses.rem_plant_cmd, Filters.group, pass_args=True, pass_job_queue=True)) dispatcher.add_handler( CommandHandler(['plantaciones', 'plant_list'], greenhouses.plants_list_cmd, Filters.group)) dispatcher.add_handler( CallbackQueryHandler(greenhouses.gh_btn, pattern=r"^gh_", pass_job_queue=True)) dispatcher.add_handler( CommandHandler(['add_poi', 'addpoi'], profdumbledorebot.add_poi_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler(['rm_poi', 'rmpoi'], profdumbledorebot.rem_poi_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler(['poi_list', 'poilist'], profdumbledorebot.poi_list_cmd, Filters.group)) dispatcher.add_handler( CallbackQueryHandler(profdumbledorebot.poi_btn, pattern=r"^poi_")) dispatcher.add_handler( CommandHandler( ['midepollas', 'flipaos'], profdumbledorebot.ranking_spain_cmd, Filters.chat(int(config["telegram"]["spain_id"])) & Filters.user(int(config["telegram"]["ranking_admin_id"])))) #TBRdispatcher.add_handler(CommandHandler('puntos', profdumbledorebot.points_cmd, Filters.private)) dispatcher.add_handler( CommandHandler('ranking', profdumbledorebot.private_ranking_cmd, Filters.group)) dispatcher.add_handler(CommandHandler('ping', profdumbledorebot.ping_cmd)) dispatcher.add_handler( CommandHandler(['fclist', 'fc'], profdumbledorebot.fclist_cmd, Filters.group)) dispatcher.add_handler( CommandHandler(['help', 'start'], profdumbledorebot.start_cmd, pass_args=True)) dispatcher.add_handler( CommandHandler(['whois', 'informe', 'info'], profdumbledorebot.whois_cmd, pass_args=True)) dispatcher.add_handler( CallbackQueryHandler(profdumbledorebot.register_btn, pattern=r"^reg_")) dispatcher.add_handler( CallbackQueryHandler(profdumbledorebot.passport_btn, pattern=r"^profile_")) dispatcher.add_handler( CommandHandler(['passport', 'pasaporte', 'profile', 'perfil'], profdumbledorebot.passport_cmd, Filters.private)) dispatcher.add_handler( CommandHandler('set_friendid', profdumbledorebot.set_friendid_cmd, Filters.private, pass_args=True)) dispatcher.add_handler( CommandHandler(['register', 'registro', 'cucuruchodecucarachas'], profdumbledorebot.register_cmd, Filters.private)) ''' dispatcher.add_handler(CommandHandler('rm_cmd', rm_cmd_cmd, Filters.group)) dispatcher.add_handler(CommandHandler('new_cmd', new_cmd_cmd, Filters.group)) dispatcher.add_handler(CommandHandler('list_cmds', list_cmds_cmd, Filters.group)) ''' dispatcher.add_handler( CommandHandler('rm_admin', admin.rm_admin_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('create_admin', admin.create_admin_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('settings_admin', admin.settings_admin_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('rm_link', admin.rm_link_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('add_tag', admin.add_tag_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('add_url', admin.add_url_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('create_link', admin.create_link_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler(['groups', 'grupos'], admin.groups_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('ban', admin.ban_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('kick', admin.kick_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('warn', admin.warn_cmd, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('unban', admin.unban_cmd, Filters.group, pass_args=True)) #dispatcher.add_handler(CommandHandler('mute', admin.mute_cmd, Filters.group, pass_args=True)) #dispatcher.add_handler(CommandHandler('unwarn', unwarn_cmd, Filters.group, pass_args=True)) #TBRdispatcher.add_handler(CommandHandler('dumbleuv', admin.uv_cmd, Filters.group, pass_args=True)) #TBRdispatcher.add_handler(CommandHandler('dumblekickuv', admin.kickuv_cmd, Filters.group, pass_args=True)) #TBRdispatcher.add_handler(CommandHandler('dumblekickmsg', admin.kickmsg_cmd, Filters.group, pass_args=True)) #TBRdispatcher.add_handler(CommandHandler('dumblekickold', admin.kickold_cmd, Filters.group, pass_args=True)) dispatcher.add_handler(CommandHandler('rules', rules.rules, Filters.group)) dispatcher.add_handler( CommandHandler('set_rules', rules.set_rules, Filters.group)) dispatcher.add_handler( CommandHandler('clear_rules', rules.clear_rules, Filters.group)) dispatcher.add_handler( CommandHandler('list', lists.list_cmd, Filters.group)) dispatcher.add_handler( CallbackQueryHandler(lists.list_btn, pattern=r"^list_")) dispatcher.add_handler( CommandHandler('listopen', lists.listopen_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('listclose', lists.listclose_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('listrefloat', lists.listrefloat_cmd, Filters.group)) dispatcher.add_handler( CommandHandler('settings', settings.settings, Filters.group)) dispatcher.add_handler( CommandHandler('set_pince', nanny.set_nanny, Filters.group)) dispatcher.add_handler( CommandHandler('set_welcome', settings.set_welcome, Filters.group)) #TBRdispatcher.add_handler(CommandHandler('test_welcome', welcome.test_welcome, Filters.group)) dispatcher.add_handler( CommandHandler('set_zone', settings.set_zone, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('set_cooldown', settings.set_cooldown, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('set_maxmembers', settings.set_maxmembers, Filters.group, pass_args=True)) dispatcher.add_handler(InlineQueryHandler(tablas.inline_tablas)) dispatcher.add_handler( CallbackQueryHandler(tablas.tablas_btn, pattern=r"^tabla_")) dispatcher.add_handler( CommandHandler('tablas', tablas.list_pics, Filters.chat(int(config["telegram"]["staff_id"])), pass_args=True)) dispatcher.add_handler( CommandHandler('nueva_tabla', tablas.new_pic, Filters.chat(int(config["telegram"]["staff_id"])), pass_args=True)) dispatcher.add_handler( CommandHandler('borrar_tabla', tablas.rm_pic, Filters.chat(int(config["telegram"]["staff_id"])), pass_args=True)) dispatcher.add_handler( CommandHandler('editar_tabla', tablas.edit_pic, Filters.chat(int(config["telegram"]["staff_id"])), pass_args=True)) dispatcher.add_handler( CommandHandler('list_news', news.list_news, Filters.group)) dispatcher.add_handler( CommandHandler('rm_news', news.rm_news, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('add_news', news.add_news, Filters.group, pass_args=True)) dispatcher.add_handler( CommandHandler('add_staff', staff.add_staff_cmd, pass_args=True)) dispatcher.add_handler( CommandHandler('rm_staff', staff.rm_staff_cmd, pass_args=True)) dispatcher.add_handler( MessageHandler(Filters.group & Filters.status_update.new_chat_members, group.joined_chat, pass_job_queue=True)) dispatcher.add_handler( MessageHandler(Filters.command, nanny.process_cmd, pass_job_queue=True)) dispatcher.add_handler( MessageHandler(Filters.group & Filters.all, group.process_group_message, pass_job_queue=True)) dispatcher.add_handler(MessageHandler(Filters.all, news.send_news)) dispatcher.add_handler(CallbackQueryHandler(settings.settingsbutton)) job_queue = updater.job_queue job_queue.run_repeating(save_jobs_job, timedelta(minutes=5)) try: support.load_jobs(job_queue) except FileNotFoundError: # First run pass updater.start_polling(timeout=25) support.save_jobs(job_queue) sys.exit(0)
def send_welcome(bot, update): chat_id, chat_type, user_id, text, message = support.extract_update_info( update) chat = update.effective_chat 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) if should_welc: sent = None new_members = update.effective_message.new_chat_members for new_mem in new_members: 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 = new_mem.first_name or "" if cust_welcome: if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_markdown(new_mem.id, first_name) if new_mem.username: username = "******" + escape_markdown(new_mem.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(new_mem.last_name or first_name), hpwu=support.replace(new_mem.id, first_name), nombrecompleto=escape_markdown(fullname), usuario=username, mention=mention, count=count, title=escape_markdown(chat.title), id=new_mem.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) sent = send(bot, chat_id, res, keyboard) return sent