Example #1
0
def listen(viber):

    sock = socket.socket()
    sock.bind(('172.31.53.92', 9090))
    sock.listen(1)
    conn, addr = sock.accept()

    print('connected:', addr)
    try:
        while True:
            data = conn.recv(1024).decode()
            jsonData = json.loads(data)
            print(jsonData)
            if jsonData['wparname'] != 'none':
                print("trueeee")
                #+str(jsonData['action'])
                if jsonData['action'] == 'start':
                    viber.send_messages(jsonData['user_id'], [
                        TextMessage(text=str(jsonData['wparname']) +
                                    " успішно запущено (checkmark)"),
                        KeyboardMessage(keyboard=buttons.student_account)
                    ])
                elif jsonData['action'] == 'stop':
                    viber.send_messages(jsonData['user_id'], [
                        TextMessage(text=str(jsonData['wparname']) +
                                    " успішно зупинено (checkmark)"),
                        KeyboardMessage(keyboard=buttons.student_account)
                    ])
            #global wparData
            #if wparData!="none":
            #print(wparQueue.qsize())
            if wparQueue.qsize() > 0:
                wparEntity = wparQueue.get()
                print(wparEntity["wparname"])
                sendingData = {
                    'wparname': wparEntity['wparname'],
                    'action': wparEntity['action'],
                    'user_id': wparEntity['user_id']
                }
                conn.send(json.dumps(sendingData).encode())
            else:
                sendingData = {
                    'wparname': 'none',
                    'action': 'none',
                    'user_id': 'none'
                }
                conn.send(json.dumps(sendingData).encode())
            #print(wparData)
            #if wparData.qsize() == 0:
            #    wparData.put("none")
            #    print("none")
            #print(wparData)
            time.sleep(2)
    except Exception as e:
        conn.close()
        print("Server error:", e)
Example #2
0
 def back_to_menu(db,quer,viber,delete_zakaz=True):
     quer.query_number = 'm2'
     if delete_zakaz:
         usr = User.query.filter_by(user_viber_id=viber_request.sender.id ).first()
         num = int(quer.zakaz_num)-1
         if Zakaz.query.filter_by(user=usr).all():
             for i in range(num+1):
                 zkz = Zakaz.query.filter_by(user=usr).all()[0]
                 db.session.delete(zkz)
         quer.zakaz_num = 1
     db.session.commit()
     with open('./bot/buttons_conf/1menu_button.json') as f:
          button = json.load(f)
     viber.send_messages(viber_request.sender.id , [
          TextMessage(None,None,'Здравствуйте, я помощник Юлии - вашего поставщика. Чем я могу вам помочь?'),
          KeyboardMessage(keyboard = button),
             ])
     return Response(status=200)
Example #3
0
File: lr4.py Project: Mtchl8/isrpo
def ask_a_question(test, id):
    current_test = test
    new_question_key = current_test.load_question(eng_words)
    answers = current_test.questions[new_question_key].translations
    answers.append(current_test.questions[new_question_key].correct_answer)
    current_test.current_word = current_test.questions[
        new_question_key].correct_answer
    random.shuffle(answers)
    for i in range(4):
        answer_keyboard['Buttons'][i]['Text'] = answers[i]
        answer_keyboard['Buttons'][i]['ActionBody'] = answers[i]

    keyboard = answer_keyboard
    viber.send_messages(id, [
        TextMessage(text="Как переводится с английского слово '" +
                    current_test.questions[new_question_key].word + "'?"),
        KeyboardMessage(keyboard=keyboard)
    ])
Example #4
0
def faq_options(viber, viber_request, condition):
    print("faq", condition)
    if re.match(r'(?i)(^завдання.*)|(.*(лаб).*(роб).*)', condition):
        viber.send_messages(viber_request.sender.id, [
            RichMediaMessage(rich_media=buttons.carousel_contentFirstLabs,
                             min_api_version=2,
                             alt_text="Обери потрібну лабораторну роботу"),
            RichMediaMessage(rich_media=buttons.carousel_contentSecondLabs,
                             min_api_version=2,
                             alt_text="Обери потрібну лабораторну роботу"),
            KeyboardMessage(keyboard=buttons.faq_keyboard)
        ])

    elif re.match(r'(?i).*(розклад).*', condition):
        viber.send_messages(viber_request.sender.id, [
            TextMessage(text=texts.schedule),
            KeyboardMessage(keyboard=buttons.faq_keyboard)
        ])
    elif re.match(r'(?i).*((вимоги)|(звіт)).*', condition):
        viber.send_messages(viber_request.sender.id, [
            TextMessage(text=texts.requirements),
            KeyboardMessage(keyboard=buttons.faq_keyboard)
        ])
    elif re.match(r'(?i)(.*цікав.*факт.*)', condition):
        viber.send_messages(viber_request.sender.id, [
            TextMessage(text=choice(texts.interesting_facts)),
            KeyboardMessage(keyboard=buttons.faq_keyboard)
        ])
    elif re.match(r'(?i).*((ssh.*)|(з wpar)).*', condition):
        viber.send_messages(viber_request.sender.id, [
            TextMessage(text=texts.connect_ssh),
            URLMessage(
                media=
                "https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html"
            ),
            KeyboardMessage(keyboard=buttons.faq_keyboard)
        ])
    elif condition == "До головного меню":
        #keyboard = KeyboardMessage(tracking_data='tracking_data', keyboard=buttons.main_menu())
        viber.send_messages(viber_request.sender.id, [
            TextMessage(text="Чим я можу тобі допомогти? (eyes)"),
            KeyboardMessage(keyboard=buttons.main_keyboard)
        ])
    else:
        dialog.main(viber, viber_request, condition)
