Пример #1
0
def followers_count(data  # type: list[dict]
                    ):

    # PRE: Obtiene la data
    # POST: Accede a la cantidad de seguidores, y la imprime
    text = ('''
        Bien, entonces la cantidad de seguidores que tenes es: {}.
        Sos famosito eh!
        '''.format(data["followers_count"]))

    print(text)
    chat_logger.info(text)
Пример #2
0
def fb_error_checking_profile_photo(data  # type: dict
                                    ):

    # PRE: Recibe data de foto de perfil.

    # POST: Chequea si hay error, si lo
    # hay, printea y devuelve True, sino
    # False.

    if data["error"].result["error"]["code"] == 100:
        return False

    else:
        print("Ha ocurrido un error inesperado.")
        chat_logger.info("[Crux]: Ha ocurrido un error inesperado")

        return True
Пример #3
0
def request_input(
        bot,  # type: ChatBot
        statement  # type: str
):

    # PRE: 'bot', debe ser una variable de tipo ChatBot
    #      'statement', debe ser una variable de tipo str
    # POST: Devuelve un string que representa una petición hecha por
    #       el usuario. Dicha petición se parsea a minúsculas

    response = bot.get_response(statement)
    chat_logger.info(f"[{bot.name}]: {response}")

    request = input(f"\n[{bot.name}]: {response}\n")
    chat_logger.info(f"[Usuario]: {request}")

    return request.lower()
Пример #4
0
def print_error(
        bot,  # type: ChatBot
        key_error,  # type: str 
        data  # type: dict
):

    # PRE: 'bot', debe ser una variable de tipo ChatBot
    #      'key_error', debe ser una variable de tipo str
    #      'data', debe ser una variable de tipo dict
    # POST: Imprime el error almacenado en data, accediendo
    #       al mismo, mediante la key key_error

    print_response(bot, "msgerrorconn")
    print(
        f"[{bot.name}]: {key_error.capitalize()}  :  {data.get(key_error).message}\n"
    )

    chat_logger.info(
        f"[{bot.name}]: {key_error.capitalize()}  :  {data.get(key_error).message}"
    )
Пример #5
0
def fb_error_checking(data  # type: dict
                      ):

    # PRE: Recibe data de todo tipo
    # de acciones.

    # POST: Chequea si hay error, si lo
    # hay, lo printea y devuelve True, sino
    # False.

    if "error" in data:
        text = "Un error ha ocurrido: {error}".format(error=data["error"])

        print(text)
        chat_logger.info(text)

        return True

    else:
        return False
Пример #6
0
def print_response(
        bot,  # type: ChatBot
        statement  # type: str
):

    # PRE: 'bot', debe ser una variable de tipo ChatBot
    #      'statement', debe ser una variable de tipo str
    # POST: Imprime la respuesta que se recibe por parte del bot,
    #       en función del statement

    request = ""

    response = bot.get_response(statement)

    while response.confidence < MIN_CONFIDENCE:
        request = request_input(bot, "msgforconfidence")

        response = bot.get_response(request)

    print(f"[{bot.name}]: {response}\n")

    chat_logger.info(f"[{bot.name}]: {response}")
