Ejemplo n.º 1
0
def start_msg_text() -> str:
    try:
        text_h = StartMessage.objects.filter(hello_text=True)
        if text_h:
            return text_h.first().text.replace("\n", "<br>")
        logger_web_chat().error("Стартовое сообщение приветствия отсутствует!")
        return ''
    except Exception as ex:
        logger_web_chat().exception("Exception in start_msg_text()\n%s" % ex)
        return ''
Ejemplo n.º 2
0
def sorry_text_msg() -> str:
    """ Sorry text if wrong input. Adding to the TOP of the "Hello" text. """
    try:
        text_obj = StartMessage.objects.filter(sorry_text=True)
        if any(text_obj):
            return text_obj.first().text.replace("\n", "<br>")
        logger_web_chat().error("Сообщение об ошибке ввода отсутствует!")
        return ''
    except Exception as ex:
        logger_web_chat().exception("Exception in sorry_text_msg()\n%s" % ex)
        return ''
Ejemplo n.º 3
0
def find_web_user(_ip: str) -> (bool, int):
    """ If user has ever used HelpBot -> find chat_id id DB and get user last position.
    Else set user_position = 0. """
    try:
        for w in ChatPositionWeb.objects.all():
            if w.ip_address == _ip:
                return True, w.position
        save_web_user(_ip, 0, False)
        return True, 0
    except Exception as ex:
        logger_web_chat().exception("Exception in find_web_user()\n%s" % ex)
        return False, 0
Ejemplo n.º 4
0
def additional_start_btn():
    try:
        active_buttons = EditionButtons.objects.filter(btn_active=True,
                                                       btn_position_start=True)
        if any(active_buttons):
            return active_buttons.first().btn_name
        else:
            return None
    except Exception as ex:
        logger_web_chat().exception(
            "Exception in additional_start_btn() - Start button NOT set!\n%s" %
            ex)
        return None
Ejemplo n.º 5
0
def help_type_text_msg() -> str:
    """ костыль, чтобы сообщение приветствия не повторялось при возврате к стартовым вопросам.
        "help_type" - название специального сообщения в разделе "Стартовое сообщение бота".
    """
    try:
        text_obj = StartMessage.objects.filter(name='help_type')
        if text_obj:
            return text_obj.first().text
        logger_web_chat().error(
            "Альтернативное сообщение при возврате к стартовым вопросам отсутствует!"
        )
        return ''
    except Exception as ex:
        logger_web_chat().exception("Exception in help_type_text_msg()\n%s" %
                                    ex)
        return ''
Ejemplo n.º 6
0
def user_has_position(_ip: str, _user_position: int, _massage: str) -> str:
    """ user used HelpBot and have last saved position """
    root = NeedHelp.objects.get(id=_user_position)
    child = root.get_children()
    if child:
        """ normal tree branch """
        for c in child:
            if _massage == c.user_input:
                if c.link_to:
                    """ If this button has a link to the other help option. Select_list in the Admin menu. """
                    user_position = c.link_to.id
                    new_child = NeedHelp.objects.get(
                        id=user_position).get_children()
                    if not new_child:
                        new_child = NeedHelp.objects.get(
                            is_default=True).get_children()
                elif c.go_back:
                    """ Back to the main questions. Check_box in the Admin menu. """
                    save_web_user(_ip, 0, True)
                    return start_chat(help_type=True)
                elif c.go_default:
                    """ if user clicked last element of the Tree - go to default branch. """
                    user_position = c.id
                    try:
                        new_child = NeedHelp.objects.get(
                            is_default=True).get_children()
                    except Exception as ex:
                        logger_web_chat().exception(
                            "Chat Tree DO NOT have element with is_default=True!\n%s"
                            % ex)
                        return random_input(_ip, True, sorry=True)
                else:  # How to speed up: add new field -> normal_element = models.BooleanField,
                    """ Normal buttons in the chat. Go deeper. """  # but it'l be to hard for Admin ?!
                    user_position = c.id
                    new_child = c.get_children()

                save_web_user(_ip, user_position, True)
                return buttons_and_text(new_child, user_position)
        """ button text not in the list. """
        return random_input(_ip, True, sorry=True)

    elif root.go_default:
        """ if user at the last element of the Tree - go to default branch. """
        return go_default_branch(_ip, _massage)

    return random_input(_ip, True, sorry=True)
Ejemplo n.º 7
0
def go_default_branch(_ip: str, _massage: str) -> str:
    """ is_default=True - hidden root node for a default output that repeats at last tree elements. """
    try:
        new_root = NeedHelp.objects.get(is_default=True)
    except Exception as ex:
        logger_web_chat().exception(
            "Chat Tree DO NOT have element with is_default=True!\n%s" % ex)
        return random_input(_ip, True, sorry=True)
    else:
        new_child = new_root.get_children()
        for c in new_child:
            if _massage == c.user_input:
                if c.go_back:
                    """ Back to the main questions. Check_box in the Admin menu. """
                    save_web_user(_ip, 0, True)
                    return start_chat(help_type=True)
                else:
                    return user_has_position(_ip, new_root.id, _massage)
        return random_input(_ip, True, sorry=True)
Ejemplo n.º 8
0
def chat_req_get(request) -> str:
    """ Web chat bot main logic. """
    if any(request.GET.values()):
        ui = request.GET['us_in'].strip()
        ip = get_client_ip(request)
        user, user_position = find_web_user(ip)

        if check_input(ui):
            if user and not user_position:
                """ user came from a start questions """
                return user_from_start_q(ui, ip)

            elif user_position:
                """ user used HelpBot and have last saved position """
                return user_has_position(ip, user_position, ui)
        else:
            """ random input from a user """
            return random_input(ip, user, sorry=True)
    else:
        """ Chat page load. """
        logger_web_chat().info("request.GET is empty.")
        return start_chat()
Ejemplo n.º 9
0
def buttons_and_text(_child, _user_position: int) -> str:
    """ Avery Tree Field in the Admin menu has 'User input' option.
    'User input' = text buttons, that must be send to the chat. """
    # btn_text = [i.user_input for i in _child]
    btn_text_list = []

    normal_chat_buttons = [i.user_input for i in _child]

    start_btn = additional_start_btn()
    if start_btn and start_btn not in normal_chat_buttons:
        btn_text_list.extend([start_btn])

    btn_text_list.extend(normal_chat_buttons)

    text_sum = ''
    for t in HelpText.objects.filter(relation_to=_user_position):
        if t:
            try:
                text_sum += t.text.replace("\n", "<br>")
                text_sum += "<br>"
                if t.geo_link_name and t.address:
                    text_sum += get_geo_link_web(t.geo_link_name, t.address,
                                                 t.latitude, t.longitude)
            except Exception as ex:
                logger_web_chat().exception(
                    "Exception in buttons_and_text():\n%s" % ex)
                continue
        else:
            continue

    json_data = json.dumps({
        'btn_text': btn_text_list,
        "help_text": text_sum
    },
                           ensure_ascii=False)
    return json_data