Example #5
0
def incoming():
    try:
        global switch

        if switch:
            switch = False
            threadServer.start()

        global switchTrue
        if switchTrue:
            switchTrue = False
            threadSpacex.start()
        logger.info("received request. post data: {0}".format(
            request.get_data()))
        # every viber message is signed, you can verify the signature using this method
        if not viber.verify_signature(
                request.get_data(),
                request.headers.get('X-Viber-Content-Signature')):
            logger.error("Signature not valid. Response code 403.")
            return Response(status=403)

        # this library supplies a simple way to receive a request object
        viber_request = viber.parse_request(request.get_data())

        if isinstance(viber_request, ViberMessageRequest):
            logger.info('Received message from user',
                        {"meta": {
                            "messagetype": "message"
                        }})
            #print(viber_request.message.text)
            #viber.send_messages(viber_request.sender.id, [TextMessage(text=viber_request.message.text),
            #                                           KeyboardMessage(keyboard=buttons.main_keyboard)])
            #print(viber_request.sender.id)
            usermessage = viber_request.message.text
            if not re.match(r'(.*@.*)|(.*\d.*)|(.*FAQ.*)', usermessage):
                usermessage = ibm_translator.translate(
                    viber_request.message.text)
            print(usermessage)
            main_menu.main_options(viber, viber_request, userrole,
                                   securityCode, usermessage)
        elif isinstance(viber_request, ViberSubscribedRequest):
            print(viber_request.user.id)

            pictureMinion = PictureMessage(
                media="https://aixbot.s3.amazonaws.com/stickerWelcome.jpg",
                text=texts.welcome)
            viber.send_messages(viber_request.user.id, [
                pictureMinion,
                TextMessage(text=texts.hint),
                KeyboardMessage(keyboard=buttons.main_keyboard)
            ])
            #-user_data = Api.get_user_details(viber, viber_request.user.id)
            #-print(user_data)
            #db2_database.add_user(user_data["id"], user_data["name"], user_data["avatar"], user_data["country"], user_data["language"],
            #                    user_data["primary_device_os"], user_data["api_version"], user_data["viber_version"], user_data["mcc"],
            #                  user_data["mnc"], user_data["device_type"])
            logger.info('User {0} subscribed.'.format(viber_request.user.id),
                        {"meta": {
                            "useraction": "subscribed"
                        }})
        elif isinstance(viber_request, ViberConversationStartedRequest):
            #Когда пользователь не подписался еще на чат-бот и просто в первый раз открыл чат-бот (сообщение приветсвие)
            if (viber_request.context == 'siri'):
                viber.send_messages(viber_request.user.id, [
                    TextMessage(text=texts.siri_message),
                    KeyboardMessage(keyboard=buttons.main_keyboard)
                ])
            else:
                viber.send_messages(viber_request.user.id,
                                    [TextMessage(text=texts.hello_message)])
        elif isinstance(viber_request, ViberUnsubscribedRequest):
            userId = viber_request.user_id
            logger.info('User {0} unsubscribed.'.format(userId),
                        {"meta": {
                            "useraction": "unsubscribed"
                        }})
            #-db2_database.delete_user(userId)
        #    print(viber_request)
        #    print("hellp")
        #    viber.send_messages(viber_request.user_id, [TextMessage(text="Good Bye!")])

        elif isinstance(viber_request, ViberFailedRequest):
            logger.warning(
                "client failed receiving message. failure: {0}".format(
                    viber_request))
        #logger.info("Response code 200")
        return Response(status=200)
    except Exception as e:
        logger.error("Error occured. {0}".format(e))
        print(e)
