コード例 #1
0
ファイル: help.py プロジェクト: thawornwit/NewsBot
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)
コード例 #2
0
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)
コード例 #3
0
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)
コード例 #4
0
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={},{}&timestamp=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)
コード例 #5
0
ファイル: start_handler.py プロジェクト: thawornwit/NewsBot
def cont_2(bot, update, chat_id):
    db_m.last_usage(chat_id,
                    datetime.datetime.now().strftime("%H:%M %d-%m-%Y"))
    db_m.is_pref(chat_id, True)
    key_pref(bot, update, chat_id, None)