Пример #7
0
def print_data(
        bot,  # type: ChatBot
        data,  # type: list[dict]
        function_name  # type: str
):

    # PRE: 'bot', debe ser una variable de tipo ChatBot
    #      'data', debe ser una variable de tipo dict
    #      'function_name', debe ser una variable de tipo str
    # POST: Imprime el error que ocurrió, al hacer la petición a la API
    #       de Facebook, de lo contrario, de acuerdo a que función llame
    #       a ésta, imprimirá la información/respuesta que se recibió de
    #       Facebook

    key_error = "error"

    if (function_name == search_user_by_bot.__name__
            or function_name == get_followers_by_bot.__name__):

        for x in range(len(data)):

            if key_error in data[x]:
                print_error(bot, key_error, data[x])

            else:
                for key in data[x]:
                    print(
                        f"[{bot.name}]: {format_key(key)}  :  {data[x].get(key)}"
                    )

                    chat_logger.info(
                        f"[{bot.name}]: {format_key(key)}  :  {data[x].get(key)}"
                    )

    elif function_name == get_medias_by_bot.__name__:

        for x in range(len(data)):

            if key_error in data[x]:
                print_error(bot, key_error, data[x])

            else:
                del data[x]["id"]
                data[x]["fecha_y_hora_de_publicacion"] = format_date(
                    data[x].get("fecha_y_hora_de_publicacion"))

                print(f"\n[{bot.name}]: {x + 1}° - publicación")

                chat_logger.info(f"[{bot.name}]: {x + 1}° - publicación")

                for key in data[x]:
                    print(
                        f"[{bot.name}]: {format_key(key)}  :  {data[x].get(key)}"
                    )

                    chat_logger.info(
                        f"[{bot.name}]: {format_key(key)}  :  {data[x].get(key)}"
                    )

    elif function_name == post_ig_photo_by_bot.__name__:

        for x in range(len(data)):

            if key_error in data[x]:
                print_error(bot, key_error, data[x])

            else:
                print_response(bot, "msgpostedphoto")

    elif function_name == update_media_by_bot.__name__:

        for x in range(len(data)):

            if key_error in data[x]:
                print_error(bot, key_error, data[x])

            else:
                if (data[x].get("success")):
                    print_response(bot, "msgcommenabledsucc")
                else:
                    print_response(bot, "msgcommenablednotsucc")

    elif function_name == bot_shows_posts.__name__:

        for posts in range(len(data)):

            for key in data[posts]:

                if key == "message":
                    print(f"Post {posts + 1}: {data[posts]['message']}\n")
                    chat_logger.info(
                        "[Crux]: Post {post_number} - {post_message}".format(
                            post_number=posts + 1,
                            post_message=data[posts]['message']))

                elif key == "picture":
                    print(f"Post {posts + 1}: This post is a photo.")
                    chat_logger.info(
                        "[Crux]: Post {post_number} - {post_message}".format(
                            post_number=posts + 1,
                            post_message="This post is a photo."))

    elif function_name == bot_shows_conversations.__name__:

        for snippet in range(len(data)):

            print('''
                [Crux]:
                Follower: {follower}
                Last message: {last_message}
                Conversation: {snippet}
                '''.format(
                follower=data[snippet]["participants"]["data"][0]["name"],
                last_message=data[snippet]["snippet"],
                snippet=snippet + 1))

            chat_logger.info(
                "[Crux]: Follower: {follower} | Last message: {last_message} | Conversation: {snippet}"
                .format(
                    follower=data[snippet]["participants"]["data"][0]["name"],
                    last_message=data[snippet]["snippet"],
                    snippet=snippet + 1))

    elif function_name == bot_shows_convers_msg.__name__:

        for message in range(len(data)):
            print('''
                [Crux]:
                Sender: {sender}
                Message: {message}
                '''.format(sender=data[message]["from"]["name"],
                           message=data[message]["message"]))

            chat_logger.info(
                "[Crux]: Sender: {sender} | Message: {message}".format(
                    sender=data[message]["from"]["name"],
                    message=data[message]["message"]))
