def song(bot, update): # Function for handling audio-messages chat_id = update.message.chat_id print("\tRecibida canción") print("ID: ", chat_id) get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) if lang == 'es': bot.sendMessage( chat_id, text="Tienes un gusto horrible... Mejor te envÃo yo algo 😜", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, text= "You have a horrible taste in music... I better send you something 😜", parse_mode=telegram.ParseMode.MARKDOWN)
def help_handler(bot, update): chat_id = update.message.chat_id get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) print(lang) if db_m.is_time(chat_id, None) == '1': if lang == 'es': bot.sendMessage(chat_id=chat_id, text="En esta parte, envíanos *el nombre de tu país* o bien *tu ubicación*." \ "\nDe esta manera podremos enviarte artículos y noticias si nos lo programas", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage(chat_id=chat_id, text="Now, send us *your country name* or your *location*. "\ "\nWith this, we will be able to send you articles and news if you schedule that", parse_mode=telegram.ParseMode.MARKDOWN) elif db_m.is_pref(chat_id, None) == '1': key_two(bot, update, chat_id, lang, None) elif db_m.is_prog(chat_id, None) == '1': key_four(bot, update, chat_id, lang, None) else: main_menu(bot, update, chat_id, None, lang)
def nothing( bot, update ): # 'nothing' function for unexpected messages (documents, contacts, etc) chat_id = update.message.chat_id print("ID: ", chat_id) get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) if lang == 'es': bot.sendMessage( chat_id=update.message.chat_id, text= "No puedo hacer nada con lo que me has enviado 🤔\n\nEscribe /help para obtener ayuda" ) else: bot.sendMessage( chat_id, text= "I can not do anything with what you have sent me 🤔\n\nType /help to get help" )
def prog(bot, update, chat_id): lang = db_m.read_lang(chat_id) last_msg = db_m.read_last_msgid(chat_id) if last_msg is not None: try: bot.deleteMessage(chat_id=chat_id, message_id=last_msg) except telegram.error.BadRequest: print("Message to delete not found. Chat_id:", chat_id, "| message_id:", last_msg) pass print("Recopilando noticias ...\n\n<Programación>", chat_id) if lang == 'es': msg = bot.sendMessage( chat_id, "Estamos recopilando las *últimas noticias* 📈... Por favor, espere 🕙", parse_mode=telegram.ParseMode.MARKDOWN) else: msg = bot.sendMessage( chat_id, "We are looking for the *latest news* 📈... Please, wait 🕙", parse_mode=telegram.ParseMode.MARKDOWN) mid = msg.message_id db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lfn.update_news(bot, update, chat_id, mid)
def voice(bot, update): # Function for handling voice-messages chat_id = update.message.chat_id print("\tRecibido audio") print("ID: ", chat_id) get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) if lang == 'es': bot.sendMessage( chat_id, text= "Una voz preciosa, pero particularmente prefiero a _Lady GaGa_ 💃", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, text="What a beautiful voice, but I prefer _Lady GaGa_ 💃", parse_mode=telegram.ParseMode.MARKDOWN)
def issues(bot, update): chat_id = update.message.chat_id get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) if lang == 'es': bot.sendMessage(chat_id=chat_id, text="ᴘʀᴏʙʟᴇᴍᴀs ᴄᴏɴᴏᴄɪᴅᴏs\n\n*1.* *No aparecen algunas de mis preferencias* ❌ al usar /start. " \ "*Google* tiene una política de servicio muy estricta 👮 y limita los resultados que recoge el bot." \ " *Para solucionarlo*, lo mejor es eliminar todas las preferencias y añadir solo " \ "*palabras clave*, sin utilizar _trucos de búsqueda_", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage(chat_id=chat_id, text="ᴋɴᴏᴡɴ ɪssᴜᴇs\n\n*1.* *There is no results of my preferences* ❌ while using /start. " \ "*Google* has a very strict usage policy 👮 and limit bot results. For *solving it*, the best " \ "option is deleting all preferences and add only *keywords*, without using _search tricks_", parse_mode=telegram.ParseMode.MARKDOWN)
def photo(bot, update): # Function for handling photo-messages chat_id = update.message.chat_id get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) print("\tRecibida imagen") if lang == 'es': bot.sendMessage( chat_id, text= "*¡¡NO VEO!!* *¡¡ME HE QUEDADO CIEGO!!*\nAh, no... Que no tengo ojos 😅", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, text= "*I CAN'T SEE ANYTHING!!* *I'M BLIND!!*\nAh, no... I have no eyes 😅", parse_mode=telegram.ParseMode.MARKDOWN)
def video(bot, update): # Function for handling video-messages chat_id = update.message.chat_id print("\tRecibido vÃdeo") print("ID: ", chat_id) get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) if lang == 'es': bot.sendMessage( chat_id, text= "Gracias pero yo soy más de cine mudo escocés subtitulado en ruso 😶", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, text= "Thank you so much but I prefer Scottish silent movies with Russian subtitles 😶", parse_mode=telegram.ParseMode.MARKDOWN)
def update_news(bot, update, chat_id, message_id): pref = db_m.get_pref(chat_id) lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) if path.exists('dict_out_{}.json'.format(chat_id)): os.remove('dict_out_{}.json'.format(chat_id)) if path.exists('current_{}.txt'.format(chat_id)): os.remove('current_{}.txt'.format(chat_id)) a = pref.split(",") b = {} total = 0 try: length = len(a) max_r = db_m.get_max(chat_id) if max_r is None: num_res = int(75/length) else: num_res = int(max_r/length) for i in range(0, length): addition = i*num_res search_results = gsearch.search_news(query=a[i], lang=lang, num=num_res) news = search_results[0] total += 1 for u in range(1, num_res): try: page = news.get("Page {}".format(u)) if page is not None: b["Page {}".format(u+addition)] = page total += 1 except KeyError: pass search_results = {} q = 1 for k, y in b.items(): if y not in search_results.values() and q <= total: current_num = str(q) if y is not None: try: key = "Page {}".format(current_num) search_results[key] = y q = q + 1 except KeyError: pass if len(search_results) < 1: if lang == 'es': bot.editMessageText(chat_id=chat_id, text="Tu búsqueda no ha obtenido resultados ❌", message_id=message_id) else: bot.editMessageText(chat_id=chat_id, text="Your search did not get resuls ❌", message_id=message_id) else: db_m.last_msgid(chat_id, message_id) nkr.load_keys(bot, update, chat_id, search_results, message_id) except IndexError: pass
def key_one(bot, update, chat_id, message_id): input_data = open('dict_out_{}.json'.format(chat_id), 'rb') json_data = json.load(input_data) a = 1 current_val = open('current_{}.txt'.format(chat_id), 'w') current_val.write(str(a)) current_val.close() lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) url = json_data["Page {}".format(a)] if url is None: if db_m.read_lang(chat_id) == 'es': bot.sendMessage(chat_id=chat_id, text="Tu búsqueda no ha obtenido resultados") msg_id = db_m.read_last_msgid(chat_id) if msg_id is not None: bot.deleteMessage(chat_id=chat_id, message_id=msg_id) db_m.last_msgid(chat_id, None) else: bot.sendMessage(chat_id=chat_id, text="Your search has no results") else: title = title_finder(url) if lang == 'es': keyboard = [[ InlineKeyboardButton("Leer más 📖", url=url), InlineKeyboardButton("Siguiente 📰", callback_data='next1') ]] else: keyboard = [[ InlineKeyboardButton("Read more 📖", url=url), InlineKeyboardButton("Next 📰", callback_data='next1') ]] reply_markup = InlineKeyboardMarkup(keyboard) bot.editMessageText(chat_id=chat_id, text="*{}*\n[Link 🔗]({})".format(title, url), parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup, message_id=message_id) # db_m.last_msgid(chat_id, message_id) return "OK"
def develop(bot, update): chat_id = update.message.chat_id print("Executing /develop") url1 = 'https://goo.gl/K7vs1z' url2 = 'https://goo.gl/60ECGQ' get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) if path.exists("first_run_{}".format(chat_id)): bot.sendMessage( chat_id=chat_id, text= "¡Hey! Primero tienes que terminar la configuración inicial\n\nHey! first you have to finish the initial setup" ) elif lang == 'es': keyboard = [[ InlineKeyboardButton("Ir al proyecto 👁", url=url1), InlineKeyboardButton("Apoya este bot 🌟", url=url2) ]] rp_mk = InlineKeyboardMarkup(keyboard) bot.sendMessage(chat_id=chat_id, text="_¿Eres desarrollador? 🤓 ¿Te interesa aprender? 📚_ *Estás en el lugar indicado*."\ "\n\nNuestra política (_basada en la de Telegram_) confía en los proyectos *OpenSource* (de "\ "código libre) 📖 y, por lo tanto, este bot es *completamente público* 👏\nPuedes acceder al"\ " [proyecto en GitHub 🔗](https://github.com/Javinator9889/NewsBot) y ver cómo lo hemos hecho."\ " Está escrito *en Python 3* y en el proyecto tienes una *lista con los repositorios que"\ " necesitas* 🗒 para que funcione.\n\nSi quieres contribuir, *no dudes en dejar tu estrella 🌟*,"\ " y *compartir el proyecto* 🗣", parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=rp_mk, disable_web_page_preview=True) else: keyboard = [[ InlineKeyboardButton("Go to the project 👁", url=url1), InlineKeyboardButton("Support this bot 🌟", url=url2) ]] rp_mk = InlineKeyboardMarkup(keyboard) bot.sendMessage(chat_id=chat_id, text="_Are you a developer? 🤓 Are you interested in learning? 📚_ *You are in the right place*." \ "\n\nOur policy (_based on Telegram ones_) rely on *OpenSource* project (" "free code) 📖 so, this bot is *completely public* 👏\nYou can access to" \ " [GitHub project 🔗](https://github.com/Javinator9889/NewsBot) and see how we did it." \ " It is written in *Python 3* and, in the project, you have a *list with dependencies" \ " you need* 🗒 for working properly.\n\nIf you want to contribute, *don't hesitate to rate 🌟*," \ " and *share the project* 🗣", parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=rp_mk, disable_web_page_preview=True)
def location(bot, update): chat_id = update.message.chat_id lat = update.message.location.latitude long = update.message.location.longitude get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) if db_m.is_time(chat_id, None) == '1': get_time_zone = "https://maps.googleapis.com/maps/api/timezone/json?location={},{}×tamp=1458000000&key={}".format( lat, long, API_KEY_geo) open_zone = urllib.request.urlopen(get_time_zone) data_zone = open_zone.read() zone_data = json.loads(data_zone.decode('utf-8')) zone_id = zone_data["timeZoneId"] db_m.update_time(chat_id, zone_id) db_m.is_time(chat_id, False) if lang == 'es': bot.sendMessage( chat_id=chat_id, text="Perfecto, hemos actualizado tu *zona horaria* 🌎", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text="Perfect, we have just updated your *time-zone* 🌎", parse_mode=telegram.ParseMode.MARKDOWN) if path.exists("first_run_{}".format(chat_id)): st.cont_2(bot, update, chat_id) else: if lang == 'es': bot.sendMessage( chat_id, text= "Por *motivos de seguridad*, primero _tienes que ir_ a /config y luego *actualizar tu zona horaria*", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, text= "For *security reasons*, first you _have to go to_ /config and then *change your time-zone*", parse_mode=telegram.ParseMode.MARKDOWN)
def policy(bot, update): chat_id = update.message.chat_id print("Executing /privacy") get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) if path.exists("first_run_{}".format(chat_id)): bot.sendMessage( chat_id=chat_id, text= "¡Hey! Primero tienes que terminar la configuración inicial\n\nHey! first you have to finish the initial setup" ) elif lang == 'es': bot.sendMessage(chat_id=chat_id, text="ᴛéʀᴍɪɴᴏs ᴅᴇ sᴇʀᴠɪᴄɪᴏ ʏ ᴘᴏʟíᴛɪᴄᴀs ᴅᴇ ᴘʀɪᴠᴀᴄɪᴅᴀᴅ" \ "\n\nAl utilizar este bot, *aceptas que recopilemos* y guardemos datos sobre ti tales como" \ " tu *nombre de usuario*, *zona horaria*, *gustos y preferencias*. Dichos datos no son ni serán" \ " *compartidos con terceros* y estarán bajo protección *inclusive cuando el usuario elimine* y" \ " *bloquee al bot*. En este caso, se pasará o a la *conservación de los datos* o a la" \ " *eliminación de los mismos*, según se convenga.\nCuando el bot recibe una ubicación, por " \ "*motivos de seguridad*, primero hay que activar la opción de cambio de zona horaria para" \ " evitar cualquier *fuga de datos*. A su vez, la ubicación *solo y únicamente se emplea* para" \ " determinar tu zona horaria. Después, *la ubicación enviada se elimina*." \ "\n\nPara *cualquier duda*, [contacta conmigo aquí](http://t.me/Javinator_9889) o escríbeme por aquí: @Javinator\\_9889", parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True) else: bot.sendMessage(chat_id=chat_id, text="ᴛᴇʀᴍs ᴏғ sᴇʀᴠɪᴄᴇ ᴀɴᴅ ᴘʀɪᴠᴀᴄʏ ᴘᴏʟɪᴛɪᴄs" \ "\n\nWhen using this bot, *you accept that we save and store* data about you such as" \ " your *username*, *time zone*, *pleasures and preferences*. Those data are not and will" \ " not be *shared with third party entities* and will be under protection *although the*" \ " *user stops and deletes the bot*. In this case, data can be *saved and protected* or" \ " *completely deleted*, as appropriate.\nWhen the bot gets a location, because of " \ "*security reasons*, first you have to active the option of changing time-zone in order to" \ " avoid *data leak*. Also, your location *is single and only used* to" \ " decide your time-zone. Then, *sent location is deleted*." \ "\n\nFor *any doubt*, [contact me here](http://t.me/Javinator_9889) or write me with: @Javinator\\_9889", parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True)
def cont_1(bot, update, chat_id, message_id): lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) if lang == 'es': bot.editMessageText( chat_id=chat_id, text= "Genial 🙌\nAhora que sé en qué idioma buscar tus artÃculos, \ dime en qué paÃs vives. También puedes enviarme *tu ubicación* 🛰", parse_mode=telegram.ParseMode.MARKDOWN, message_id=message_id) db_m.is_time(chat_id, True) else: bot.editMessageText( chat_id=chat_id, text= "Great 🙌\nNow that I know in which language I must look for your articles, \ tell me where are you living. Also you can send me *your location* 🛰", parse_mode=telegram.ParseMode.MARKDOWN, message_id=message_id) db_m.is_time(chat_id, True) db_m.is_time(chat_id, True)
def upd_pref(bot, chat_id, text): lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) if text == "Terminado" or text == "terminado" or text == "Done" or text == "done": if path.exists("pref_{}.txt".format(chat_id)): pref_file = open("pref_{}.txt".format(chat_id), 'r') pref = pref_file.readline() pref_file.close() os.remove("pref_{}.txt".format(chat_id)) db_m.update_pref(chat_id, pref) if lang == 'es': bot.sendMessage( chat_id, "Perfecto, hemos actualizado tus preferencias") else: bot.sendMessage(chat_id, "Perfect, everything is updated") else: if lang == 'es': bot.sendMessage(chat_id, "No se ha realizado ningún cambio") else: bot.sendMessage(chat_id, "No changes were done") db_m.is_pref(chat_id, False) elif text == "Cancelar" or text == "cancelar" or text == "Cancell" or text == "cancell": if path.exists("pref_{}.txt".format(chat_id)): os.remove("pref_{}.txt".format(chat_id)) db_m.is_pref(chat_id, False) if lang == 'es': bot.sendMessage( chat_id, "Se ha cancelado la actualización de las preferencias") else: bot.sendMessage(chat_id, "Updating preferences cancelled") elif 'Eliminar' in text or 'eliminar' in text: if path.exists("pref_{}.txt".format(chat_id)): file = open("pref_{}.txt".format(chat_id), 'r') saved_pref = file.readline() file.close() if saved_pref == '' or saved_pref is None: err = True else: pref_list = saved_pref.split(",") out = [var for var in pref_list if var] err = False else: saved_pref = db_m.get_pref(chat_id) if saved_pref == '' or saved_pref is None: err = True else: pref_list = saved_pref.split(",") out = [var for var in pref_list if var] err = False delete = text[9:] delete_list = delete.split(",") # print(delete_list, out) deleting = [] if err is True: if lang == 'es': bot.sendMessage(chat_id, "No puedes eliminar nada más...") else: bot.sendMessage(chat_id, "You can't delete anything else...") else: for k in range(0, len(delete_list)): elem = int(delete_list[k]) - 1 try: deleting.append(out[elem]) except (ValueError, IndexError, KeyError): bot.sendMessage(chat_id, "...") for x in range(0, len(deleting)): print(deleting[x], len(deleting)) try: out.remove(deleting[x]) out = [var for var in out if var] except (ValueError, IndexError, KeyError): bot.sendMessage(chat_id, "...") # print(out) write_file = open("pref_{}.txt".format(chat_id), 'w') for item in out: write_file.write("%s," % item) write_file.close() if len(out) == 0: if lang == 'es': comp_list = "_vacío_" else: comp_list = "_empty_" else: for a in range(0, len(out)): lst = re.findall(r'"(.*?)(?<!\\)"', out[a]) if a == 0: try: comp_list = "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list = "*" + str( a + 1) + "*: " + "_" + out[a] + "_" + "\n" else: if out[a] != '': try: comp_list += "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list += "*" + str( a + 1) + "*: " + "_" + out[a] + "_" + "\n" if lang == 'es': bot.sendMessage( chat_id=chat_id, text="_Estado actual de tus preferencias:_\n\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text="_Current status of your preferences:_\n\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN) elif 'Delete' in text or 'delete' in text: if path.exists("pref_{}.txt".format(chat_id)): file = open("pref_{}.txt".format(chat_id), 'r') saved_pref = file.readline() file.close() if saved_pref == '' or saved_pref is None: err = True else: pref_list = saved_pref.split(",") out = [var for var in pref_list if var] err = False else: saved_pref = db_m.get_pref(chat_id) if saved_pref == '' or saved_pref is None: err = True else: pref_list = saved_pref.split(",") out = [var for var in pref_list if var] err = False delete = text[7:] delete_list = delete.split(",") # print(delete_list, out) deleting = [] if err is True: if lang == 'es': bot.sendMessage(chat_id, "No puedes eliminar nada más...") else: bot.sendMessage(chat_id, "You can't delete anything else...") else: for k in range(0, len(delete_list)): try: elem = int(delete_list[k]) - 1 deleting.append(out[elem]) except (ValueError, IndexError, KeyError): bot.sendMessage(chat_id, "...") for x in range(0, len(deleting)): # print(deleting[x], len(deleting)) try: out.remove(deleting[x]) out = [var for var in out if var] except ValueError: bot.sendMessage(chat_id, "...") # print(out) write_file = open("pref_{}.txt".format(chat_id), 'w') for item in out: write_file.write("%s," % item) write_file.close() if len(out) == 0: if lang == 'es': comp_list = "_vacío_" else: comp_list = "_empty_" else: for a in range(0, len(out)): lst = re.findall(r'"(.*?)(?<!\\)"', out[a]) if a == 0: try: comp_list = "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list = "*" + str( a + 1) + "*: " + "_" + out[a] + "_" + "\n" else: if out[a] != '': try: comp_list += "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list += "*" + str( a + 1) + "*: " + "_" + out[a] + "_" + "\n" if lang == 'es': bot.sendMessage( chat_id=chat_id, text="_Estado actual de tus preferencias:_\n\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text="_Current status of your preferences:_\n\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN) else: if path.exists("pref_{}.txt".format(chat_id)): file = open("pref_{}.txt".format(chat_id), 'r') saved_pref = file.readline() file.close() if saved_pref == '' or saved_pref is None: out = [] else: pref_list = saved_pref.split(",") out = [var for var in pref_list if var] else: saved_pref = db_m.get_pref(chat_id) if saved_pref == '' or saved_pref is None: out = [] else: pref_list = saved_pref.split(",") out = [var for var in pref_list if var] new_pref = text.split(",") print(new_pref) a = len(new_pref) for v in range(0, a): if new_pref[v] not in out: out.append(new_pref[v]) print(out) save_file = open("pref_{0}.txt".format(chat_id), 'w') for x in range(0, len(out)): save_file.write(out[x] + ",") save_file.close() if len(out) == 0: if lang == 'es': comp_list = "_vacío_" else: comp_list = "_empty_" else: for a in range(0, len(out)): lst = re.findall(r'"(.*?)(?<!\\)"', out[a]) if a == 0: try: comp_list = "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list = "*" + str( a + 1) + "*: " + "_" + out[a] + "_" + "\n" else: if out[a] != '': try: comp_list += "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list += "*" + str( a + 1) + "*: " + "_" + out[a] + "_" + "\n" if lang == 'es': bot.sendMessage(chat_id=chat_id, text="_Estado actual de tus preferencias:_\n\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage(chat_id=chat_id, text="_Current status of your preferences:_\n\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN)
def key_var(bot, update, chat_id, message_id, n_or_p): input_data = open('dict_out_{}.json'.format(chat_id), 'rb') json_data = json.load(input_data) current_val = open('current_{}.txt'.format(chat_id), 'r') read_value = current_val.readline() current_val.close() if n_or_p is True: a = int(read_value) + 1 else: a = int(read_value) - 1 new_val = open('current_{}.txt'.format(chat_id), 'w') new_val.write(str(a)) new_val.close() lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) url = json_data["Page {}".format(a)] print("Reading value:", a, "URL:", url) title = title_finder(url) try: json_data["Page {}".format(a - 1)] if lang == 'es': prev = "◀ Anterior" else: prev = "◀ Previous" except KeyError: prev = None try: json_data["Page {}".format(a + 1)] if lang == 'es': nxt = "Siguiente 📰" else: nxt = "Next 📰" except KeyError: nxt = None if lang == 'es': destination = "Leer más 📖" else: destination = "Read more 📖" if nxt is None: keyboard = [[ InlineKeyboardButton(prev, callback_data='prev'), InlineKeyboardButton(destination, url=url) ]] elif prev is None: keyboard = [[ InlineKeyboardButton(destination, url=url), InlineKeyboardButton(nxt, callback_data='next') ]] else: keyboard = [[ InlineKeyboardButton(prev, callback_data='prev'), InlineKeyboardButton(destination, url=url), InlineKeyboardButton(nxt, callback_data='next') ]] reply_markup = InlineKeyboardMarkup(keyboard) bot.editMessageText(chat_id=chat_id, text="*{}*\n[Link 🔗]({})".format(title, url), parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup, message_id=message_id) return "OK"
def echo(bot, update): text = update.message['text'] chat_id = update.message.chat_id get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) text_dec = unidecode(text) url_text = urlencoder(text=text) print("Received text:", text, "--Conversion--", text_dec) if db_m.is_pref(chat_id, None) == '1': print("Changing/adding values to preferences", chat_id) up.upd_pref(bot, chat_id, text) elif db_m.is_prog(chat_id, None) == '1': print("Changing/programming time", chat_id) actual = db_m.read_prog(chat_id) if actual is None: act_list = [] else: act_list = actual.split(",") if len(act_list) == 2: if lang == 'es': bot.sendMessage( chat_id=chat_id, text= "Lo sentimos, pero de momento *solo se pueden programar dos horas* 🕖 🕣\n\n_Borra alguna y prueba de nuevo_", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text= "We are sorry. Right now, you are able to *set up at most two times* 🕖 🕣\n\n_Delete one and try again_", parse_mode=telegram.ParseMode.MARKDOWN) db_m.is_prog(chat_id, False) else: time = text list_from_text = time.split(",") print(list_from_text, len(list_from_text)) if len(list_from_text) == 1 and len(act_list) == 1 or len( list_from_text) == 1 and len(act_list) == 0: print("Primera condición (len(list) == 1)") next_prog = p_updater.next_day(chat_id, list_from_text[0]) if next_prog == "Error": if lang == 'es': bot.sendMessage( chat_id, "El formato de tiempo que has utilizado no es correcto.\n\nUsa /help para saber _cómo programar correctamente el timepo_", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, "Specified time format is not correct\n\nUse /help to know _how to set up a schedule correctly_", parse_mode=telegram.ParseMode.MARKDOWN) else: print("Next programmation:", next_prog) if len(act_list) == 0: act_list.append(next_prog) print("Final programmation:", act_list[0]) db_m.update_prog(chat_id, list_from_text[0]) db_m.update_prog_time(act_list[0], chat_id) print("DB updated correctly") else: act_list.append(next_prog) print("Final programmation:", act_list[0], ",", act_list[1]) db_m.update_prog( chat_id, list_from_text[0] + "," + db_m.get_time_prog(chat_id)) db_m.update_prog_time( act_list[0] + "," + act_list[1], chat_id) print("DB updated correctly") db_m.is_prog(chat_id, False) if lang == 'es': bot.sendMessage( chat_id=chat_id, text= "Perfecto 😄\nLa siguiente programación *comenzará en las próximas 24 horas*", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text= "Perfect 😄\nNext scheduling *will start in the next 24 hours*", parse_mode=telegram.ParseMode.MARKDOWN) print("Finalizado") elif len(list_from_text) == 2: print("Segunda condición (len(list) == 2)") prog1 = p_updater.next_day(chat_id, list_from_text[0]) prog2 = p_updater.next_day(chat_id, list_from_text[1]) if prog1 == "Error" or prog2 == "Error": if lang == 'es': bot.sendMessage( chat_id, "El formato de tiempo que has utilizado no es correcto.\n\nUsa /help para saber _cómo programar correctamente el timepo_", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, "Specified time format is not correct\n\nUse /help to know _how to set up a schedule correctly_", parse_mode=telegram.ParseMode.MARKDOWN) else: programming = prog1 + "," + prog2 print("Programación final:", programming) db_m.update_prog( chat_id, list_from_text[0] + "," + list_from_text[1]) print("Primera base de datos actualizada") db_m.update_prog_time(programming, chat_id) print("Segunda base de datos actualizada") db_m.is_prog(chat_id, False) if lang == 'es': bot.sendMessage( chat_id=chat_id, text= "Perfecto 😄\nLa siguiente programación *comenzará en las próximas 24 horas*", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text= "Perfect 😄\nNext scheduling *will start in the next 24 hours*", parse_mode=telegram.ParseMode.MARKDOWN) print("Finalizado") else: print("No se ha cumplido ninguna condición") if len(act_list) > 1: if lang == 'es': bot.sendMessage( chat_id=chat_id, text= "Lo sentimos, pero de momento *solo se pueden programar dos horas* 🕖 🕣\n\n_Borra alguna y prueba de nuevo_", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id=chat_id, text= "We are sorry. Right now, you are able to *set up at most two times* 🕖 🕣\n\n_Delete one and try again_", parse_mode=telegram.ParseMode.MARKDOWN) db_m.is_prog(chat_id, False) elif lang == 'es': bot.sendMessage( chat_id, "El formato de tiempo que has utilizado no es correcto.\n\nUsa /help para saber _cómo programar correctamente el timepo_", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, "Specified time format is not correct\n\nUse /help to know _how to set up a schedule correctly_", parse_mode=telegram.ParseMode.MARKDOWN) elif db_m.is_time(chat_id, None) == '1': print("Changing/selecting time zone", chat_id) search_url = "https://maps.googleapis.com/maps/api/geocode/json?address={}&key={}".format( url_text[0], API_KEY) print("Correctly obtained URL: ", search_url) weburl = urllib.request.urlopen(search_url) data = weburl.read() encoding = weburl.info().get_content_charset('utf-8') try: obt_data = json.loads(data.decode(encoding)) print(obt_data) latitude = obt_data['results'][0]['geometry']['location'][ 'lat'] longitude = obt_data['results'][0]['geometry']['location'][ 'lng'] print("Latitude: ", latitude, " | Longitude: ", longitude) except IndexError: if lang == 'es': bot.sendMessage( chat_id=chat_id, text= "La ubicación 🛰 que nos has enviado no existe 😅" ) else: bot.sendMessage( chat_id=chat_id, text="The sent 🛰 location does not exist 😅") get_time_zone = "https://maps.googleapis.com/maps/api/timezone/json?location={},{}×tamp=1458000000&key={}".format( latitude, longitude, API_KEY_geo) print("Correctly obtained TimeZone URL: ", get_time_zone) open_zone = urllib.request.urlopen(get_time_zone) print("Correctly opened URL") data_zone = open_zone.read() print("Correctly readed URL data") # encoded_zone = data_zone.get_content_charset('utf-8') print("Omitted encoding URL-data") zone_data = json.loads(data_zone.decode('utf-8')) print("Correctly loaded JSON") zone_id = zone_data["timeZoneId"] print("Correctly obtained \"timeZoneID\": ", zone_id) db_m.update_time(chat_id, zone_id) key_tz(bot, update, chat_id) else: if path.exists("first_run_{}".format(chat_id)): if lang == 'es': bot.sendMessage( chat_id, "¡¡Hey!! Primero tienes que completar la configuración inicial" ) elif lang == 'en': bot.sendMessage( chat_id, "Hey!! First you have to finish the initial setup") else: bot.sendMessage( chat_id, "¡¡Hey!! Primero tienes que completar la configuración inicial\nHey!! First you have to finish the initial setup" ) elif lang == 'es': last_msg = db_m.read_last_msgid(chat_id) if last_msg is not None: try: bot.deleteMessage(chat_id=chat_id, message_id=last_msg) except telegram.error.BadRequest: print("No message to delete", chat_id) pass msg = bot.sendMessage( chat_id=chat_id, text= "Recopilando las últimas noticias 📰 en base a tus términos de búsqueda: _\"{}\"_" .format(text_dec), parse_mode=telegram.ParseMode.MARKDOWN) else: last_msg = db_m.read_last_msgid(chat_id) if last_msg is not None: try: bot.deleteMessage(chat_id=chat_id, message_id=last_msg) except telegram.error.BadRequest: print("No message to delete", chat_id) pass msg = bot.sendMessage( chat_id=chat_id, text= "Recovering latest news 📰 with your search terms: _\"{}\"_" .format(text_dec), parse_mode=telegram.ParseMode.MARKDOWN) mid = msg.message_id results = gsearch.search_news(query=text_dec, lang=lang) if len(results[0]) < 1: if lang == 'es': bot.editMessageText( chat_id=chat_id, text="Tu búsqueda no ha obtenido resultados â�Œ", message_id=mid) else: bot.editMessageText( chat_id=chat_id, text="Your search did not get resuls â�Œ", message_id=mid) else: db_m.last_msgid(chat_id, mid) nwk.load_keys(bot, update, chat_id, results[0], mid)
def callb_button(bot, update): query = update.callback_query chat_id = query['message']['chat']['id'] update.callback_query.answer() value = query.data msg_id = query.message.message_id get_chat_id = db_m.read_chatid(chat_id) if get_chat_id is None: bot.sendMessage(chat_id, text="*Disculpa las molestias*, pero tienes que _volver a configurar el bot_. Escribe /start o púlsalo" \ "\n\n*We are sorry*, but you have to _configure again the bot_. Type /start or press on it", parse_mode=telegram.ParseMode.MARKDOWN) else: db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) lang = db_m.read_lang(chat_id) print("\n\tSelected option:", value) if value == 'next1': key_var(bot, update, chat_id, msg_id, True) elif value == 'next': key_var(bot, update, chat_id, msg_id, True) elif value == 'prev': key_var(bot, update, chat_id, msg_id, False) elif value == 'es': db_m.write_lang(chat_id, value) bot.editMessageText( chat_id=chat_id, text= "Preferencias actualizadas correctamente. Cámbialas cuando quieras \ en /config", message_id=msg_id) elif value == 'en': db_m.write_lang(chat_id, value) bot.editMessageText( chat_id=chat_id, text="Preferences updated correctly. Change them in /config", message_id=msg_id) elif value == 'yes': if db_m.is_time(chat_id, None) == '1': if path.exists("first_run_{}".format(chat_id)): bot.deleteMessage(chat_id=chat_id, message_id=msg_id) db_m.is_time(chat_id, False) st.cont_2(bot, update, chat_id) elif lang == 'es': bot.editMessageText( chat_id=chat_id, text="Perfecto, hemos actualizado tu *zona horaria* 🌍", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Perfect, we have just updated your *time-zone* 🌍", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) db_m.is_time(chat_id, False) elif value == 'no': if db_m.is_time(chat_id, None) == '1': if lang == 'es': bot.editMessageText( chat_id=chat_id, text= "Prueba a enviar tu *ciudad y país* 🌍 o también puedes *enviar tu ubicación* 🛰", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text= "Try to send your *city and country* 🌍 or also you can send *your location* 🛰", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == "tec": key_tec(bot, update, chat_id, msg_id) elif value == "soc": key_soc(bot, update, chat_id, msg_id) elif value == "eco": key_eco(bot, update, chat_id, msg_id) elif value == "inr": key_int(bot, update, chat_id, msg_id) elif value == "dep": key_dep(bot, update, chat_id, msg_id) elif value == "cul": key_cul(bot, update, chat_id, msg_id) elif value == "finished": db_m.is_pref(chat_id, False) if lang == 'es': bot.editMessageText(chat_id=chat_id, text="Genial 😄 Ya está todo configurado. Ahora puedes:"\ "\n■ Escribir /start para *empezar a recopilar noticias*" \ "\n■ Usar /help para acceder a la *guía de uso*" \ "\n■ Editar *tus preferencias* en /config" \ "\n\n*NOTA:* accede al _menú_ pulsando la barra *[ / ]* que aparece _abajo a la derecha_", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText(chat_id=chat_id, text="It's all configured 😄 Now you can:"\ "\n■ Write /start for *fetching the latest news*"\ "\n■ Use /help for going to the *usage guide*"\ "\n■ Edit *your preferences* in /config" \ "\n\n*INFO:* access to the _menu_ using the slash *[ / ]* that is at the _bottom right_", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) os.remove("first_run_{}".format(chat_id)) elif value == 'es_1': db_m.write_lang(chat_id, "es") started.cont_1(bot, update, chat_id, msg_id) elif value == 'en_1': db_m.write_lang(chat_id, "en") started.cont_1(bot, update, chat_id, msg_id) elif value == '0': key_guide(bot, update, chat_id, msg_id, lang) elif value == '1': main_menu(bot, update, chat_id, msg_id, lang) elif value == '2': key_two(bot, update, chat_id, lang, msg_id) elif value == '3': key_three(bot, update, chat_id, lang, msg_id) elif value == '4': key_four(bot, update, chat_id, lang, msg_id) elif value == '4_2': key_four_two(bot, update, chat_id, lang, msg_id) elif value == '5': key_five(bot, update, chat_id, lang, msg_id) elif value == '6': key_six(bot, update, chat_id, lang, msg_id) elif value == 'more_info': key_more(bot, update, chat_id, msg_id, lang) elif value == 'tz': if lang == 'es': bot.editMessageText( chat_id=chat_id, text= "¿Dónde vives? También puedes mandarme *tu ubicación* 🛰", parse_mode=telegram.ParseMode.MARKDOWN, message_id=msg_id) else: bot.editMessageText( chat_id=chat_id, text= "Where are you living? Also, you can send *your location* 🛰", parse_mode=telegram.ParseMode.MARKDOWN, message_id=msg_id) db_m.is_time(chat_id, True) elif value == 'lang': key_lang(bot, update, chat_id, msg_id) elif value == 'pref': actual_pref = db_m.get_pref(chat_id) if actual_pref == '' or actual_pref is None: act_list = [] else: act_list = actual_pref.split(",") if len(act_list) == 0: if lang == 'es': comp_list = "_vacío_" else: comp_list = "_empty_" else: for a in range(0, len(act_list) - 1): lst = re.findall(r'"(.*?)(?<!\\)"', act_list[a]) if a == 0: try: comp_list = "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list = "*" + str( a + 1) + "*: " + "_" + act_list[a] + "_" + "\n" else: if act_list[a] != '': try: comp_list += "*" + str( a + 1) + "*: " + "_" + lst[0] + "_" + "\n" except IndexError: comp_list += "*" + str( a + 1) + "*: " + "_" + act_list[a] + "_" + "\n" if lang == 'es': bot.editMessageText( chat_id=chat_id, text="Tus *preferencias actualmente* son las siguientes:\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN, message_id=msg_id) bot.sendMessage( chat_id=chat_id, text= "*1.* Añade tus preferencias separándolas *por una coma* \ \n`bolsa,fuegos artificiales` \ \n*2.* 🗑 Elimínalas escribiendo *Eliminar seguid del número de la preferencia*\ \n`Eliminar 1,2`\n\ \nEscribe *Terminado* cuando hayas acabado o\ \n*Cancelar* dejarlo todo como estaba (si usas /help podrás ver la ayuda para este apartado)", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Your *actual preferences* are the following ones:\n" + comp_list + "", parse_mode=telegram.ParseMode.MARKDOWN, message_id=msg_id) bot.sendMessage( chat_id=chat_id, text= "*1.* Add your preferences *splitting them with a comma*\ \n`economy, New York weather` \ \n*2.* 🗑 Delete one typing *Delete followed by preference number*\ \n`Delete 1,2`\n\ \nWrite *Done* when you have finished or\ \n*Cancel* for doing no changes(in /help you will get personalized help for this)", parse_mode=telegram.ParseMode.MARKDOWN) db_m.is_pref(chat_id, True) elif value == 'lista': key_prefes(bot, update, chat_id, msg_id, lang) elif value == 'pref2': key_pref2(bot, update, chat_id, msg_id) elif value == 'prog': key_time_prog(bot, update, chat_id, lang, msg_id) elif value == 'First': act = db_m.get_time_prog(chat_id) real = db_m.read_prog(chat_id) l_act = act.split(",") l_real = real.split(",") out_1 = [var for var in l_act if var] out_2 = [var for var in l_real if var] val_1 = out_1[0] val_2 = out_2[0] out_1.remove(val_1) out_2.remove(val_2) final = [var for var in out_1 if var] final_2 = [var for var in out_2 if var] if not final: final = None else: final = final[0] if not final_2: final_2 = None else: final_2 = final_2[0] db_m.update_prog(chat_id, final) db_m.update_prog_time(final_2, chat_id) if lang == 'es': bot.editMessageText(chat_id=chat_id, text="Listo ✔ Se *ha borrado* la hora", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText(chat_id=chat_id, text="Done ✔ Chosen *time was deleted*", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == 'Second': act = db_m.get_time_prog(chat_id) real = db_m.read_prog(chat_id) l_act = act.split(",") l_real = real.split(",") out_1 = [var for var in l_act if var] out_2 = [var for var in l_real if var] val_1 = out_1[1] val_2 = out_2[1] out_1.remove(val_1) out_2.remove(val_2) final = [var for var in out_1 if var] final_2 = [var for var in out_2 if var] db_m.update_prog(chat_id, final[0]) db_m.update_prog_time(final_2[0], chat_id) if lang == 'es': bot.editMessageText(chat_id=chat_id, text="Listo ✔ Se *ha borrado* la hora", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText(chat_id=chat_id, text="Done ✔ Chosen *time was deleted*", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == 'All': db_m.update_prog(chat_id, None) db_m.update_prog_time(None, chat_id) if lang == 'es': bot.editMessageText(chat_id=chat_id, text="Listo ✔ Se *han borrado* las horas", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText(chat_id=chat_id, text="Done ✔ Chosen *time was deleted*", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == 'add_prog': if lang == 'es': bot.editMessageText( chat_id=chat_id, text= "Manda las horas *que quieras programar* con el siguiente formato:\ \n\n`HH:MM` ó `HH:MM lun`. *Escribe* /help *para obtener más información*", parse_mode=telegram.ParseMode.MARKDOWN, message_id=msg_id) else: bot.editMessageText( chat_id=chat_id, text="Send the *scheduling time* in this format:\ \n\n`HH:MM` or `HH:MM Mon`. *Type* /help *for getting help*", parse_mode=telegram.ParseMode.MARKDOWN, message_id=msg_id) db_m.is_prog(chat_id, True) elif value == 'del_prog': key_del_prog(bot, update, chat_id, lang, msg_id) elif value == 'max': key_max(bot, update, chat_id, msg_id) elif value == 'es': db_m.write_lang(chat_id, value) bot.editMessageText( chat_id=chat_id, text="Preferencias de idioma _actualizadas correctamente_", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == 'en': db_m.write_lang(chat_id, value) bot.editMessageText( chat_id=chat_id, text="Language preferences _updated correctly_", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == "Back": key_pref(bot, update, chat_id, msg_id) elif value == "20": db_m.update_max(int(value), chat_id) if lang == 'es': bot.editMessageText( chat_id=chat_id, text="Listo. Ahora _recibirás como máximo 20 resultados_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Done. Now you _will receive at most 20 results_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == "50": db_m.update_max(int(value), chat_id) if lang == 'es': bot.editMessageText( chat_id=chat_id, text="Listo. Ahora _recibirás como máximo 50 resultados_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Done. Now you _will receive at most 50 results_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == "75": db_m.update_max(int(value), chat_id) if lang == 'es': bot.editMessageText( chat_id=chat_id, text="Listo. Ahora _recibirás como máximo 75 resultados_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Done. Now you _will receive at most 75 results_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == "100": db_m.update_max(int(value), chat_id) if lang == 'es': bot.editMessageText( chat_id=chat_id, text= "Listo. Ahora _recibirás como máximo 100 resultados_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Done. Now you _will receive at most 100 results_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == "150": db_m.update_max(int(value), chat_id) if lang == 'es': bot.editMessageText( chat_id=chat_id, text= "Listo. Ahora _recibirás como máximo 150 resultados_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Done. Now you _will receive at most 150 results_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) elif value == "200": db_m.update_max(int(value), chat_id) if lang == 'es': bot.editMessageText( chat_id=chat_id, text= "Listo. Ahora _recibirás como máximo 200 resultados_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: bot.editMessageText( chat_id=chat_id, text="Done. Now you _will receive at most 200 results_ 😄", message_id=msg_id, parse_mode=telegram.ParseMode.MARKDOWN) else: preferences = db_m.get_pref(chat_id) if '1_' in value: if preferences is None: updated_pref = value[2:] + "," db_m.update_pref(chat_id, updated_pref) elif value[2:] in preferences: updated_pref = preferences.replace(value[2:] + ",", "") db_m.update_pref(chat_id, updated_pref) else: updated_pref = preferences + value[2:] + "," db_m.update_pref(chat_id, updated_pref) key_tec(bot, update, chat_id, msg_id) elif '2_' in value: if preferences is None: updated_pref = value[2:] + "," db_m.update_pref(chat_id, updated_pref) elif value[2:] in preferences: updated_pref = preferences.replace(value[2:] + ",", "") db_m.update_pref(chat_id, updated_pref) else: updated_pref = preferences + value[2:] + "," db_m.update_pref(chat_id, updated_pref) key_soc(bot, update, chat_id, msg_id) elif '3_' in value: if preferences is None: updated_pref = value[2:] + "," db_m.update_pref(chat_id, updated_pref) elif value[2:] in preferences: updated_pref = preferences.replace(value[2:] + ",", "") db_m.update_pref(chat_id, updated_pref) else: updated_pref = preferences + value[2:] + "," db_m.update_pref(chat_id, updated_pref) key_eco(bot, update, chat_id, msg_id) elif '4_' in value: if preferences is None: updated_pref = value[2:] + "," db_m.update_pref(chat_id, updated_pref) elif value[2:] in preferences: updated_pref = preferences.replace(value[2:] + ",", "") db_m.update_pref(chat_id, updated_pref) else: updated_pref = preferences + value[2:] + "," db_m.update_pref(chat_id, updated_pref) key_int(bot, update, chat_id, msg_id) elif '5_' in value: if preferences is None: updated_pref = value[2:] + "," db_m.update_pref(chat_id, updated_pref) elif value[2:] in preferences: updated_pref = preferences.replace(value[2:] + ",", "") db_m.update_pref(chat_id, updated_pref) else: updated_pref = preferences + value[2:] + "," db_m.update_pref(chat_id, updated_pref) key_dep(bot, update, chat_id, msg_id) elif '6_' in value: if preferences is None: updated_pref = value[2:] + "," db_m.update_pref(chat_id, updated_pref) elif value[2:] in preferences: updated_pref = preferences.replace(value[2:] + ",", "") db_m.update_pref(chat_id, updated_pref) else: updated_pref = preferences + value[2:] + "," db_m.update_pref(chat_id, updated_pref) key_cul(bot, update, chat_id, msg_id)
def update_time(bot, chat_id, text): lang = db_m.read_lang(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) currently_setup = db_m.get_time_prog(chat_id) if currently_setup is None: prog_list = [] else: prog_list = currently_setup.split(",") try: if len(prog_list) > 1: raise TabError('Only set-up two different times') time = text.split(",") days = { 0: "mon", 1: "tue", 2: "wed", 3: "thu", 4: "fri", 5: "sat", 6: "sun" } dias = { 0: "lun", 1: "mar", 2: "mie", 3: "jue", 4: "vie", 5: "sab", 6: "dom" } weekday = None other_wd = None for a in range(0, len(time)): current = time[a] for m in range(0, 6): if lang == 'en': if days.get(m) in current: if a == 0: weekday = days.get(m) num_day = m elif a == 1: other_wd = days.get(m) num_day_2 = m else: if dias.get(m) in current: if a == 0: weekday = days.get(m) num_day = m elif a == 1: other_wd = days.get(m) num_day_2 = m if len(time) > 1: try: check_time = datetime.datetime.strptime(time[0], "%H:%M") typo_1 = 0 except ValueError: try: check_time = datetime.datetime.strptime(time[0], "%I:%M%p") typo_1 = 0 except ValueError: try: check_time = datetime.datetime.strptime( time[0].replace(dias.get(num_day), days.get(num_day)), "%H:%M %a") typo_1 = 1 except ValueError: try: check_time = datetime.datetime.strptime( time[0].replace(dias.get(num_day), days.get(num_day)), "%I:%M%p %a") typo_1 = 1 except ValueError: raise TypeError('Time format is not correct') else: try: check_time_2 = datetime.datetime.strptime(time[1], "%H:%M") typo_2 = 0 except ValueError: try: check_time_2 = datetime.datetime.strptime( time[1], "%I:%M%p") typo_2 = 0 except ValueError: try: check_time_2 = datetime.datetime.strptime( time[1].replace(dias.get(num_day_2), days.get(num_day_2)), "%H:%M %a") typo_2 = 1 except ValueError: try: check_time_2 = datetime.datetime.strptime( time[1].replace(dias.get(num_day_2), days.get(num_day_2)), "%I:%M%p %a") typo_2 = 1 except ValueError: raise TypeError('Time format is not correct') else: try: check_time = datetime.datetime.strptime(time[0], "%H:%M") typo_1 = 0 except ValueError: try: check_time = datetime.datetime.strptime(time[0], "%I:%M%p") typo_1 = 0 except ValueError: try: check_time = datetime.datetime.strptime( time[0], "%H:%M {}".format(weekday)) typo_1 = 1 except ValueError: try: check_time = datetime.datetime.strptime( time[0], "%I:%M%p {}".format(weekday)) typo_1 = 1 except ValueError: raise TypeError('Time format is not correct') time_diff = db_m.get_time_diff(chat_id) if time_diff > 0 and len(time) > 1: updated_time_1 = check_time - datetime.timedelta(hours=time_diff) updated_time_2 = check_time_2 - datetime.timedelta(hours=time_diff) if weekday is not None: if '-1 day' in str(updated_time_1): weekday = days.get(num_day + 1) server_time_1 = updated_time_1.strftime( "%H:%M {}".format(weekday)) elif other_wd is not None: if '-1 day' in str(updated_time_2): other_wd = days.get(num_day_2 + 1) server_time_2 = updated_time_2.strftime( "%H:%M {}".format(other_wd)) else: server_time_1 = updated_time_1.strftime("%H:%M") server_time_2 = updated_time_2.strftime("%H:%M") elif time_diff < 0 and len(time) > 1: updated_time_1 = check_time + datetime.timedelta(hours=-time_diff) updated_time_2 = check_time_2 + datetime.timedelta( hours=-time_diff) day_compensator = updated_time_1 - check_time day_compensator_2 = updated_time_2 - check_time_2 if weekday is not None: if '-1 day' in day_compensator: weekday = days.get(num_day - 1) server_time_1 = updated_time_1.strftime( "%H:%M {}".format(weekday)) elif other_wd is not None: if '-1 day' in day_compensator_2: other_wd = days.get(num_day_2 - 1) server_time_2 = updated_time_2.strftime( "%H:%M {}".format(other_wd)) else: server_time_1 = updated_time_1.strftime("%H:%M") server_time_2 = updated_time_2.strftime("%H:%M") elif time_diff > 0 and len(time) == 1: updated_time_1 = check_time - datetime.timedelta(hours=time_diff) if weekday is not None: if '-1 day' in str(updated_time_1): weekday = days.get(num_day + 1) server_time_1 = updated_time_1.strftime( "%H:%M {}".format(weekday)) else: server_time_1 = updated_time_1.strftime("%H:%M") elif time_diff < 0 and len(time) == 1: updated_time_1 = check_time - datetime.timedelta(hours=time_diff) day_compensator = updated_time_1 - check_time if weekday is not None: if '-1 day' in day_compensator: weekday = days.get(num_day - 1) server_time_1 = updated_time_1.strftime( "%H:%M {}".format(weekday)) else: server_time_1 = updated_time_1.strftime("%H:%M") if len(time) > 1: updated_scheduler = server_time_1 + "," + server_time_2 else: updated_scheduler = server_time_1 + "," db_m.update_prog(chat_id, updated_scheduler) db_m.is_prog(chat_id, False) if lang == 'es': if len(time) > 1: bot.sendMessage( chat_id, text= "Se han programado correctamente las horas siguientes: *{} y {}*" .format(time[0], time[1]), parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, text="Se ha programado correctamente la hora siguiente: *{}*" .format(time[0]), parse_mode=telegram.ParseMode.MARKDOWN) else: if len(time) > 1: bot.sendMessage( chat_id, text= "Time was updated and scheduled correctly at these hours: *{} y {}*" .format(time[0], time[1]), parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, text= "Time was updated and scheduled correctly at this hour: *{}*" .format(time[0]), parse_mode=telegram.ParseMode.MARKDOWN) except TypeError: if lang == 'es': bot.sendMessage( chat_id, "El formato de tiempo que has especificado no es correcto. \ Por favor, envíalo así: `14:15 dom (HH:MM día)` ó `2:15PM (H:MMAM/PM)`", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage(chat_id, "The specified time format is not correct. \ Please, use this: `14:15 Mon (HH:MM day)` or `2:15PM (H:MMAM/PM)`", parse_mode=telegram.ParseMode.MARKDOWN) db_m.is_prog(chat_id, False) except TabError: if lang == 'es': bot.sendMessage( chat_id, "Solo se pueden programar dos tiempos distintos. Borra alguno y prueba de nuevo", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, "Only two different times can be scheduled. Remove someone and try again", parse_mode=telegram.ParseMode.MARKDOWN) db_m.is_prog(chat_id, False)
def start(bot, update): chat_id = update.message.chat_id user = unidecode(update.message.from_user['first_name']) print("Executing '/start' ...", chat_id) if db_m.r_w_chat_id(chat_id, user) == "Updated": print("\nFirst run", chat_id) first_boot = open("first_run_{}".format(chat_id), 'w') first_boot.close() key_lang(bot, update) elif path.exists("first_run_{}".format(chat_id)): bot.sendMessage( chat_id, "¡¡Hey!! Primero tienes que completar la configuración inicial\nHey!! First you have to finish the initial setup" ) else: lang = db_m.read_lang(chat_id) msg_id = db_m.read_last_msgid(chat_id) db_m.last_usage(chat_id, datetime.datetime.now().strftime("%H:%M %d-%m-%Y")) try: if msg_id is not None: bot.deleteMessage(chat_id=chat_id, message_id=msg_id) except telegram.error.BadRequest: print("No message found for chat_id:", chat_id) pass print("Recopilando noticias ...\n\nIdioma:", lang) url = 'https://goo.gl/60ECGQ' url2 = 'https://goo.gl/fFOI2j' act = db_m.get_pref(chat_id) if act is None or act == '': if lang == 'es': bot.sendMessage(chat_id, "Mmm... Me temo que va a ser complicado buscar algo sino sé tus preferencias\n" \ "Ejecuta /config para establecer tus gustos") else: bot.sendMessage(chat_id, "Mmm... I think it's going to be difficult looking for something if I don't " \ "know your preferences\nExecute /config for setting your pleasures") db_m.last_msgid(chat_id, None) elif lang == 'es': bot.sendMessage( chat_id, "¿Te gusta este bot?\n*Compártelo* 🗣 y *puntúalo* 🌟 [en este enlace 🔗](" + url + ") \no [👉 directamente desde aquà 👈](" + url2 + ")", parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True) msg = bot.sendMessage( chat_id, "Estamos recopilando las *últimas noticias* 📈... Por favor, espere 🕙", parse_mode=telegram.ParseMode.MARKDOWN) else: bot.sendMessage( chat_id, "Do you like this bot?\n*Share it* 🗣 & *rate it* 🌟 [using this link 🔗](" + url + ") \nor [👉 directly from here 👈](" + url2 + ")", parse_mode=telegram.ParseMode.MARKDOWN, disable_web_page_preview=True) msg = bot.sendMessage( chat_id, "We are looking for the *latest news* 📈... Please, wait 🕙", parse_mode=telegram.ParseMode.MARKDOWN) mid = msg.message_id lfn.update_news(bot, update, chat_id, mid)