Example #6
0
def main_options(viber, viber_request, userrole, securityCode, usermessage):
    keyboard = KeyboardMessage(keyboard=buttons.main_keyboard)
    print("---------------------------------------------------")
    print(viber_request.message)
    global email
    if isinstance(viber_request.message, TextMessage):

        if re.match(r'(?i)(.*(FAQ).*)', usermessage):
            viber.send_messages(viber_request.sender.id, [
                TextMessage(text="Обери питання, яке тебе цікавить (Q): "),
                KeyboardMessage(keyboard=buttons.faq_keyboard)
            ])
        elif re.match(r'(?i).*(увійти)|(особистий)|(приватний).*кабінет.*',
                      usermessage):
            #viber.send_messages(viber_request.sender.id, [TextMessage(text=texts.sign_in), keyboard])
            if userrole[0] == 0:
                viber.send_messages(viber_request.sender.id, [
                    TextMessage(text=texts.sign_in),
                    KeyboardMessage(keyboard=buttons.share_phone,
                                    min_api_version=3)
                ])

            elif userrole[0] == 1:
                viber.send_messages(viber_request.sender.id, [
                    TextMessage(
                        text="Ви увійшли до особистого кабінету студента (nerd)"
                    ),
                    KeyboardMessage(keyboard=buttons.student_account)
                ])
            elif userrole[0] == 2:
                viber.send_messages(viber_request.sender.id, [
                    TextMessage(
                        text=
                        "Ви увійшли до особистого кабінету викладача (rockon)"
                    ), keyboard
                ])
        elif re.match(r'(?i).*((допомога)|(хелп)|(help)|(довідка)).*',
                      usermessage):
            viber.send_messages(viber_request.sender.id,
                                [TextMessage(text=texts.help), keyboard])
        elif re.match(r'(?i).*(зв\'язок)|(написати)|(зв\'язатися).*викладач.*',
                      usermessage):
            viber.send_messages(viber_request.sender.id, [
                TextMessage(
                    text="Задай питання, яке тебе цікавить викладачу нижче: "),
                keyboard
            ])
        elif re.match(r'.*@.*', usermessage):

            email = usermessage
            verification.main(viber, viber_request, userrole, usermessage,
                              securityCode)
        elif re.match(r'\d\d\d\d\d\d\d', usermessage):
            #print(condition, "!!!", securityCode, userrole)
            if int(usermessage) == int(securityCode[0]):
                if userrole[0] == 0:
                    viber.send_messages(
                        viber_request.sender.id,
                        [TextMessage(text=texts.error_registration)])
                elif userrole[0] == 1:
                    viber.send_messages(viber_request.sender.id, [
                        TextMessage(
                            text=
                            "Вітаю! (wink) Ви увійшли до особистого кабінету студента (nerd)"
                        ),
                        KeyboardMessage(keyboard=buttons.student_account)
                    ])

                    db2_database.update_user_id(viber_request.sender.id, email)
                elif userrole[0] == 2:
                    viber.send_messages(viber_request.sender.id, [
                        TextMessage(
                            text=
                            "Вітаю! (wink) Ви увійшли до особистого кабінету викладача (rockon)"
                        ), keyboard
                    ])
        elif userrole[0] == 1:
            studentAccount.main(viber, viber_request, usermessage)
        else:
            faq.faq_options(viber, viber_request, usermessage)
    elif isinstance(viber_request.message, ContactMessage):
        #viber.send_messages(viber_request.sender.id, [TextMessage(text=viber_request.message.contact.phone_number), keyboard])
        #print(viber_request.message.contact)
        viber.send_messages(viber_request.sender.id, [
            TextMessage(
                text="Введіть свій e-mail для перевірки нижче (letter): ")
        ])
Example #7
0
def incoming():
    logger.debug("received request. post data: {0}".format(request.get_data()))

    viber_request = viber.parse_request(request.get_data().decode('utf8'))
    # Welcome message
    if isinstance(viber_request, ViberConversationStartedRequest):
        viber.send_messages(viber_request.user.id, [
            TextMessage(text="Welcome! Please provide some feedback")
        ])

    elif isinstance(viber_request, ViberMessageRequest):

        message_id = str(viber_request.message_token)
        chat_id = str(viber_request.sender.id)
        user_name = viber_request.sender.name
        time_stmp = str(datetime.now())

        if isinstance(viber_request.message, TextMessage):
            message_text = viber_request.message.text
        elif isinstance(viber_request.message, PictureMessage):
            message_text = 'PictureMessage'

            image_url = viber_request.message.media
            headers = {'Ocp-Apim-Subscription-Key': param.azure_subscription_key}

            params = {
                'returnFaceId': 'false',
                'returnFaceLandmarks': 'false',
                'returnFaceAttributes': 'emotion',
            }

            response = requests.post(param.azure_face_api_url, params=params,
                                     headers=headers, json={"url": image_url})

            emotion_result = response.json()

            try:
                emotions = emotion_result[0]['faceAttributes']['emotion']
                print(emotions)
                if (emotions['happiness'] > 0.5) or (emotions['surprise'] > 0.5):
                    message_text = 'Great'
                elif (emotions['neutral'] > 0.5):
                    message_text = 'Not bad'
                elif (emotions['sadness'] > 0.5) or (emotions['anger'] > 0.5 ) or (emotions['anger'] > 0.5 ) \
                        or(emotions['disgust'] > 0.5) or (emotions['fear'] > 0.5 ):
                    message_text = 'So so'

            except IndexError:
                pass

        else:
            message_text = 'Something else'

        # Sending of statistics
        if (chat_id == param.viber_admin_id) and (message_text == 'Send statistics'):
            users = db.get_users()
            statistics = db.get_statistics()

            smiles = {'Great': ' (smiley) ', 'Not bad': ' (straight) ', 'So so': ' (sad) '}
            stat_mess = 'Thank you for voting!\nCurrent statisctics:'
            for statistic in statistics:
                stat_mess = stat_mess + '\n' + str(statistic.column_values[1]) + smiles[
                    statistic.column_values[0]] + str(statistic.column_values[0])

            for user in users:
                viber.send_messages(user.column_values[0], [
                    TextMessage(text=stat_mess)
                ])

        else:
            # Update message in BW
            bw_data = [{'/BIC/ZCHATID': chat_id,
                        '/BIC/ZMESID': message_id,
                        '/BIC/ZCHANNEL': 'Viber',
                        'RECORDMODE': '',
                        '/BIC/ZUSERNM': user_name,
                        '/BIC/ZSTAMP': time_stmp,
                        '/BIC/ZMESS': message_text}]
            try:
                bw.dso_update(bw_data)
            except:
                pass

            # Update message in HANA
            db_data = {'chat_id': chat_id,
                       'message_id': int(message_id),
                       'channel_id': 'Viber',
                       'user_name': user_name,
                       'time_stmp': time_stmp,
                       'message_text': message_text}

            db.table_update(db_data)
            # Voting keyboard JSON
            keyboard = {
                "Type": "keyboard",
                "Buttons": [
                    {
                        "Columns": 2,
                        "Rows": 2,
                        "BgColor": "#00348d",
                        "ActionType": "reply",
                        "ActionBody": "Great",
                        "Text": "<font color=\"#ffffff\" size=\"20\">Great</font>"
                    },
                    {
                        "Columns": 2,
                        "Rows": 2,
                        "BgColor": "#005fb8",
                        "ActionType": "reply",
                        "ActionBody": "Not bad",
                        "Text": "<font color=\"#ffffff\" size=\"20\">Not bad</font>"
                    },
                    {
                        "Columns": 2,
                        "Rows": 2,
                        "BgColor": "#0091da",
                        "ActionType": "reply",
                        "ActionBody": "So so",
                        "Text": "<font color=\"#ffffff\" size=\"20\">So so</font>"
                    }
                ]
            }

            ratings = ["Great", "Not bad", "So so"]

            if (message_text not in ratings):
                viber.send_messages(viber_request.sender.id, [
                    TextMessage(
                        text="Thank you! Please rate:\n(smiley) Great, (straight) Not bad, (sad) So so"),
                    KeyboardMessage(keyboard=keyboard)
                ])
            else:
                statistics = db.get_statistics()

                smiles = {'Great': ' (smiley) ', 'Not bad': ' (straight) ', 'So so': ' (sad) '}
                stat_mess = 'Thank you for voting!\nYou are ' + smiles[message_text] + '\nCurrent result:'

                for statistic in statistics:
                    stat_mess = stat_mess + '\n' + str(statistic.column_values[1]) + smiles[
                        statistic.column_values[0]] + str(statistic.column_values[0])

                viber.send_messages(viber_request.sender.id, [
                    TextMessage(text=stat_mess)
                ])

    elif isinstance(viber_request, ViberFailedRequest):
        logger.warn("client failed receiving message. failure: {0}".format(viber_request))

    return Response(status=200)
