예제 #1
0
def cmd_planifier(msg):
    '''
    Commande pour la planification d’un message récuurrent.
    Utilise le context pour la réponse. Ex :

    - Vous: /planifier
    - Lui : À qu’elle heure ?
    - Vous : 10h
    - Lui : Trés bien … planification de « commande » à 10h

    ou :

    - Vous /planifier 10h
    - Lui : Trés bien … planification de « commande » à 10h
    '''
    previous_text = get_last_message(msg)
    if previous_text and "planifier" not in previous_text:
        heure, minute = extract_hours_minutes(msg["query"])
        if heure:
            task = Task(username_or_channel(msg),
                        "{0}:{1}".format(heure, minute), previous_text)
            db_session.add(task)
            db_session.commit()
            return "Parfait ! Vous allez recevoir automatiquement « {0} » tous les jours à {1}h{2}".format(
                previous_text, heure, minute)
        else:
            mark_for_awaiting_response(username_or_channel(msg), "planifier")
            return "À qu’elle heure voulez vous planifier l’envoi automatique de « {0} » ?".format(
                previous_text)
    else:
        return "Désolé, je ne peu pas planifier autre chose qu’une commande."
예제 #2
0
def cmd_start(msg):
    if "telegram" in msg:  # pragma: no cover
        save_new_user(username_or_channel(msg), msg["telegram"]["update"].message.chat.id)
        reply_to_user(msg, "Bonjour, Je suis Laurence. Pour avoir la liste des commandes tapez /aide")
        return True
    else:
        return False
예제 #3
0
def cmd_quizzreponse(msg):
    mark_for_awaiting_response(username_or_channel(msg), "r")
    username = get_username(msg)

    reponse = msg["query"]

    if reponse.strip().lower() == quizz.quizz_reponse.strip().lower():
        try:
            score = quizz.quizz_tabscore[username]
            quizz.quizz_tabscore[username] = score + 1
        except:
            quizz.quizz_tabscore[username] = 1

        return 'Bravo! Bonne reponse {0} \r\nQuestion suivante : \r\n {1}'.format(
            username, get_question())
    else:
        # Test si la reponse s'approche
        if difflib.SequenceMatcher(None,
                                   quizz.quizz_reponse.strip().lower(),
                                   reponse.strip().lower()).ratio() > 0.7:
            return 'Ah {0} pas loin!'.format(username)
        else:
            # Si ce n'est pas la bonne reponse et que la reponse est eloigne
            if random.randint(0, 20) == 10:  # pragma: no cover
                # tous les quelques messages on diffuse soit un indice, soit la question
                if random.choice(['indice', 'question']) == "indice":
                    return say_indice()
                else:
                    return quizz.quizz_question
            else:
                return ""
예제 #4
0
def get_last_message(msg):
    # Récupération du dernier message dans l’historique. (Utilisé pour le context)
    try:
        pseudo = username_or_channel(msg)
        remove_last_history(pseudo)
        return Historique.query.filter_by(username=pseudo).order_by(
            Historique.datetime.desc()).limit(1).one().text
    except:  # pragma: no cover
        return ""
예제 #5
0
def analyze_text(bot, update, do_google_search=False):
    text = demojize(update.message.text)

    # Analyse du texte en mode POS TAGGER
    blob = tb(text)
    text_keywords = [(x[0].lower(), x[1]) for x in blob.tags]

    # Création de l’objet qui gère un peu tout
    attrs = make_attrs_from_telegram(update, bot, {})
    username = username_or_channel(attrs)

    save_last_tags(username, text_keywords)

    closest = find_closest(text_keywords)
    send_message_debug_users(bot, closest)

    # On regarde si dans le context actuel on a un message en attente
    awaiting_command = get_awaiting_response(username)
    context_data = {}
    if awaiting_command:
        # Il y avait une commande en attente alors on append celle-ci pour une l’executer
        update.message.text = "/{0} {1}".format(awaiting_command["commande"], update.message.text)
        context_data = awaiting_command["data"]
    elif closest:
        update.message.text = closest[0][1]
    elif do_google_search:
        # Rien ne match alors on fallback en mode « Recherche Google »
        update.message.text = "/google {0}".format(update.message.text)

    # Une fois les traitements sur le texte éffectué, on remet en place les infos pour la suite
    args = update.message.text.split(' ')
    text = demojize(update.message.text)

    if ":cry" in text or ":thumbs_down_sign:" in text:
        update.message.reply_text(emojize("Oh :pensive_face: Un soucis ?"))
        update.message.text = "/giphy"
        args = ["giphy", "cute"]
    elif ":zzz:" in text or ":sleep" in text:
        update.message.text = "/gif"
        args = []
    elif "kiss:" in text:
        update.message.text = "/echo"
        args = ["echo", ":kiss:"]
    elif ":poop:" in text or ":shit:" in text:
        update.message.text = "/echo"
        args = ["echo", "Jolie :poop: !"]
    elif ":thumbs_up_sign:" in text:
        update.message.text = "/echo"
        args = ["echo", ":thumbs_up_sign:"]
    elif "_heart" in text:
        update.message.text = "/echo"
        args = ["echo", ":face_throwing_a_kiss:"]

    return make_attrs_from_telegram(update, bot, args[1:])
