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)
def incoming(): global last_token global last_token_track logger.debug("received request. post data: {0}".format(request.get_data())) viber_request = viber.parse_request(request.get_data().decode('utf8')) if isinstance(viber_request, ViberMessageRequest): message = viber_request.message token = viber_request.message_token command = message.text if token != last_token: last_token = token if re.match(command, "start", re.IGNORECASE) or re.match(command, "menu", re.IGNORECASE): send_main_menu(viber_request.sender.id) elif re.match(command, "mvnews", re.IGNORECASE): send_mvnews_menu(viber_request.sender.id) elif re.match(command, "mvjobs", re.IGNORECASE): send_mvjobs_menu(viber_request.sender.id) elif re.match(command, "radeef", re.IGNORECASE): send_radeef_menu(viber_request.sender.id) elif re.match(command, "sun.mv", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest headlines (book) from sun.mv:")]) sun_rich_media = Property.create_richmedia(News.sun()) viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media= sun_rich_media, min_api_version=6)]) send_mvnews_menu(viber_request.sender.id) elif re.match(command, "rajje.mv", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest headlines (book) from rajje.mv:")]) rajje_rich_media = Property.create_richmedia(News.raajje()) viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media= rajje_rich_media, min_api_version=6)]) send_mvnews_menu(viber_request.sender.id) elif re.match(command, "vaguthu.mv", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest headlines (book) from vaguthu.mv:")]) vaguthu_rich_media = Property.create_richmedia(News.vaguthu()) viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media= vaguthu_rich_media, min_api_version=6)]) send_mvnews_menu(viber_request.sender.id) elif re.match(command, "mihaaru.com", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest headlines (book) from mihaaru.mv:")]) mihaaru_rich_media = Property.create_richmedia(News.mihaaru()) viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media= mihaaru_rich_media, min_api_version=6)]) send_mvnews_menu(viber_request.sender.id) elif re.match(command, "jobmaldives", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest listings (paperclip) from job-maldives.com:")]) jobs_rich_media = Property.create_jobmv_rich_media() viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media= jobs_rich_media, min_api_version=6)]) send_mvjobs_menu(viber_request.sender.id) elif re.match(command, "vazeefa.mv", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest listings (paperclip) from vazeefa.mv:")]) vazeefa_rich_media = Property.create_vazeefa_rich_media() viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media= vazeefa_rich_media, min_api_version=6)]) send_mvjobs_menu(viber_request.sender.id) elif re.match(command, "gazette", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest listings (paperclip) from gazette.mv:")]) gazette_rich_media = Property.create_gazette_rich_media() viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media= gazette_rich_media, min_api_version=6)]) send_mvjobs_menu(viber_request.sender.id) elif re.match(command, "criminalcourt", re.IGNORECASE): court_schedule = getpdf() viber.send_messages(viber_request.sender.id, [TextMessage(text="Latest schedule (time) available from criminlcourt.gov.mv - [{0}]:".format(court_schedule[0]))]) pdf_message = FileMessage(media=court_schedule[1], size=court_schedule[2], file_name=court_schedule[3]) viber.send_messages(viber_request.sender.id, [pdf_message]) send_main_menu(viber_request.sender.id) elif re.match(command, "faithoora", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Kindly send me the Publication Number of the Faithoora you would like to read. \n\nFor example send me a message with the number: 200\n\nI will reply you with the 200th Publication of Faithoora.\n\nCurrently I have details of 300 Faithoora Publications in my database.", tracking_data="faithoora")]) send_radeef_menu(viber_request.sender.id) elif re.match(command, "en_radeef", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Kindly send me the English Word that you would like to search in Radeef.", tracking_data="en_radeef")]) send_radeef_menu(viber_request.sender.id) elif re.match(command, "lt_radeef", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Kindly send me the Latin Word that you would like to search in Radeef.", tracking_data="lt_radeef")]) send_radeef_menu(viber_request.sender.id) elif re.match(command, "dv_radeef", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Kindly send me the Dhivehi Word that you would like to search in Radeef.", tracking_data="dv_radeef")]) send_radeef_menu(viber_request.sender.id) elif re.match(command, "yt_audio", re.IGNORECASE): viber.send_messages(viber_request.sender.id, [TextMessage(text="Kindly send me the YouTube Link that you would like to convert to Audio", tracking_data="yt_audio")]) send_main_menu(viber_request.sender.id) if message.tracking_data == "yt_audio" and viber_request.sender.name is not "roanuedhuru": if token != last_token_track: last_token_track = token domain = tldextract.extract(message.text) if domain.domain == 'youtube' or domain.domain == 'youtu': viber.send_messages(viber_request.sender.id, [TextMessage(text="Ok! Allow me to convert it and come back to you with an Audio File. (yo)", tracking_data=None)]) ytdl_data = ytdl.ytdl_audio(message.text) if ytdl_data is not False: file_size = ytdl_data[0] media_link = ytdl_data[1] file_name = ytdl_data[2] aud_message = FileMessage(media=media_link, size=file_size, file_name=file_name) viber.send_messages(viber_request.sender.id, [aud_message]) else: viber.send_messages(viber_request.sender.id, [TextMessage(text="Well Viber is stupid! And it has limitations. (depressed) \nMax file size that can be shared is 50MB and the file we just downloaded is larger than that, well tell you a secret I could send you the same file on telegram - try our partner bot on telegram @megadlbot (eek)")]) else: viber.send_messages(viber_request.sender.id, [TextMessage(text="Invalid Link (eyeroll), Kindly resend me the command yt_audio and send me a proper YouTube link to convert it to Audio.", tracking_data=None)]) elif message.tracking_data == "faithoora" and viber_request.sender.name is not "roanuedhuru": if (message.text).isdigit() and float(message.text) <= 300: faithoora_link = "http://viber.eyaadh.net/faithoora/pdf/{0}.pdf".format(message.text) faithoora_size = os.path.getsize("/var/www/html/faithoora/pdf/{0}.pdf".format(message.text)) file_name = "{0}.pdf".format(message.text) if faithoora_size < 50000000: viber.send_messages(viber_request.sender.id, [TextMessage(text="Ok! Here is the {0}th Publication of Faithoora. (yo):".format(message.text), tracking_data=None)]) faithoora_message = FileMessage(media=faithoora_link, size=faithoora_size, file_name=file_name) viber.send_messages(viber_request.sender.id, [faithoora_message]) else: faithoora_link = "http://viber.eyaadh.net/download.php?file={0}".format(message.text) viber.send_messages(viber_request.sender.id, [TextMessage(text="Well Viber has limitations. (depressed) \nMax file size that can be shared is 50MB and the publication I have is larger than that therefore I cannot send it as a pdf file however I have shared the link to download it.", tracking_data=None)]) faithoora_keyboard = { "Type":"keyboard", "DefaultHeight":True, "Buttons": [ { "Columns": 6, "Rows": 1, "BgColor": "#FFFAFA", "ActionType": "open-url", "ActionBody":faithoora_link, "Text":"<font color='#000000'><b>Download Faithoora Publication: {0}</b></font>".format(file_name), "TextVAlign": "middle", "TextHAlign": "center", "TextOpacity": 90, "TextSize":"regular", "Frame": { "BorderWidth" : 2, "BorderColor" : "#708090", "CornerRadius" : 4 } }, { "Columns": 6, "Rows": 1, "BgColor": "#FFFAFA", "ActionType": None, "ActionBody": "menu", "Text":"<font color='#000000'><b>Back</b></font>", "TextVAlign": "middle", "TextHAlign": "center", "TextOpacity": 90, "TextSize":"regular", "Frame": { "BorderWidth" : 2, "BorderColor" : "#708090", "CornerRadius" : 4 } } ] } viber.send_messages(viber_request.sender.id, [KeyboardMessage(keyboard= faithoora_keyboard, min_api_version=6)]) elif float(message.text) > 300: viber.send_messages(viber_request.sender.id, [TextMessage(text="Invalid Publication Number (eyeroll), Kindly resend me the command faithoora and send me a proper Publication Number. I only have details of the first 300 Publications", tracking_data=None)]) else: viber.send_messages(viber_request.sender.id, [TextMessage(text="Invalid Publication Number (eyeroll), Kindly resend me the command faithoora and send me a proper Publication Number(only numerical values are accepted).", tracking_data=None)]) elif message.tracking_data == "en_radeef" and viber_request.sender.name is not "roanuedhuru": data_obj = radeef.radeef_english(message.text) if not data_obj: viber.send_messages(viber_request.sender.id, [TextMessage(text="I am sorry (sad), I could not find that word in Radeef.", tracking_data=None)]) else: data_message = "Dhivehi: {0}\nDefinition: {1}\nLatin: {2}\nEnglish:{3}".format(data_obj[3], data_obj[2], data_obj[1], data_obj[0]) viber.send_messages(viber_request.sender.id, [TextMessage(text=data_message, tracking_data=None)]) elif message.tracking_data == "lt_radeef" and viber_request.sender.name is not "roanuedhuru": data_obj = radeef.radeef_latin(message.text) if not data_obj: viber.send_messages(viber_request.sender.id, [TextMessage(text="I am sorry (sad), I could not find that word in Radeef.", tracking_data=None)]) else: data_message = "Dhivehi: {0}\nDefinition: {1}\nLatin: {2}\nEnglish:{3}".format(data_obj[3], data_obj[2], data_obj[1], data_obj[0]) viber.send_messages(viber_request.sender.id, [TextMessage(text=data_message, tracking_data=None)]) elif message.tracking_data == "dv_radeef" and viber_request.sender.name is not "roanuedhuru": data_obj = radeef.radeef_dhivehi(message.text) if not data_obj: viber.send_messages(viber_request.sender.id, [TextMessage(text="I am sorry (sad), I could not find that word in Radeef.", tracking_data=None)]) else: data_message = "Dhivehi: {0}\nDefinition: {1}\nLatin: {2}\nEnglish:{3}".format(data_obj[3], data_obj[2], data_obj[1], data_obj[0]) viber.send_messages(viber_request.sender.id, [TextMessage(text=data_message, tracking_data=None)]) if isinstance(viber_request, ViberConversationStartedRequest) : viber.send_messages(viber_request.user.id, [TextMessage(text="Hello {0}, \nI came to life from telegram. I am the same Raonueudhuru_bot from Telegarm and the same family who developed the telegram bot develop me on viber, currently I am at my beta source however we will be there in no time. \n\nSend me Start or Menu to begin with.".format(viber_request.user.name))]) elif isinstance(viber_request, ViberFailedRequest): logger.warn("client failed receiving message. failure: {0}".format(viber_request)) return Response(status=200)
def incoming(): #global output_ 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_product", "Text": '<font color="#f5f8f6"><b>Продукция</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", "Image": webhookURL + "images/png/shoppaymentorderbuy-250_90_5.png", #"ImageScaleType":"fit" # "BgMediaType": "picture", # "ImageScaleType": "fit", # "BgMediaScaleType": "fit", }, { "Columns": 3, "Rows": 1, "ActionBody": "_bot_search", "Text": '<font color="#f5f8f6"><b>Поиск</b></font>', "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", "Image": webhookURL + "images/png/search_find_magnifyingglass_15640_4.png" } ] } RETURNBUTTON = { "Type": "keyboard", "InputFieldState": "hidden", "Buttons": [{ "Columns": 6, "Rows": 1, "ActionBody": "_bot_home", "Text": "В главное меню", "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", }] } SEARCHBUTTON = { "Type": "keyboard", "InputFieldState": "hidden", "Buttons": [{ "Columns": 3, "Rows": 1, "ActionBody": "_bot_search_articul", "Text": '<font color="#f5f8f6"><b>Поиск по артикулу</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", }, { "Columns": 3, "Rows": 1, "ActionBody": "_bot_search_product", "Text": '<font color="#f5f8f6"><b>Поиск по названию</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", }, { "Columns": 6, "Rows": 1, "ActionBody": "_bot_home", "Text": '<font color="#f5f8f6"><b>В главное меню</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", "Image": webhookURL + "images/png/home256_24783_3.png", }] } STILLBUTTON = """{ "Type": "keyboard", "InputFieldState": "hidden", "Buttons": [{ "Columns": 6, "Rows": 1, "ActionBody": "_bot_search_still", "Text": "Еще", "Silent": "true", "BgColor": "#015b29" }, { "Columns": 6, "Rows": 1, "ActionBody": "_bot_home", "Text": "В главное меню", "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", }] }""" message = viber_request.message command = message.text if command == "Начать" or command == "начать": viber.send_messages(viber_request.sender.id, [ TextMessage( text= 'Могу рассказать Вам о наличии товаров на складах и действующих ценах и акциях.\n\n"Продукция" - переход в каталог товаров.\n"Поиск" - поиск по артикулу или наименованию.\n\nВыберите, пожалуйста, подходящий пункт меню.' ), KeyboardMessage(keyboard=SAMPLE_BUTTON, min_api_version=6) ]) #del OUTPUT_['mass'][:] #del OUTPUT['mass'][:] if command == "_bot_search": viber.send_messages(viber_request.sender.id, [ TextMessage(text="Выберите параметры поиска"), KeyboardMessage(keyboard=SEARCHBUTTON) ]) if command == "_bot_home": viber.send_messages(viber_request.sender.id, [ TextMessage( text= 'Могу рассказать Вам о наличии товаров на складах и действующих ценах и акциях.\n\n"Продукция" - переход в каталог товаров.\n"Поиск" - поиск по артикулу или наименованию.\n\nВыберите, пожалуйста, подходящий пункт меню.' ), KeyboardMessage(keyboard=SAMPLE_BUTTON) ]) #del OUTPUT_['mass'][:] # del OUTPUT['mass'][:] if command == "_bot_search_articul": global text_command text_command = "_bot_search_articul" # del OUTPUT['mass'][:] viber.send_messages(viber_request.sender.id, [ TextMessage( text="Введите артикул для поиска. Не менее 4-х символов"), KeyboardMessage(keyboard=SEARCHBUTTON) ]) if command == "_bot_search_product": text_command = "_bot_search_product" #del OUTPUT['mass'][:] viber.send_messages(viber_request.sender.id, [ TextMessage(text="Введите название или часть названия"), KeyboardMessage(keyboard=SEARCHBUTTON) ]) if text_command == "_bot_search_articul" and not ( command.startswith("_")): text_command = "_bot_search_articul" # print(text_command) message = viber_request.message #del OUTPUT['mass'][:] 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" ) cursor.execute(stmt, [message.text]) #global output outputProduct = cursor.fetchall() data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } if len(outputProduct) == 0 and command != text_command: viber.send_messages(viber_request.sender.id, [ TextMessage( text="По вашему запросу ничего не найдено."), KeyboardMessage(keyboard=SEARCHBUTTON) ]) countProduct = len(outputProduct) if len(outputProduct) <= 3: lenOut = len(outputProduct) else: lenOut = 3 for number in range(0, len(outputProduct), 1): if outputProduct != None: for row in outputProduct[:lenOut]: dataAppend(row, data) if len(data["Buttons"]) > 0: #output_.clear() #global output_ del outputProduct[:lenOut] if len(outputProduct) == 0: outputProduct = None #output_ = output[:] '''if len(OUTPUT['mass']) > 0: viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media=data, min_api_version=6), KeyboardMessage(keyboard=json.loads(STILLBUTTON))]) else:''' viber.send_messages(viber_request.sender.id, [ RichMediaMessage(rich_media=data, min_api_version=6) ]) data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } if outputProduct == None: if countProduct > 0: viber.send_messages(viber_request.sender.id, [ TextMessage(text="Всего найдено товаров: " + str(countProduct) + " (смотри выше 👆)"), KeyboardMessage(keyboard=SEARCHBUTTON) ]) if text_command == "_bot_search_product" and not ( command.startswith("_")): text_command = "_bot_search_product" message = viber_request.message 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 product ~* %s" ) cursor.execute(stmt, [message.text]) outputProduct = cursor.fetchall() data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } if len(outputProduct) == 0 and command != text_command: viber.send_messages(viber_request.sender.id, [ TextMessage( text="По вашему запросу ничего не найдено."), KeyboardMessage(keyboard=SEARCHBUTTON) ]) countProduct = len(outputProduct) if len(outputProduct) <= 3: lenOut = len(outputProduct) else: lenOut = 3 for number in range(0, len(outputProduct), 1): if outputProduct != None: for row in outputProduct[:lenOut]: dataAppend(row, data) if len(data["Buttons"]) > 0: del outputProduct[:lenOut] logger.debug( "text_command == '_bot_search_product' OUTPUT['mass'] =: " + str(len(outputProduct))) if len(outputProduct) == 0: outputProduct = None '''if len(OUTPUT['mass']) > 0: viber.send_messages(viber_request.sender.id, [RichMediaMessage(rich_media=data, min_api_version=6), KeyboardMessage(keyboard=json.loads(STILLBUTTON))]) else:''' viber.send_messages(viber_request.sender.id, [ RichMediaMessage(rich_media=data, min_api_version=6) ]) data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } if outputProduct == None: viber.send_messages(viber_request.sender.id, [ TextMessage(text="Всего найдено товаров: " + str(countProduct) + " (смотри выше 👆)"), KeyboardMessage(keyboard=SEARCHBUTTON) ]) if command == "_bot_search_still": text_command = "_bot_search_still" #output = OUTPUT_['mass'][:] #del output_[:] data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } if len(OUTPUT['mass']) <= 3: lenOut = len(OUTPUT['mass']) else: lenOut = 3 logger.debug("сommand == '_bot_search_still' OUTPUT['mass'] =: " + str(len(OUTPUT['mass']))) for row in OUTPUT['mass'][:lenOut]: dataAppend(row, data) if len(data["Buttons"]) > 0: #global output_ #del OUTPUT_['mass'][:] # global output_ #nonlocal output del OUTPUT['mass'][:lenOut] #OUTPUT_['mass'] = output[:] logger.debug( "сommand == '_bot_search_still' OUTPUT['mass'] =: " + str(len(OUTPUT['mass']))) if len(OUTPUT['mass']) > 0: viber.send_messages(viber_request.sender.id, [ RichMediaMessage(rich_media=data, min_api_version=6), KeyboardMessage(keyboard=STILLBUTTON) ]) else: viber.send_messages(viber_request.sender.id, [ RichMediaMessage(rich_media=data, min_api_version=6), KeyboardMessage(keyboard=SEARCHBUTTON) ]) if command == "_bot_product": text_command = "_bot_product" conn = psycopg2.connect(dbname='server-test-pe-lab', user='******', password='******', host='78.24.216.107', port=5433) with conn.cursor() as cursor: smtp = sql.SQL( "Select id_start_category, name_start_category From start_categories" ) cursor.execute(smtp) output = cursor.fetchall() categories_buttons = { "Type": "keyboard", "InputFieldState": "hidden", "Buttons": [] } for row in output: categories_buttons["Buttons"].append({ "Columns": 3, "Rows": 1, "ActionType": "", "ActionBody": row[1], "Text": '<font color="#f5f8f6"><b>' + row[1].replace(" ", "\n") + '</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", #"name": row[1] }) categories_buttons["Buttons"].append({ "Columns": 6, "Rows": 1, "ActionBody": "_bot_home", "Text": '<font color="#f5f8f6"><b>В главное меню</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", "Image": webhookURL + "images/png/home256_24783_3.png", }) viber.send_messages(viber_request.sender.id, [ TextMessage( text= "Выберите, пожалуйста, из меню информация о каком товаре Вам нужна." ), KeyboardMessage(keyboard=categories_buttons) ]) if command == "Общелабораторное оборудование" or command == "Аксессуары": message = viber_request.message global name_razdel name_razdel = message.text 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 start_categories.id_start_category, categories.id_category, categories.name_category From start_categories Left Join categories On start_categories.id_start_category = categories.id_start_category Where start_categories.name_start_category ~ %s" ) cursor.execute(stmt, [message.text]) output = cursor.fetchall() data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } for row in output: data["Buttons"].append({ "Columns": 6, "Rows": 1, "Text": '<font color="#3c38d8"><u>' + row[2] + "</u></font>", "ActionBody": row[2], "TextVAlign": "middle", "TextHAlign": "left", "TextShouldFit": "true", "Silent": "true", }) conn = psycopg2.connect(dbname='server-test-pe-lab', user='******', password='******', host='78.24.216.107', port=5433) with conn.cursor() as cursor: smtp = sql.SQL( "Select id_start_category, name_start_category From start_categories" ) cursor.execute(smtp) output = cursor.fetchall() categories_buttons = { "Type": "keyboard", "InputFieldState": "hidden", "Buttons": [] } for row in output: categories_buttons["Buttons"].append({ "Columns": 3, "Rows": 1, "ActionBody": row[1], "Text": '<font color="#f5f8f6"><b>' + row[1] + '</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", }) categories_buttons["Buttons"].append({ "Columns": 6, "Rows": 1, "ActionBody": "_bot_home", "Text": '<font color="#f5f8f6"><b>В главное меню</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", "Image": webhookURL + "images/png/home256_24783_3.png", }) viber.send_messages(viber_request.sender.id, [ RichMediaMessage(rich_media=data, min_api_version=6), TextMessage(text="Выберите нужный раздел из списка выше."), KeyboardMessage(keyboard=categories_buttons) ]) if command == "_bot_order_product": pass else: if command != "": message = viber_request.message 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 start_categories.id_start_category, categories.id_category, categories.name_category From start_categories Left Join categories On start_categories.id_start_category = categories.id_start_category Where start_categories.name_start_category ~ %s" ) cursor.execute(stmt, [name_razdel]) output = cursor.fetchall() for row in output: if command == row[2]: 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 Left Join categories On products.id_category = categories.id_category WHERE categories.name_category ~ %s" ) cursor.execute(stmt, [message.text]) outputProduct = cursor.fetchall() data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } countProduct = len(outputProduct) if len(outputProduct) <= 3: lenOut = len(outputProduct) else: lenOut = 3 for number in range(0, len(outputProduct), 1): if outputProduct != None: for row_ in outputProduct[:lenOut]: dataAppend(row_, data) if len(data["Buttons"]) > 0: # del outputProduct[:lenOut] for row_ in outputProduct[:lenOut]: outputProduct.remove(row_) # time.sleep(1) if len(outputProduct) <= 3 and len( outputProduct) != 0: lenOut = len(outputProduct) else: lenOut = 3 logger.debug( "text_command == '_bot_search_product' OUTPUTProduct['mass'] =: " + str(len(outputProduct))) if len(outputProduct) == 0: outputProduct = None viber.send_messages( viber_request.sender.id, [ RichMediaMessage( rich_media=data, min_api_version=6) ]) data = { "Type": "rich_media", "ButtonsGroupColumns": 6, "ButtonsGroupRows": 7, # "BgColor": "#E6E6FA", "Buttons": [] } else: command = None text_command = None name_razdel = None break if outputProduct == None: smtp = sql.SQL( "Select id_start_category, name_start_category From start_categories" ) cursor.execute(smtp) outputStartCat = cursor.fetchall() categories_buttons = { "Type": "keyboard", "InputFieldState": "hidden", "Buttons": [] } for row__ in outputStartCat: categories_buttons["Buttons"].append({ "Columns": 3, "Rows": 1, "ActionBody": row__[1], "Text": '<font color="#f5f8f6"><b>' + row__[1] + '</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", }) categories_buttons["Buttons"].append({ "Columns": 6, "Rows": 1, "ActionBody": "_bot_home", "Text": '<font color="#f5f8f6"><b>В главное меню</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", "Image": webhookURL + "images/png/home256_24783_3.png", }) viber.send_messages(viber_request.sender.id, [ TextMessage(text="Всего товаров: " + str(countProduct) + " (смотри выше 👆)"), KeyboardMessage( keyboard=categories_buttons) ]) #return return Response(status=200)
def user_message_handler(viber, viber_request): """Receiving a message from user and sending replies.""" logger.info(viber_request) message = viber_request.message tracking_data = message.tracking_data # Data for usual TextMessage reply_text = '' reply_keyboard = {} # Data for RichMediaMessage reply_alt_text = '' reply_rich_media = {} if tracking_data is None: tracking_data = {'comment_mode': 'off', 'address_mode': 'off'} else: tracking_data = json.loads(tracking_data) if isinstance(message, ContactMessage): # Handling reply after user shared his contact infromation input_new_user(viber_request.sender.id, message.contact.phone_number) tracking_data['name'] = message.contact.name tracking_data['phone'] = message.contact.phone_number reply_keyboard = kb.MENU_KEYBOARD reply_text = 'Спасибо! Выберите интересующую Вас категорию.' ##### # user_data = f'{viber_request.sender.id} - {message.contact.phone_number}' # feedback = TextMessage(text=user_data) # for admin in ADMINS: # viber.send_messages(admin, feedback) ##### elif isinstance(message, LocationMessage): # Handling reply after a user shared his location and transcribing it tracking_data['location'] = get_address(message.location) reply_keyboard = kb.FINAL_COMFIRMATION_WITH_COMMENT_KEYBOARD reply_text = f"Спасибо! Вы указали:\n{tracking_data['location']}\n\n"\ 'Нажмите кнопку "добавить комментарий" для того чтобы указать дату и время.'\ "Для подтверждения заказа нажмите Заказать." else: text = viber_request.message.text ########################################################## ######## Dislpaying keyboard of different items ########## ########################################################## if text in KEYBOARD_RESPONSE_MAP: reply_text = KEYBOARD_RESPONSE_MAP[text][0] reply_keyboard = KEYBOARD_RESPONSE_MAP[text][1] if kb.MENU_BUTTON not in reply_keyboard['Buttons'] and text != 'menu': reply_keyboard['Buttons'].append(kb.MENU_BUTTON) if 'order' in tracking_data and len(tracking_data['order']) > 0 and text not in ['address','confirmation']: if kb.ORDER_BUTTON[0] not in reply_keyboard['Buttons']: reply_keyboard['Buttons'] += kb.ORDER_BUTTON if 'order' in tracking_data and len(tracking_data['order']) == 0 and text not in ['address','confirmation']: if kb.ORDER_BUTTON[0] in reply_keyboard['Buttons']: reply_keyboard['Buttons'].remove(kb.ORDER_BUTTON[0]) reply_keyboard['Buttons'].remove(kb.ORDER_BUTTON[1]) ########################################################## ######## Dislpaying carousel of different items ########## ########################################################## elif text in RICH_RESPONSE_MAP: reply_alt_text = RICH_RESPONSE_MAP[text][0] reply_rich_media = RICH_RESPONSE_MAP[text][1] ########################################################## elif text == 'edit': reply_text = 'Выберите какое блюдо вы желаете удалить.' reply_keyboard = keyboard_delete(tracking_data['order']) elif text[:6] == 'delete': deleted_item = text.split('_')[1] for item in tracking_data['order']: if item[0] == deleted_item: tracking_data['order'].remove(item) break reply_text = f'Вы удалили {deleted_item}.\nВыберите дальнейшее дейтсвие.' reply_keyboard = kb.GO_TO_MENU_KEYBOARD if kb.MENU_BUTTON not in reply_keyboard['Buttons'] and text != 'menu': reply_keyboard['Buttons'].append(kb.MENU_BUTTON) if 'order' in tracking_data and len(tracking_data['order']) > 0: if kb.ORDER_BUTTON[0] not in reply_keyboard['Buttons']: reply_keyboard['Buttons'] += kb.ORDER_BUTTON if 'order' in tracking_data and len(tracking_data['order']) == 0: if kb.ORDER_BUTTON[0] in reply_keyboard['Buttons']: reply_keyboard['Buttons'].remove(kb.ORDER_BUTTON[0]) reply_keyboard['Buttons'].remove(kb.ORDER_BUTTON[1]) elif text == 'address': if int(viber_request.sender.api_version) < 10: reply_text = 'Напишите адрес доставки в ответе на это сообщение.' reply_keyboard = kb.GO_TO_MENU_KEYBOARD reply_keyboard['Buttons'].append(kb.MENU_BUTTON) tracking_data['address_mode'] = 'on' else: reply_text = 'Укажите адрес доставки заказа. '\ 'Для этого нажмите Отправить Локацию.' reply_keyboard = kb.SHARE_LOCATION_KEYBOARD elif text == 'pickup': tracking_data['location'] = 'Самовывоз' reply_text = 'Нажмите кнопку "добавить комментарий" для того чтобы указать дату и время' reply_keyboard = kb.FINAL_COMFIRMATION_WITH_COMMENT_KEYBOARD elif text == 'comment': # Setting the possibility to write a comment tracking_data['comment_mode'] = 'on' reply_text = 'Напишите Ваши пожелания в ответ на это сообщение.' elif text[:5] == 'order': # Handling user selection of product, and dislpaying his choice ordered_item = text.split('_')[1] item_price = text.split('_')[2] if 'order' in tracking_data: tracking_data['order'].append((ordered_item, item_price)) else: tracking_data['order'] = [(ordered_item, item_price)] total_price = sum([int(x[1]) for x in tracking_data['order']]) invoice = [u"\u2022" + f' {x[0]} - {x[1]} грн.' for x in tracking_data['order']] bslash = '\n' reply_text = f'Вы выбрали:\n{bslash.join(invoice)}\n'\ f'Всего - {total_price} грн.\n\n'\ 'Если желаете выбрать что-нибудь еще, нажмите Меню. '\ 'Для продолжения, нажмите Оформить заказ.' reply_keyboard = kb.ORDER_COMFIRMATION_KEYBOARD elif text == 'send_order': # Final step, sends all info to manager and resets tracking_data tracking_data['comment_mode'] = 'off' mesage_to_admin = "Новый заказ!\n" total_price = sum([int(x[1]) for x in tracking_data['order']]) invoice = [u"\u2022" + f' {x[0]} - {x[1]} грн.' for x in tracking_data['order']] bslash = '\n' if tracking_data['name'] is not None: mesage_to_admin += f"Имя: {tracking_data['name']}\n" mesage_to_admin += f"Номер: +{tracking_data['phone']}\n"\ f"Заказ:\n{bslash.join(invoice)}\n"\ f"Всего: {total_price} грн.\n"\ f"Адрес: {tracking_data['location']}\n" if 'comment' in tracking_data and tracking_data['comment'] != '': mesage_to_admin += f"Комментарий: {tracking_data['comment']}\n" for admin in ADMINS: viber.send_messages(admin, TextMessage(text=mesage_to_admin)) tracking_data['order'] = [] tracking_data['location'] = '' tracking_data['comment'] = '' reply_text = 'Спасибо за заказ, менеджер в скором времени'\ ' свяжется с Вами.' reply_keyboard = kb.MENU_KEYBOARD else: # Handling text messages from client and checking if it's a comment if tracking_data['comment_mode'] == 'on': tracking_data['comment'] = text reply_text = 'Спасибо! Для подтверждения заказа нажмите '\ 'Заказать.' reply_keyboard = kb.FINAL_COMFIRMATION_WITHOUT_COMMENT_KEYBOARD elif tracking_data['address_mode'] == 'on': tracking_data['address_mode'] = 'off' tracking_data['location'] = text reply_text = 'Нажмите кнопку "добавить комментарий" для того чтобы указать дату и время.'\ "Для подтверждения заказа нажмите Заказать." reply_keyboard = kb.FINAL_COMFIRMATION_WITH_COMMENT_KEYBOARD else: reply_text = 'Воспользуйтесь клавиатурой с кнопками для '\ 'управления ботом.' if 'phone' in tracking_data: reply_keyboard = kb.MENU_KEYBOARD else: reply_keyboard = kb.SHARE_PHONE_KEYBOARD if reply_rich_media: reply = [] reply_text = 'Для выбора нажмите на желаемую позицию из перечня выше.' reply_keyboard = kb.GO_TO_MENU_KEYBOARD if kb.MENU_BUTTON not in reply_keyboard['Buttons'] and text != 'menu': reply_keyboard['Buttons'].append(kb.MENU_BUTTON) if 'order' in tracking_data and len(tracking_data['order']) > 0: if kb.ORDER_BUTTON[0] not in reply_keyboard['Buttons']: reply_keyboard['Buttons'] += kb.ORDER_BUTTON if 'order' in tracking_data and len(tracking_data['order']) == 0: if kb.ORDER_BUTTON[0] in reply_keyboard['Buttons']: reply_keyboard['Buttons'].remove(kb.ORDER_BUTTON[0]) reply_keyboard['Buttons'].remove(kb.ORDER_BUTTON[1]) logger.info(tracking_data) tracking_data = json.dumps(tracking_data) for template in reply_rich_media: reply.append( RichMediaMessage(rich_media=template, alt_text=reply_alt_text, tracking_data=tracking_data, min_api_version=7) ) reply.append( TextMessage(text=reply_text, keyboard=reply_keyboard, tracking_data=tracking_data, min_api_version=3) ) else: logger.info(tracking_data) tracking_data = json.dumps(tracking_data) reply = [TextMessage(text=reply_text, keyboard=reply_keyboard, tracking_data=tracking_data, min_api_version=3)] viber.send_messages(viber_request.sender.id, reply)
def incoming(): print("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()) viber2_request = viber.parse_request(request.get_data().decode('utf-8')) #viber.post_messages_to_public_account(sender=viber_request.get_sender().get_id(), #messages=[TextMessage(text="sample message")]) if isinstance(viber2_request, ViberConversationStartedRequest): SAMPLE_BUTTON = { "Type": "keyboard", "InputFieldState": "hidden", "Buttons": [ { "Columns": 3, "Rows": 1, "ActionBody": "_bot_product", "Text": '<font color="#f5f8f6"><b>Продукция</b></font>', "Silent": "true", "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", # "ImageScaleType":"fit" # "BgMediaType": "picture", # "ImageScaleType": "fit", # "BgMediaScaleType": "fit", }, { "Columns": 3, "Rows": 1, "ActionBody": "_bot_search", "Text": '<font color="#f5f8f6"><b>Поиск</b></font>', "BgColor": "#015b29", "TextSize": "large", "TextHAlign": "center", "TextVAlign": "middle", "ActionType": "reply", } ] } SAMPLE_RICH_MEDIA = { "Type": "rich_media", "ButtonsGroupRows":3, "Buttons": [ { "Columns": 6, "Rows": 2, "BgMedia": "https://i.imgur.com/G5rI7pK.png", "BgMediaType": "picture", "BgLoop": "true", "ActionType": None, "Silent": "true", "ActionBody": "", "Image": "#", "TextVAlign": "middle", "TextHAlign": "center", "Text": "", "TextOpacity": 100, "TextSize": "regular" }, { "Columns": 6, "Rows": 1, "BgColor": "#8074d6", "BgMediaType": "gif", "BgMedia": "#", "BgLoop": "true", "ActionType": None, "Silent": "true", "ActionBody": " ", "Image": "#", "TextVAlign": "middle", "TextHAlign": "center", "Text": "<b>Подписаться</b>", "TextOpacity": 100, "TextSize": "regular" } ], } SAMPLE_ALT_TEXT = "Забирай бонус!" message = RichMediaMessage(rich_media=SAMPLE_RICH_MEDIA, alt_text=SAMPLE_ALT_TEXT, min_api_version=2) #json.loads? viber.send_messages(viber2_request.user.id, [message]) RICH_MEDIA_BUTTON = { "Type": "rich_media", "ButtonsGroupRows": 1, "Buttons": [ { "Columns": 6, "Rows": 1, "BgColor": "#8074d6", "BgMediaType": "gif", "BgMedia": "#", "BgLoop": "true", "ActionType": 'open-url', "Silent": "true", "ActionBody": "http://hotto.top/cosmo", "Image": "#", "TextVAlign": "middle", "TextHAlign": "center", "Text": "<b>Забрать бонус🎁</b>", "TextOpacity": 100, "TextSize": "regular" } ], } RICH_MEDIA_ALT = "Забирай бонус!" if isinstance(viber2_request, ViberMessageRequest): viber.send_messages(viber2_request.sender.id, [ PictureMessage(media='https://i.imgur.com/wZxWrlb.jpg'), TextMessage(text='Забирай космические бонусы.\nНажимай на кнопку под сообщением и крути колесо. Тебя ждут до 5️⃣0️⃣0️⃣ FS + 5️⃣ 0️⃣0️⃣0️⃣ гривен к первому депозиту. \nПредложение актуально только 48 часов. Не тяни👇'), RichMediaMessage(rich_media=RICH_MEDIA_BUTTON, alt_text=RICH_MEDIA_ALT, min_api_version=2) ]) #if isinstance(viber2_request, ViberSubscribedRequest): #TextMessage(text="Добрый день!\n Для начала работы с ботом наберите Начать."), #KeyboardMessage(keyboard=SAMPLE_BUTTON, min_api_version=6) if isinstance(viber_request, ViberFailedRequest): print("client failed receiving message. failure: {0}".format(viber_request)) return Response(status=200)
def user_message_handler(viber, viber_request): """Receiving a message from user and sending replies.""" logger.info(f'user_data: {viber_request.sender.id}') message = viber_request.message tracking_data = message.tracking_data # Data for Message reply_text = '' reply_keyboard = {} reply_rich_media = {} if tracking_data: tracking_data = json.loads(tracking_data) else: tracking_data = {} logger.info(f'user_data: {tracking_data}') text = viber_request.message.text if text[:6] == 'newday': last_hours = datetime.now() - timedelta(hours=24) post_list = model_transcriptor(Post.objects.filter( publish_date__gte=last_hours))[::-1] callback = text.split('_') if post_list: reply_text, reply_rich_media, reply_keyboard = view_definer( post_list, tracking_data, callback, 'newday') else: reply_text = 'Новых вакансий пока нет.' reply_keyboard = kb.GO_TO_MENU_KEYBOARD elif text[:6] == 'filter': callback = text.split('_') if len(callback) > 1 and callback[1] == 'title': tracking_data['title'] = callback[2] if len(callback) > 1 and callback[1] == 'salary': tracking_data['salary'] = callback[2] if ('title' in tracking_data and tracking_data['title'] != '') or\ ('salary' in tracking_data and tracking_data['salary'] != ''): reply_text = 'Вы выбрали следующие параметры поиска.\n' if 'title' in tracking_data and tracking_data['title'] != '': reply_text += f'\nДолжность: {tracking_data["title"]}' if 'salary' in tracking_data and tracking_data['salary'] != '': reply_text += f'\nЗарплата: {tracking_data["salary"]}' else: reply_text = 'Выберите параметр по которому отфильтровать вакансии.' reply_keyboard = kb.FILTER_KEYBOARD elif text[:6] == 'detail': callback_id = text.split('_')[1] back_menu = text.split('_')[2] post = Post.objects.get(id=callback_id) reply_text = model_text_details(post) reply_keyboard = action_insert(kb.RETURN_KEYBOARD, back_menu) elif text == 'title': reply_text = 'Выберите интересующую должность.' reply_keyboard = kb.GO_TO_MENU_KEYBOARD reply_rich_media = rm.TITLE_MEDIA elif text == 'salary': reply_text = 'Выберите интересующую зарплату.' reply_keyboard = kb.GO_TO_MENU_KEYBOARD reply_rich_media = rm.SALARY_MEDIA elif text == 'documents': reply_text = DOCUMENTS reply_keyboard = kb.GO_TO_MENU_KEYBOARD elif text == 'reset': garbage_title = tracking_data.pop('title', None) garbage_salary = tracking_data.pop('salary', None) reply_text = 'Выберите параметр по которому отфильтровать вакансии.' reply_keyboard = kb.FILTER_KEYBOARD elif text[:6] == 'search': all_entries = Post.objects.all() callback = text.split('_') if 'title' in tracking_data and tracking_data['title'] != '': logger.info(f'user_data: {tracking_data["title"]}') all_entries = all_entries.filter(title__in=tracking_data['title'].split(', ')) post_list = model_transcriptor(all_entries)[::-1] titles_unique = set([x['title'] for x in post_list]) # logger.info(f'user_data: {titles_unique}') if post_list == []: reply_text = 'По Вашему фильтру вакансий не найдено.' reply_keyboard = kb.GO_TO_MENU_KEYBOARD else: result = [] for post in post_list: if 'salary' not in tracking_data or \ tracking_data['salary'] == '' or \ tracking_data['salary'] == 'Не важно': cleaned_sub_salary_start = 0 cleaned_sub_salary_end = 1000000 else: cleaned_sub_salary = re.findall(r'[0-9]+',tracking_data['salary']) cleaned_sub_salary_start = int(cleaned_sub_salary[0]) cleaned_sub_salary_end = int(cleaned_sub_salary[1]) cleaned_salary = int(re.findall(r'[0-9]+', post['salary'])[0]) if cleaned_sub_salary_start != '' \ and cleaned_sub_salary_end != '' \ and cleaned_sub_salary_start <= cleaned_salary \ and cleaned_salary <= cleaned_sub_salary_end: result.append(post) reply_text, reply_rich_media, reply_keyboard = view_definer( result, tracking_data, callback, 'search') elif text == 'menu': # Setting the possibility to write a comment tracking_data['page'] = '0' reply_text = 'Выберите действие чтобы продолжить.' reply_keyboard = kb.MENU_KEYBOARD else: reply_text = 'Выберите действие чтобы продолжить.' reply_keyboard = kb.MENU_KEYBOARD tracking_data = json.dumps(tracking_data) if reply_rich_media: reply = [RichMediaMessage(rich_media=reply_rich_media, alt_text=reply_text, tracking_data=tracking_data, min_api_version=7)] reply.append(TextMessage(text=reply_text, keyboard=reply_keyboard, tracking_data=tracking_data, min_api_version=3)) else: reply = [TextMessage(text=reply_text, keyboard=reply_keyboard, tracking_data=tracking_data, min_api_version=3)] viber.send_messages(viber_request.sender.id, reply)
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()
def send_disclaimer(user_id: int, language: str): viber.send_messages(user_id, [RichMediaMessage( rich_media=json.loads(format_lang(disclaimer_rich_text, 'disclaimer', language)), min_api_version=4, keyboard=json.loads(format_lang(menu_keyboard, menu_button_messages, language)))])