Example #8
0
def incoming():
    log("received request. post data: {0}".format(request.get_data()))
    # every viber message is signed, you can verify the signature using this method
    if not viber.verify_signature(
            request.get_data(),
            request.headers.get('X-Viber-Content-Signature')):
        return Response(status=403)

    # this library supplies a simple way to receive a request object
    viber_request = viber.parse_request(request.get_data())

    if isinstance(viber_request, ViberMessageRequest):
        message = viber_request.message
        message_out = messenger.handle_messages(message.text)
        keyboard_string = '''{
            "Type": "keyboard",
            "Buttons": [{
                "Columns": 2,
                "Rows": 2,
                "Text": "<br><font color=\\"#494E67\\"><b>RENT</b></font>",
                "TextSize": "large",
                "TextHAlign": "center",
                "TextVAlign": "middle",
                "ActionType": "reply",
                "ActionBody": "RENT",
                "BgColor": "#f4dfc1",
                "BgMedia": "https://s3.amazonaws.com/splitwise/uploads/category/icon/slim/home/rent.png"
            },{
                "Columns": 2,
                "Rows": 2,
                "Text": "<br><font color=\\"#494E67\\"><b>WATER</b></font>",
                "TextSize": "large",
                "TextHAlign": "center",
                "TextVAlign": "middle",
                "ActionType": "reply",
                "ActionBody": "WATER",
                "BgColor": "#cee8f1",
                "BgMedia": "https://s3.amazonaws.com/splitwise/uploads/category/icon/slim/utilities/water.png"
            },{
                "Columns": 2,
                "Rows": 2,
                "Text": "<br><font color=\\"#494E67\\"><b>GAS</b></font>",
                "TextSize": "large",
                "TextHAlign": "center",
                "TextVAlign": "middle",
                "ActionType": "reply",
                "ActionBody": "GAS",
                "BgColor": "#cee8f1",
                "BgMedia": "https://s3.amazonaws.com/splitwise/uploads/category/icon/slim/utilities/heat-gas.png"
            },{
                "Columns": 2,
                "Rows": 2,
                "Text": "<br><font color=\\"#494E67\\"><b>INTERNET</b></font>",
                "TextSize": "large",
                "TextHAlign": "center",
                "TextVAlign": "middle",
                "ActionType": "reply",
                "ActionBody": "INTERNET",
                "BgColor": "#cee8f1",
                "BgMedia": "https://s3.amazonaws.com/splitwise/uploads/category/icon/slim/utilities/tv-phone-internet.png"
            },{
                "Columns": 2,
                "Rows": 2,
                "Text": "<br><font color=\\"#494E67\\"><b>ELECTRICITY</b></font>",
                "TextSize": "large",
                "TextHAlign": "center",
                "TextVAlign": "middle",
                "ActionType": "reply",
                "ActionBody": "ELECTRICITY",
                "BgColor": "#cee8f1",
                "BgMedia": "https://s3.amazonaws.com/splitwise/uploads/category/icon/slim/utilities/electricity.png"
            }]
        }'''
        keyboard = json.loads(keyboard_string)
        message_keyboard = KeyboardMessage(tracking_data=None,
                                           keyboard=keyboard)
        viber.send_messages(viber_request.sender.id,
                            [TextMessage(text=message_out), message_keyboard])
    elif isinstance(viber_request, ViberSubscribedRequest):
        viber.send_messages(viber_request.get_user.id,
                            [TextMessage(text="thanks for subscribing!")])
    elif isinstance(viber_request, ViberFailedRequest):
        logger.warn("client failed receiving message. failure: {0}".format(
            viber_request))

    return Response(status=200)