Пример #8
0
def init_main_options(
        request,  # type: str
        bot,  # type: ChatBot
        api,  # type: Api
        igproapi,  # type: IgProApi
        graphapi  # type: GraphAPI
):

    # PRE: 'request', debe ser una variable de tipo str
    #      'bot', debe ser una variable de tipo ChatBot
    #      'api', debe ser una variable de tipo Api
    #      'igproapi', debe ser una variable de tipo IgProApi
    #      'graphapi', debe ser una variable de tipo GraphAPI
    # POST: Retorna un string, que representa una petición
    #       solicitada por el usuario

    response = ""
    image_url = ""
    posts_list = []
    post_id = 0

    comment_enabled = False

    if "bienvenida" in request:
        print_response(bot, request)

        request = request_input(bot, "continuar")

    elif "opciones" in request:
        request = request_input(bot, request)

        flag_is_valid = False

        while not flag_is_valid:

            if request in OPTIONS_FOR_FACEBOOK:
                for x in range(9):
                    response = bot.get_response(f"fbopt{x}")
                    print(f"[{bot.name}]: {response}")

                    chat_logger.info(f"[{bot.name}]: {response}")

                request = request_input(bot, "msgreqopt")
                response = bot.get_response(request)

                while (response.confidence < MIN_CONFIDENCE
                       or not are_keywords_in_text(response.text.lower(),
                                                   KEYWORDS)
                       or "habilitar" in response.text.lower()):

                    request = request_input(bot, "msgforconfidence")
                    response = bot.get_response(request)

                print(f"[{bot.name}]: {response}\n")

                chat_logger.info(f"[{bot.name}]: {response}")

                if "likear" in request and "likear" in response.text.lower():
                    bot_likes_posts(api, bot)

                elif "publicaciones" in request and "publicaciones" in response.text.lower(
                ):
                    bot_shows_posts(api, bot)

                elif "postear" in request and "postear" in response.text.lower(
                ):
                    bot_post_publication(api, bot)

                elif "foto" in request and "foto" in response.text.lower():
                    bot_uploads_feed_photo(graphapi, bot)

                elif "actualizar" in request and "actualizar" in response.text.lower(
                ):
                    bot_put_publication(api, bot)

                elif "seguidores" in request and "seguidores" in response.text.lower(
                ):
                    information_followers(api, bot)

                elif "perfil" in request and "perfil" in response.text.lower():
                    bot_uploads_profile_photo(graphapi, bot)

                elif "conversaciones" in request and "conversaciones" in response.text.lower(
                ):
                    bot_shows_convers_msg(api, bot)

                elif "comentar" in request and "comentar" in response.text.lower(
                ):
                    bot_comments_posts(api, bot)

                flag_is_valid = True

            elif request in OPTIONS_FOR_INSTAGRAM:
                for x in range(5):
                    response = bot.get_response(f"igopt{x}")
                    print(f"[{bot.name}]: {response}")

                    chat_logger.info(f"[{bot.name}]: {response}")

                request = request_input(bot, "msgreqopt")
                response = bot.get_response(request)

                while response.confidence < MIN_CONFIDENCE or not are_keywords_in_text(
                        response.text.lower(), KEYWORDS):
                    request = request_input(bot, "msgforconfidence")
                    response = bot.get_response(request)

                print(f"[{bot.name}]: {response}\n")

                chat_logger.info(f"[{bot.name}]: {response}")

                if "buscar" in request and "buscar" in response.text.lower():
                    username = request_input(bot, "msgrequsername")

                    search_user_by_bot(bot, igproapi, username)

                elif "publicaciones" in request and "publicaciones" in response.text.lower(
                ):
                    username = IG_USERNAME

                    print_response(bot, "msgreqposts")
                    get_medias_by_bot(bot, igproapi, username)

                elif "foto" in request and "foto" in response.text.lower():

                    image_url = validate_url(bot)
                    post_ig_photo_by_bot(bot, graphapi, image_url)

                elif "actualizar" in request and "habilitar" in response.text.lower(
                ):
                    username = IG_USERNAME

                    posts_list = get_medias_by_bot(bot, igproapi, username)

                    post_id = validate_number_in_range(bot, posts_list)

                    request = validate_enable_disable(bot)

                    if request in KEYWORDS_ENABLE:
                        comment_enabled = True
                    elif request in KEYWORDS_DISABLE:
                        comment_enabled = False

                    update_media_by_bot(bot, igproapi,
                                        posts_list[post_id].get("id"),
                                        comment_enabled)

                elif "seguidores" in request and "seguidores" in response.text.lower(
                ):
                    username = IG_USERNAME

                    print_response(bot, "msgfollowersok")
                    get_followers_by_bot(bot, igproapi, username)

                flag_is_valid = True

            else:
                request = request_input(bot, "msgnotfborig")

        request = request_input(bot, "continuar")

    else:
        request = request_input(bot, "msgnotvalidopt")

    return request