예제 #6
0
def cmd_do_proche(msg):
    if is_telegram(msg) and msg["telegram"][
            "update"].message.location:  # pragma: no cover
        user_location = msg["telegram"]["update"].message.location
        return search_arround_me("{0}, {1}".format(user_location.latitude,
                                                   user_location.longitude))
    elif msg["query"] != "":
        return search_arround_me(msg["query"])
    else:  # pragma: no cover
        mark_for_awaiting_response(username_or_channel(msg), "proche")
        return "Pour utiliser la recherche proche merci de m’indiquer une position GPS. Ex: 48.802,2.025"
예제 #7
0
def cmd_quizzscore(msg):
    mark_for_awaiting_response(username_or_channel(msg), "r")
    string_score = ""
    for user in quizz.quizz_tabscore:
        string_score = string_score + " \r\n " + str(user) + " : " + str(
            quizz.quizz_tabscore[user])

    if string_score:
        return "Score : {0}".format(string_score)
    else:
        return "Aucun historique de quizz."
예제 #8
0
def cmd_planning(msg):
    tasks = Task.query.filter_by(username=username_or_channel(msg)).all()
    if tasks:
        retour = "Voici la liste des commandes planifiés : \n"
        for task in tasks:
            retour = "{0} - « {1} » tous les jours à {2}\n".format(
                retour, task.commande, task.planned_time)
    else:
        retour = "Aucune commande planifiés."

    return retour
예제 #9
0
def cmd_do_googlesearch(msg):
    try:
        if msg["query"]:
            for url in search(msg["query"], tld='fr', lang='fr', num=1,
                              stop=1):
                return "Voici le premier résultat \n {0}".format(url)
        else:
            mark_for_awaiting_response(username_or_channel(msg), "google")
            return "Oui ? Que recherchez vous ?"
    except Exception as e:  # pragma: no cover
        return "Recherche impossible."
예제 #10
0
def cmd_aide(msg):
    """
    Cherche la définition demandé par l’utilisateur
    :param msg: Objet qui correspond à la demande de l’utilisateur.
    """

    if not msg["query"]:
        mark_for_awaiting_response(username_or_channel(msg), "def")
        return "Sur quel sujet ?"

    try:
        wikipedia.set_lang("fr")
        query = wikipedia.search(msg["query"],
                                 results=1).pop(0).replace(" ", "_")

        # En français la lib wikipedia ne fonctionne pas vraiment bien (exemple valentin est impossible à charger…)
        if query:
            params = {
                "format": "json",
                "action": "query",
                "prop": "extracts",
                "exintro": "",
                "explaintext": "",
                "titles": query
            }
            domain = "fr.wikipedia.org"
            retour = callrest(domain=domain,
                              port="443",
                              ssl=True,
                              params=params,
                              path="/w/api.php",
                              user_headers={"Accept-Charset": "utf-8"})
            retour = json.loads(retour[2])
            page_id = list(retour["query"]["pages"]).pop(0)
            if page_id != "-1":
                page = retour["query"]["pages"][page_id]
                return "{0} \n\nhttps://{1}/?curid={2}".format(
                    page.get("extract", ""), domain, page_id)
            else:
                raise Exception("KO")
    except Exception as e:  # pragma: no cover
        if msg["query"]:
            return "Aucun résultat pour {0}".format(msg["query"])
예제 #11
0
def has_msg(msg):
    if not msg["query"]:
        mark_for_awaiting_response(username_or_channel(msg), "giphy")
        return False, "Pour quel mot clef ?"
    else:
        return True, msg["query"]
예제 #12
0
def cmd_indice(msg):
    mark_for_awaiting_response(username_or_channel(msg), "r")
    return say_indice()
예제 #13
0
def cmd_quizzstart(msg):
    mark_for_awaiting_response(username_or_channel(msg), "r")
    return get_question()