Example #9
0
File: lr4.py Project: Mtchl8/isrpo
def incoming():
    logger.debug("received request. post data: {0}".format(request.get_data()))

    viber_request = viber.parse_request(request.get_data().decode('utf8'))
    try:
        if isinstance(viber_request, ViberMessageRequest):
            message = viber_request.message
            if viber_request.sender.id not in Tests.keys():
                Tests[viber_request.sender.id] = Test(viber_request.sender.id)

            current_test = Tests[viber_request.sender.id]
            if message.text.startswith('start'):
                ask_a_question(Tests[viber_request.sender.id],
                               viber_request.sender.id)

            elif message.text == 'Привести пример':
                example = random.choice(
                    current_test.questions[current_test.current_word].examples)
                viber.send_messages(viber_request.sender.id, [
                    TextMessage(text=example),
                    KeyboardMessage(keyboard=answer_keyboard)
                ])

            else:
                if message.text in Tests[
                        viber_request.sender.id].questions.keys():
                    if current_test.questions[message.text].check_answer(
                            message.text):
                        current_test.correct_amount += 1
                        viber.send_messages(viber_request.sender.id,
                                            [TextMessage(text="Верно!")])
                else:
                    Tests[viber_request.sender.id].wrong_amount += 1
                    viber.send_messages(
                        viber_request.sender.id,
                        [TextMessage(text='Ответ неправильный!')])

                if (current_test.correct_amount + current_test.wrong_amount
                    ) < current_test.max_questions:
                    ask_a_question(Tests[viber_request.sender.id],
                                   viber_request.sender.id)
                else:
                    viber.send_messages(viber_request.sender.id, [
                        TextMessage(
                            text=
                            f'Тест завершен! Ваши результаты: правильных ответов - {current_test.correct_amount}, неправильных - {current_test.wrong_amount}'
                        )
                    ])

        elif isinstance(viber_request, ViberConversationStartedRequest):
            viber.send_messages(viber_request.get_user().get_id(), [
                TextMessage(
                    text=
                    "Этот бот предназначен для заучивания английских слов. Для начала работы введите start или нажмите на кнопку снизу."
                )
            ])
        elif isinstance(viber_request, ViberFailedRequest):
            logger.warning(
                "client failed receiving message. failure: {0}".format(
                    viber_request))

    except Exception as ex:
        print(ex)

    return Response(status=200)
Example #10
0
def index(request):
    try:
        # every viber message is signed, you can verify the signature using this method
        if not viber.verify_signature(request.body, request.META.get('HTTP_X_VIBER_CONTENT_SIGNATURE')):
            return HttpResponseForbidden()
        # this library supplies a simple way to receive a request object
        viber_request = viber.parse_request(str(request.body, 'utf-8', 'ignore'))
        #logger.error(viber_request)

        if isinstance(viber_request, ViberFailedRequest):
            logger.warning("client failed receiving message. failure: {0}".format(viber_request))
            return HttpResponse()

        viber_user = None
        if hasattr(viber_request, 'user'):
            try:
                viber_user = ViberUser.objects.get(pk=viber_request.user.id)
            except ObjectDoesNotExist:
                pass
        elif hasattr(viber_request, 'sender'):
            try:
                viber_user = ViberUser.objects.get(pk=viber_request.sender.id)
            except ObjectDoesNotExist:
                pass

        if viber_user:
            if isinstance(viber_request, ViberConversationStartedRequest):
                send_disclaimer(viber_user.user_id, viber_user.user_language)
            elif isinstance(viber_request, ViberMessageRequest):
                if viber_request.silent:
                    id_int = []
                    if viber_request.message.text == 'm':
                        send_main_menu(viber_user.user_id, viber_user.user_language)
                    elif viber_request.message.text[0] == 'c' and check_id(id_int, viber_request.message.text[1:]):
                        id_int = id_int[0]
                        if viber_request.message.tracking_data == 'cust':
                            viber.send_messages(viber_user.user_id, [
                                TextMessage(tracking_data = id_int, text=format_lang(None, 'enter_question', viber_user.user_language), 
                                            keyboard=json.loads(get_main_menu_keyboard(viber_user.user_language)), min_api_version=3)
                            ])
                        else:
                            viber.send_messages(viber_user.user_id, [
                                RichMediaMessage(rich_media=json.loads(get_unified_button_keyboard(
                                        ['q' + str(quest.id) for quest in Question.objects.filter(category_id=id_int).order_by('id')],
                                        [quest.question_text_ru if is_ru(viber_user.user_language) else quest.question_text_en
                                            for quest in Question.objects.filter(category_id=id_int).order_by('id')],
                                        viber_user.user_language, rich=True)
                                    ), keyboard=json.loads(format_lang(menu_keyboard, menu_button_messages, viber_user.user_language)), min_api_version=3)
                            ])
                    elif viber_request.message.text[0] == 'q' and check_id(id_int, viber_request.message.text[1:]):
                        quest = Question.objects.get(pk=int(id_int[0]))
                        viber.send_messages(viber_user.user_id, [
                                RichMediaMessage(rich_media=json.loads(Template(question_rich_text).substitute({'answer_url': quest.answer_url or '', 
                                                 'action_type': 'open-url' if quest.answer_url else 'none', 'bg_color': '#A9CCE3' if quest.answer_url else '#D5DBDB',
                                                 'answer_text': quest.answer_text_ru if is_ru(viber_user.user_language) else quest.answer_text_en})), 
                                                 keyboard=json.loads(format_lang(menu_keyboard, menu_button_messages, viber_user.user_language)), min_api_version=3)
                            ])
                    elif viber_request.message.text == 'ask':
                        viber.send_messages(viber_user.user_id, [
                            KeyboardMessage(keyboard=json.loads(get_unified_button_keyboard(
                                ['c' + str(cat.id) for cat in Category.objects.all().order_by('id')],
                                [cat.category_name_ru if is_ru(viber_user.user_language) else cat.category_name_en
                                    for cat in Category.objects.all().order_by('id')], viber_user.user_language)), 
                                min_api_version=3)
                        ])
                    elif viber_request.message.text == 'cust':
                        viber.send_messages(viber_user.user_id, [
                            KeyboardMessage(tracking_data='cust', keyboard=json.loads(get_unified_button_keyboard(
                                ['c' + str(cat.id) for cat in Category.objects.all().order_by('id')],
                                [cat.category_name_ru if is_ru(viber_user.user_language) else cat.category_name_en

                                    for cat in Category.objects.all().order_by('id')], viber_user.user_language)), 
                                min_api_version=3)
                        ])
                    elif viber_request.message.text == 'call':
                        viber.send_messages(viber_user.user_id, [
                            ContactMessage(contact = Contact(name=format_lang(None, 'contact_name', viber_request.sender.language),
                                                     phone_number=format_lang(None, 'contact_phone', viber_request.sender.language)), 
                                           keyboard = json.loads(format_lang(menu_keyboard, menu_button_messages, 
                                                                        viber_user.user_language)), min_api_version = 3)
                            ])
                    elif viber_request.message.text == 'check':
                        mail = format_lang(None, 'email', viber_user.user_language)
                        subject = format_lang(None, 'email_subject_check', viber_user.user_language)
                        phone = viber_user.phone.phone_number_text
                        mail_text = Template(format_lang_not_for_json(None, 'email_template_check', viber_user.user_language)).substitute(
                            {'phone': phone})
                        viber.send_messages(viber_user.user_id, [
                            TextMessage(text=format_lang(None, 'check_accepted', viber_user.user_language), 
                                        keyboard=json.loads(format_lang(menu_keyboard, menu_button_messages, 
                                                                        viber_user.user_language)), min_api_version=3)
                            ])
                        if EmailMessage(subject, mail_text, settings.EMAIL_HOST_USER, [mail]).send(True) != 1:
                            raise Exception("Mail wasn't delivered. Subject:%s, Text:%s, Phone:%s"%(subject, mail_text, phone))
                    elif viber_request.message.text == 'att_n':
                        track_data = viber_request.message.tracking_data.split('|', 1)
                        mail = format_lang(None, 'email', viber_user.user_language)
                        subject = format_lang(None, 'email_subject', viber_user.user_language)
                        phone = viber_user.phone.phone_number_text
                        category = Category.objects.get(pk=int(track_data[0]))
                        mail_text = Template(format_lang_not_for_json(None, 'email_template', viber_user.user_language)).substitute(
                            {'question_text': track_data[1], 'phone': phone, 
                             'category': category.category_name_ru if is_ru(viber_user.user_language) else category.category_name_en})
                        viber.send_messages(viber_user.user_id, [
                                TextMessage(text=format_lang(None, 'question_accepted', viber_user.user_language), 
                                            keyboard=json.loads(format_lang(menu_keyboard, menu_button_messages, 
                                                                            viber_user.user_language)), min_api_version=3)
                                ])
                        if EmailMessage(subject, mail_text, settings.EMAIL_HOST_USER, [mail]).send(True) != 1:
                            raise Exception("Mail wasn't delivered. Subject:%s, Text:%s, Phone:%s"%(subject, mail_text, phone))
                    elif viber_request.message.text == 'sl':
                        viber_user.user_language = 'en' if is_ru(viber_user.user_language) else 'ru'
                        viber_user.save()
                        viber_user.refresh_from_db()
                        send_main_menu(viber_user.user_id, viber_user.user_language)
                else:
                    track_data = viber_request.message.tracking_data.split('|', 1)
                    if len(track_data) == 1:
                        viber.send_messages(viber_user.user_id, [
                            TextMessage(tracking_data = viber_request.message.tracking_data + '|' + viber_request.message.text,
                                text=format_lang(None, 'attach_file', viber_user.user_language), 
                                keyboard=json.loads(format_lang(attach_file_keyboard, ['att_n'], 
                                                                        viber_user.user_language)), min_api_version=3)
                            ])
                    else:
                        mail = format_lang(None, 'email', viber_user.user_language)
                        subject = format_lang(None, 'email_subject', viber_user.user_language)
                        phone = viber_user.phone.phone_number_text
                        category = Category.objects.get(pk=int(track_data[0]))
                        mail_text = Template(format_lang_not_for_json(None, 'email_template', viber_user.user_language)).substitute(
                            {'question_text': track_data[1], 'phone': phone, 
                             'category': category.category_name_ru if is_ru(viber_user.user_language) else category.category_name_en})
                        viber.send_messages(viber_user.user_id, [
                                TextMessage(text=format_lang(None, 'question_accepted', viber_user.user_language), 
                                            keyboard=json.loads(format_lang(menu_keyboard, menu_button_messages, 
                                                                            viber_user.user_language)), min_api_version=3)
                                ])
                        thr = threading.Thread(target=send_email, args=(subject, mail_text, mail, phone, viber_request))
                        thr.start()
        else:
            if isinstance(viber_request, ViberConversationStartedRequest):# or (isinstance(viber_request, ViberMessageRequest) and viber_request.silent):
                viber.send_messages(viber_request.user.id, [
                    KeyboardMessage(keyboard=json.loads(authorize_keyboard), min_api_version=4)])
            elif isinstance(viber_request, ViberMessageRequest):
                phone = None
                if hasattr(viber_request.message, 'text'):
                    m_phone = str(viber_request.message.text)
                elif hasattr(viber_request.message, 'contact'):
                    m_phone = viber_request.message.contact.phone_number
                try:
                    if m_phone.isalnum():
                        phone = WhitePhone.objects.get(pk=m_phone)
                except ObjectDoesNotExist:
                    pass
                if phone:
                    ViberUser.objects.create(user_id=viber_request.sender.id, phone=phone,
                                             user_language=viber_request.sender.language)
                    send_disclaimer(viber_request.sender.id, viber_request.sender.language)
                else:
                    viber.send_messages(viber_request.sender.id, [
                                        KeyboardMessage(keyboard=json.loads(format_lang(not_authorized_keyboard, 'not_authorized',
                                        viber_request.sender.language)), min_api_version=4)
                                        ])
    except Exception as e:
        logger.error(e)
    finally:
        return HttpResponse()
Example #11
0
def send_main_menu(user_id: int, language: str):
    viber.send_messages(user_id, [
        KeyboardMessage(keyboard=json.loads(format_lang(menu_keyboard, menu_button_messages, language)),
                       min_api_version=3)])
def incoming():
    logger.debug("received request. post data: {0}".format(request.get_data()))
    # every viber message is signed, you can verify the signature using this method
    if not viber.verify_signature(
            request.get_data(),
            request.headers.get('X-Viber-Content-Signature')):
        print("durak")
        return Response(status=403)

    # this library supplies a simple way to receive a request object
    viber_request = viber.parse_request(request.get_data())

    #viber.post_messages_to_public_account(sender=viber_request.get_sender().get_id(),
    #                                     messages=[TextMessage(text="sample message")])

    if isinstance(viber_request, ViberConversationStartedRequest):
        viber.send_messages(viber_request.sender.id, [
            TextMessage(
                text="Добрый день!\n Для начала работы с ботом наберите Начать."
            )
        ])

    if isinstance(viber_request, ViberMessageRequest):
        #message = viber_request.message

        SAMPLE_BUTTON = """{
                    "Type": "keyboard",
                    "InputFieldState": "hidden",
                    "Buttons": [{
                        "Columns": 3,
                        "Rows": 1,
                        "ActionBody": "_bot_write_acii",
                        "Text": "Акции"
                    },{

                        "Columns": 3,
                        "Rows": 1,
                        "ActionBody": "_bot_search_articul",
                        "Text": "Поиск по артикулу"

                    }]
                }"""

        RETURNBUTTON = """{
                            "Type": "keyboard",
                            "InputFieldState": "hidden",
                            "Buttons": [{
                                "Columns": 6,
                                "Rows": 1,
                                "ActionBody": "_bot_home",
                                "Text": "Назад"
                            }]
                    }"""

        SAMPLE_RICH_MEDIA = """{
                              "BgColor": "#69C48A",
                              "Buttons": [
                                {
                                  "Columns": 6,
                                  "Rows": 1,
                                  "BgColor": "#454545",
                                  "BgMediaType": "gif",
                                  "BgMedia": "http://www.url.by/test.gif",
                                  "BgLoop": true,
                                  "ActionType": "open-url",
                                  "Silent": true,
                                  "ActionBody": "www.tut.by",
                                  "Image": "www.tut.by/img.jpg",
                                  "TextVAlign": "middle",
                                  "TextHAlign": "left",
                                  "Text": "<b>example</b> button",
                                  "TextOpacity": 10,
                                  "TextSize": "regular"
                                }
                              ]
                            }"""

        SAMPLE_ALT_TEXT = "upgrade now!"

        message = viber_request.message
        command = message.text

        if command == "Начать" or command == "начать":
            viber.send_messages(
                viber_request.sender.id,
                [KeyboardMessage(keyboard=json.loads(SAMPLE_BUTTON))])

        if command == "_bot_search_articul":
            viber.send_messages(viber_request.sender.id, [
                TextMessage(text="Введите артикул для поиска"),
                KeyboardMessage(keyboard=json.loads(RETURNBUTTON))
            ])

        if command == "_bot_write_acii":
            viber.send_messages(
                viber_request.sender.id,
                [KeyboardMessage(keyboard=json.loads(RETURNBUTTON))])

        if command == "_bot_home":
            viber.send_messages(
                viber_request.sender.id,
                [KeyboardMessage(keyboard=json.loads(SAMPLE_BUTTON))])

        else:
            message = viber_request.message
            #message = "Select products.id_product, products.articul, prices.price, quantities.quantity, products.product FROM products LEFT JOIN prices on products.id_product = prices.id_product LEFT JOIN quantities on products.id_product = quantities.id_product WHERE articul LIKE "

            if len(str(message.text)) >= 4:
                #conn = psycopg2.connect(dbname='test-pe-lab', user='******',password='******', host='78.24.216.107', port=5433)
                conn = psycopg2.connect(dbname='server-test-pe-lab',
                                        user='******',
                                        password='******',
                                        host='78.24.216.107',
                                        port=5433)

                with conn.cursor() as cursor:
                    stmt = sql.SQL(
                        "Select products.id_product, products.articul, prices.price, quantities.quantity, products.product, prices.time_, products.link, products.image, prices.stock_price FROM products LEFT JOIN prices on products.id_product = prices.id_product and prices.date_ = current_date LEFT JOIN quantities on products.id_product = quantities.id_product and quantities.date_ = current_date WHERE articul ~* %s"
                    )
                    # viber.send_messages(viber_request.sender.id, [TextMessage(text=viber_request.message.text)])

                    cursor.execute(stmt, [message.text])
                    output = cursor.fetchall()
                    #viber.send_messages(viber_request.sender.id, [TextMessage(text=len(output[0]))])
                    data = {
                        #"receiver": viber_request.sender.id,
                        "type": "rich_media",
                        #"min_api_version": 6,
                        "rich_media": {
                            "Type": "rich_media",
                            "ButtonsGroupColumns": 6,
                            "ButtonsGroupRows": 7,
                            "BgColor": "#FFFFFF",
                            "Buttons": []
                        }
                    }
                    for row in output:
                        #viber.send_messages(viber_request.sender.id, [TextMessage(text=row[0])])

                        data["rich_media"]["Buttons"].append({
                            "Columns":
                            6,
                            "Rows":
                            3,
                            "ActionType":
                            "open-url",
                            "ActionBody":
                            "https://ulabrus.ru/" + row[6],
                            "Image":
                            "https://ulabrus.ru/" + row[7]
                        })
                        data["rich_media"]["Buttons"].append({
                            "Columns":
                            6,
                            "Rows":
                            2,
                            "Text":
                            "<font color=#323232><b>" + row[1] + "," + row[4] +
                            "</b></font>" +
                            "<font color=#777777><br>Цена </font><font color=#6fc133>"
                            + str(row[2]) + ", с учетом НДС 20%" + "</font>" +
                            "<font color=#777777><br>На складе </font><font color=#6fc133>"
                            + str(row[3]) + "</font>" +
                            "<font color=#777777><br>Данные актуальны на </font><font color=#6fc133>"
                            + str(row[5].strftime("%d.%m.%Y %H:%M")) +
                            "</font>",
                            "ActionType":
                            "open-url",
                            "ActionBody":
                            "https://ulabrus.ru/" + row[6],
                            "TextSize":
                            "medium",
                            "TextVAlign":
                            "middle",
                            "TextHAlign":
                            "left"
                        })
                        data["rich_media"]["Buttons"].append({
                            "Columns":
                            6,
                            "Rows":
                            1,
                            "ActionType":
                            "reply",
                            "ActionBody":
                            "https://ulabrus.ru/" + row[6],
                            "Text":
                            "<font color=#8367db>ПОДРОБНЕЕ</font>",
                            "TextSize":
                            "small",
                            "TextVAlign":
                            "middle",
                            "TextHAlign":
                            "middle"
                        })
                        if row[3] == None:
                            text_message = "Артикул: %s\nНаименование Полное:%s \nЦена: %s\nЦена по акции: %s\nКоличество на складе: 0\nДанные актуальны на: %s\nЗаказать: https://ulabrus.ru%s" % (
                                row[1], row[4],
                                str(
                                    locale.format(
                                        '%.2f', row[2],
                                        grouping=True)).replace(",", ".") +
                                ", с учетом НДС 20%",
                                str(
                                    locale.format(
                                        '%.2f', row[8],
                                        grouping=True)).replace(",", ".") +
                                ", с учетом НДС 20%"
                                if row[8] != None else "не проводится",
                                str(row[5].strftime("%d.%m.%Y %H:%M")), row[6])
                        else:
                            text_message = "Артикул: %s\nНаименование Полное:%s \nЦена: %s\nЦена по акции: %s\nКоличество на складе: %s\nДанные актуальны на: %s\nЗаказать: https://ulabrus.ru%s" % (
                                row[1], row[4],
                                str(
                                    locale.format(
                                        '%.2f', row[2],
                                        grouping=True)).replace(",", ".") +
                                ", с учетом НДС 20%",
                                str(
                                    locale.format(
                                        '%.2f', row[8],
                                        grouping=True)).replace(",", ".") +
                                ", с учетом НДС 20%" if row[8] != None else
                                "не проводится", str(row[3]),
                                str(row[5].strftime("%d.%m.%Y %H:%M")), row[6])
                            # text_message = "hello"
                        #if row[6] != None:
                        #url_message = "https://ulabrus.ru/" + row[6]

                        #if row[7] != None:
                        # img_message = "https://ulabrus.ru/" + row[7]
                        viber.send_messages(viber_request.sender.id, [
                            TextMessage(text=text_message),
                            KeyboardMessage(keyboard=json.loads(RETURNBUTTON))
                        ])
                app_json = json.dumps(data)
                #api.add_resource(app_json, '')
                #viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media=json.loads(app_json)), KeyboardMessage(keyboard=json.loads(RETURNBUTTON))])
            else:
                text_message = "Не могу найти товар.\nВведите, пожалуйста, не менее 4х символов!"
                viber.send_messages(viber_request.sender.id, [
                    TextMessage(text=text_message),
                    KeyboardMessage(keyboard=json.loads(RETURNBUTTON))
                ])

            #RichMediaMessage(rich_media=json.loads(app_json))

            # logger.debug(message)

        # lets echo back
        '''viber.send_messages(viber_request.sender.id, [
            message
        ])
    elif isinstance(viber_request, ViberSubscribedRequest):
        viber.send_messages(viber_request.get_user.id, [
            TextMessage(text="thanks for subscribing!")
        ])
    elif isinstance(viber_request, ViberFailedRequest):
        logger.warn("client failed receiving message. failure: {0}".format(viber_request))'''

    return Response(status=200)