def test_validate_failure(): picture_message = PictureMessage(tracking_data=SAMPLE_TRACKING_DATA, keyboard=SAMPLE_KEYBOARD, text=SAMPLE_TEXT, thumbnail=SAMPLE_THUMBNAIL) assert not picture_message.validate()
def get_question_response(bot, request, response_message): subject = get_subject_code(bot) question = get_question(subject) if question.image and question.content: response_message.append( PictureMessage( media=IMAGE_URL.format(id=question.id), thumbnail=THUMBNAIL_URL.format(id=question.id), ) ) if question.image and not question.content: response = ViberResponsePictureMessage(request, question.id) response.text = f"{INDEX_POINTING_RIGHT} {CHOICES_AVAILABLE_B}" else: response = ViberResponseTextMessage(request) response.text = question.text response.tracking_data = question.id response.keyboard["Buttons"].extend(question.buttons) return response
def share(self, viber_request): hostname = "%s://%s" % (self.request.scheme, self.request.get_host()) photo = urljoin(hostname, 'media/qr-code1.jpg') viber.send_messages(viber_request.sender.id, [PictureMessage( media=photo, text="Viber bot", thumbnail=photo, )]) botton_back(viber_request)
def send_file(self, receiver: str, file_url: str, file_size: int, file_name: str, file_type: str = None, button_list: list = None, **kwargs) -> str: kb = self._get_keyboard(button_list) if button_list else None if file_type == 'image': message = PictureMessage(media=file_url, keyboard=kb) elif file_type == 'video': message = VideoMessage(media=file_url, size=file_size, keyboard=kb) else: message = FileMessage(media=file_url, size=file_size, file_name=file_name, keyboard=kb) try: return self.bot.send_messages(receiver, [message])[0] except Exception as err: if str(err) == 'failed with status: 6, message: notSubscribed': raise NotSubscribed(err) raise MessengerException(err)
def message(self): return PictureMessage( tracking_data=self.tracking_data, keyboard=self.keyboard, text=self.text, media=IMAGE_URL.format(id=self.question_id), thumbnail=THUMBNAIL_URL.format(id=self.question_id), min_api_version=self.min_api_version, )
def sendClues(user_id, clueNumber, keyboard): clues = { 1:'firstclue-beta.jpg', 2:'secondclue-beta.jpg', 3:'thirdclue-beta.jpg', 4:'fourthclue-beta.jpg', 5:'fifthclue-beta.jpg' } message = PictureMessage(media = "https://grammarbuffet.org/static/viberhuntbot/assets/%s"%(clues[clueNumber]), text = "Find this place and send your location.", keyboard = keyboard) viber.send_messages(user_id, [message])
def test_creation(): picture_message = PictureMessage(tracking_data=SAMPLE_TRACKING_DATA, keyboard=SAMPLE_KEYBOARD, text=SAMPLE_TEXT, media=SAMPLE_MEDIA, thumbnail=SAMPLE_THUMBNAIL) assert picture_message.tracking_data == SAMPLE_TRACKING_DATA assert picture_message.keyboard == SAMPLE_KEYBOARD assert picture_message.media == SAMPLE_MEDIA assert picture_message.text == SAMPLE_TEXT assert picture_message.thumbnail == SAMPLE_THUMBNAIL
def __comeback__message__(self, user): messages = [ PictureMessage( text="С возвращением, " + user.name, media= 'https://static4.depositphotos.com/1000765/349/i/450/depositphotos_3491019' '-stock-photo-3d-small-empty-product-box.jpg'), TextMessage( text= 'Надеюсь ты не забыл, что я создан для того, чтобы помогать людям в изуение новых слов ' 'на английском языке') ] return messages + self.__help__message__()
def test_from_dict(): message_dict = dict(tracking_data=SAMPLE_TRACKING_DATA, keyboard=SAMPLE_KEYBOARD, text=SAMPLE_TEXT, media=SAMPLE_MEDIA, thumbnail=SAMPLE_THUMBNAIL) picture_message = PictureMessage().from_dict(message_dict) assert picture_message.tracking_data == SAMPLE_TRACKING_DATA assert picture_message.keyboard == SAMPLE_KEYBOARD assert picture_message.media == SAMPLE_MEDIA assert picture_message.text == SAMPLE_TEXT assert picture_message.thumbnail == SAMPLE_THUMBNAIL
def __hello__message__(self, user): messages = [ PictureMessage( text="Поздравляю тебя с подпиской, " + user.name, media= 'https://pngimage.net/wp-content/uploads/2018/06/%D1%87%D0%B5%D0%BB%D0%BE%D0' '%B2%D0%B5%D1%87%D0%BA%D0%B8-png-%D0%B4%D0%B5%D0%BD%D1%8C%D0%B3%D0%B8-2.png' ), TextMessage( text= 'Я создан для того, чтобы помогать людям в изучение новых слов на английском языке' ) ] return messages + self.__help__message__()
def test_to_dict(): message_dict = dict(type=MessageType.PICTURE, tracking_data=SAMPLE_TRACKING_DATA, keyboard=SAMPLE_KEYBOARD, text=SAMPLE_TEXT, media=SAMPLE_MEDIA, thumbnail=SAMPLE_THUMBNAIL) picture_message_dict = PictureMessage( tracking_data=SAMPLE_TRACKING_DATA, keyboard=SAMPLE_KEYBOARD, text=SAMPLE_TEXT, media=SAMPLE_MEDIA, thumbnail=SAMPLE_THUMBNAIL).to_dict() assert message_dict == picture_message_dict
def send_picture( self, picture: str, thumbnail: str = None, duration: int = None, text: str = None, keyboard: Keyboard = None, min_api_version=None, tracking_data: str = None): return self.api.send_message( to=self.sender.id, message = PictureMessage(tracking_data=tracking_data, keyboard=keyboard, text=text, media=picture, thumbnail=thumbnail, min_api_version=min_api_version ) )
def incoming(): logger.debug("received request. post data: {0}".format(request.get_data())) if not viber.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')): return Response(status=403) viber_request = viber.parse_request(request.get_data()) if isinstance(viber_request, ViberMessageRequest): user_id = viber_request.sender.id logger.debug("received interaction from user id: {}".format(user_id)) logger.debug("received interaction from user name: {}".format(viber_request.sender.name)) userStartedHunt = checkUserStatus(user_id) if userStartedHunt: currentClueNumber = getCurrentClueNumber(user_id) if viber_request.message._message_type == 'text': if viber_request.message.text.lower() == 'get a clue': sendClues(user_id, currentClueNumber,keyboardResponse) elif viber_request.message.text.lower() == 'see some phrases': sendPhrases(user_id, keyboardResponse) elif viber_request.message.text.lower() == 'send location': message = TextMessage(text='tap "..." below and select "Send Location" from the menu', keyboard=keyboardResponse) viber.send_messages(user_id, [ message ]) else: message = TextMessage(text='sorry, if you think you\'re at the right place, try sending your location again. Press "get a clue" to see the clue again', keyboard=keyboardResponse) viber.send_messages(user_id, [ message ]) elif viber_request.message._message_type == 'location': longitude = viber_request.message.location.longitude latitude = viber_request.message.location.latitude currentClueNumber = getCurrentClueNumber(user_id) correctCoordinates = checkLocation(currentClueNumber) if (abs(longitude - correctCoordinates['lon']) < .001) and (abs(latitude - correctCoordinates['lat']) < .001): clueNumber = getNextClueNumber(user_id) if clueNumber == 0: message = PictureMessage(media="https://grammarbuffet.org/static/viberhuntbot/assets/congrats.jpg", text = "Hurray! You finished!",keyboard = finalKeyboardResponse) viber.send_messages(user_id, [ message ]) else: message = TextMessage(text = 'You found the place! Here\'s your next clue...') viber.send_messages(user_id, [ message ]) sendClues(user_id, clueNumber, keyboardResponse) else: message = TextMessage(text = 'sorry, you haven\'t found it yet. Ask somebody else and try to find the correct place. Then send your location.', keyboard = keyboardResponse) viber.send_messages(user_id, [ message ]) else: message = TextMessage(text = 'I\'m not sure about that. Try tapping one of the buttons below or sending your location', keyboard = keyboardResponse) viber.send_messages(user_id, [ message ]) else: if viber_request.message._message_type == 'text': if viber_request.message.text.lower() == 'get a clue': clueNumber = getNextClueNumber(user_id) sendClues(user_id, clueNumber, keyboardResponse) elif viber_request.message.text.lower() == 'see some phrases': sendPhrases(user_id, initialKeyboardResponse) else: message = TextMessage(text = 'would you like to start the treasure hunt, or see some phrases for asking directions?', keyboard=initialKeyboardResponse) viber.send_messages(user_id, [ message ]) elif viber_request.message._message_type == 'location': message = TextMessage(text ='you haven\'t seen the first clue yet', keyboard = initialKeyboardResponse) viber.send_messages(user_id, [ message ]) else: message = TextMessage(text = 'I\'m not sure about that. Try tapping one of the buttons below to see the first clue or see some phrases for asking directions', keyboard = initialKeyboardResponse) viber.send_messages(user_id, [ message ]) elif isinstance(viber_request, ViberSubscribedRequest): logger.debug("received subscribed request from user id: {}".format(viber_request.get_user.id)) logger.debug("received subscribed request from user name: {}".format(viber_request.get_user.name)) viber.send_messages(viber_request.get_user.id, [ TextMessage(text = 'you are now subscribed to the treasure hunt!') ]) elif isinstance(viber_request, ViberFailedRequest): logger.warn('client failed receiving message. failure: {0}'.format(viber_request)) return Response(status = 200)
def callback(request): if request.method == 'POST': viber_request = viber.parse_request(request.body) if isinstance(viber_request, ViberConversationStartedRequest): viber.send_messages(viber_request.user.id, [TextMessage(text='Вас приветствует бот!')]) elif isinstance(viber_request, ViberSubscribedRequest): # user_detail = viber.get_user_details(viber_request.user.id) # ViberUser.objects.update_or_create(viber_id=viber_request.user.id, # name=viber_request.user.name, # language=viber_request.user.language, # country=viber_request.user.country, # api_version=viber_request.user.api_version, # defaults={'is_active': True}) viber.send_messages(viber_request.user.id, [TextMessage(text='Thanks')]) elif isinstance(viber_request, ViberMessageRequest): if isinstance(viber_request.message, TextMessage): ViberUser.objects.update_or_create( viber_id=viber_request.sender.id, name=viber_request.sender.name, language=viber_request.sender.language, country=viber_request.sender.country, api_version=viber_request.sender.api_version, defaults={'is_active': True}) keyboard_home = { "Type": "keyboard", "Buttons": [ { "Columns": 3, "Rows": 1, "Text": "Prezentacje", "ActionType": "reply", "ActionBody": "prezentacje", }, { "Columns": 3, "Rows": 1, "Text": "Wydarzenia", "ActionType": "reply", "ActionBody": "wydarzenia", }, { "Columns": 3, "Rows": 1, "Text": "Zmartwiony", "ActionType": "reply", "ActionBody": "zmartwiony", }, { "Columns": 3, "Rows": 1, "Text": "Uczyć się polskiego", "ActionType": "reply", "ActionBody": "uczyć się polskiego", }, { "Columns": 3, "Rows": 1, "Text": "Rozkład jazdy", "ActionType": "reply", "ActionBody": "rozkład jazdy", }, { "Columns": 3, "Rows": 1, "Text": "Jesteśmy", "ActionType": "reply", "ActionBody": "jesteśmy", }, ] } # keyboard_home = { # "Type": "keyboard", # "Buttons": [{ # "Columns": 3, # "Rows": 1, # "Text": "locations", # "ActionType": "location-picker", # "ActionBody": "", # # }] # } message = KeyboardMessage(tracking_data='tracking_data', keyboard=keyboard_home) viber.send_messages(viber_request.sender.id, [message]) keyboard_exit = { "Type": "keyboard", "Buttons": [{ "Columns": 6, "Rows": 1, "Text": "Wróć", "ActionType": "reply", "ActionBody": "wróć", }] } if str(viber_request.message.text) == 'prezentacje': # keyboard_exit = { # "Type": "keyboard", # "Buttons": [{ # "Columns": 6, # "Rows": 1, # "Text": "Wróć", # "ActionType": "reply", # "ActionBody": "wróć", # # }] # } keyboard_message = KeyboardMessage( tracking_data='tracking_data', keyboard=keyboard_exit) message = URLMessage( media= "https://drive.google.com/open?id=1iirBXn0AXtddNkVv-OX5bwbzWwjErjYw" ) viber.send_messages(viber_request.sender.id, [message, keyboard_message]) elif str(viber_request.message.text) == 'wydarzenia': keyboard_message = KeyboardMessage( tracking_data='tracking_data', keyboard=keyboard_exit) message = PictureMessage( media='https://5fd86f1e.ngrok.io/media/marafon2.jpg', text="") viber.send_messages(viber_request.sender.id, [message, keyboard_message]) elif isinstance(viber_request.message, LocationMessage): location = str(viber_request.message.location) lat = re.search('(?:lat=)(.................)', location) lon = re.search('(?:lon=)(.................)', location) location_user = {'lat': '', 'lon': ''} if lat: location_user['lat'] = lat[1] if lon: location_user['lon'] = lon[1] list_object(location_user['lat'], location_user['lon'], 1, viber_request.sender.id) # if isinstance(viber_request, ViberMessageRequest): # message = viber_request.message # text = message.text # text = text.split('|') # text_type = text[0] # text_message = '' # SAMPLE_KEYBOARD = { # "Type": "keyboard", # "Buttons": [{ # "Columns": 2, # "Rows": 2, # "Text": "<br><font color=\"#494E67\"><b>ASIAN</b></font>", # "TextSize": "large", # "TextHAlign": "center", # "TextVAlign": "middle", # "ActionType": "reply", # "ActionBody": "ASIAN", # "BgColor": "#f7bb3f", # "Image": "https://s18.postimg.org/9tncn0r85/sushi.png" # }, { # "Columns": 2, # "Rows": 2, # "Text": "<br><font color=\"#494E67\"><b>FRENCH</b></font>", # "TextSize": "large", # "TextHAlign": "center", # "TextVAlign": "middle", # "ActionType": "open-url", # "ActionBody": "tel:+380966600745", # "BgColor": "#7eceea", # "Image": "https://s18.postimg.org/ntpef5syd/french.png" # }, { # "Columns": 2, # "Rows": 2, # "Text": "<br><font color=\"#494E67\"><b>MEXICAN</b></font>", # "TextSize": "large", # "TextHAlign": "center", # "TextVAlign": "middle", # "ActionType": "reply", # "ActionBody": "Mexican", # "BgColor": "#f6f7f9", # "Image": "https://s18.postimg.org/t8y4g4kid/mexican.png" # }, { # "Columns": 2, # "Rows": 2, # "Text": "<br><font color=\"#494E67\"><b>ITALIAN</b></font>", # "TextSize": "large", # "TextHAlign": "center", # "TextVAlign": "middle", # "ActionType": "reply", # "ActionBody": "Italian", # "BgColor": "#dd8157", # "Image": "https://s18.postimg.org/x41iip3o5/itallian.png" # }, { # "Columns": 2, # "Rows": 2, # "Text": "<br><font color=\"#494E67\"><b>INDIE</b></font>", # "TextSize": "large", # "TextHAlign": "center", # "TextVAlign": "middle", # "ActionType": "reply", # "ActionBody": "Indie", # "BgColor": "#f6f7f9", # "Image": "https://s18.postimg.org/wq06j3jkl/indi.png" # }, { # "Columns": 2, # "Rows": 2, # "Text": "<br><font color=\"#494E67\"><b>MORE</b></font>", # "TextSize": "large", # "TextHAlign": "center", # "TextVAlign": "middle", # "ActionType": "reply", # "ActionBody": "More", # "BgColor": "#a8aaba", # "Image": "https://s18.postimg.org/ylmyu98et/more_Options.png", # # }] # } # text_message = TextMessage(text='Это бот') # message = KeyboardMessage(tracking_data='tracking_data', keyboard=SAMPLE_KEYBOARD) # # viber.send_messages(viber_request.sender.id, [ # text_message, message # ]) # # if text_type == 'More': # 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 = RichMediaMessage(rich_media=SAMPLE_RICH_MEDIA, alt_text=SAMPLE_ALT_TEXT, min_api_version=2) # viber.send_messages(viber_request.sender.id, [ # message # ]) # print(viber_request.sender.api_version) # # elif text_type == 'Asian': # viber.send_messages(viber_request.sender.id, [ # TextMessage(text='Asian') # ]) # # elif text_type == 'Mexican': # viber.send_messages(viber_request.sender.id, [ # TextMessage(text='Mexican') # ]) # # # elif isinstance(viber_request, ViberConversationStartedRequest): # print(viber_request) # viber.send_messages(viber_request.user.id, [ # TextMessage(text="Welcome!") # ]) return HttpResponse(status=200)
def Message(t_bot, v_bot, message, user): settings = db_settings.find_one() if user['messenger'] == "viber": # Пользователь написал из вайбера if user['operator']['active session'] is None: # Сообщение поступает в чат операторов link = f"https://t.me/{t_bot.get_me().username}?start={user['system id']}" keyboard = types.InlineKeyboardMarkup() keyboard.add(types.InlineKeyboardButton(text="Ответить пользователю", url=link)) #logging.info(message) if isinstance(message.message, PictureMessage): t_bot.send_photo(settings["main_id"], message.message.media, caption=f"{user['name']}, ({user['messenger']}) прислал изображение", reply_markup=keyboard) return True out = f"{user['name']}, ({user['messenger']}) прислал сообщение:\n{message.message.text}" t_bot.send_message(settings["main_id"], out, reply_markup=keyboard) return True else: # Диалог tolker = db_users.find_one({"system id": user['operator']['active session']}) if isinstance(message.message, PictureMessage): t_bot.send_photo(tolker['_id'], message.message.media, caption=f"{user['name']}, ({user['messenger']}) прислал изображение") return True out = f"{user['name']}, ({user['messenger']}) прислал сообщение:\n{message.message.text}" t_bot.send_message(tolker["_id"], out) return True elif user['messenger'] == "telegram": # Пользователь написал из телеги if user['operator']['active session'] is None: # Сообщение поступает в чат операторов link = f"https://t.me/{t_bot.get_me().username}?start={user['system id']}" keyboard = types.InlineKeyboardMarkup() keyboard.add(types.InlineKeyboardButton(text="Ответить пользователю", url=link)) if message.content_type == 'photo': t_bot.send_photo(settings["main_id"], message.photo[-1].file_id, caption=f"{user['name']}, ({user['messenger']}) прислал изображение", reply_markup=keyboard) return True out = f"{user['name']} ({user['messenger']}) прислал сообщение:\n{message.text}" t_bot.send_message(settings["main_id"], out, reply_markup=keyboard) return True else: # Диалог tolker = db_users.find_one({"system id": user['operator']['active session']}) if message.content_type == 'photo': if tolker["messenger"] == "telegram": if user["admin"] >= 1: t_bot.send_photo(tolker["_id"], message.photo[-1].file_id, caption=user['name']) else: t_bot.send_photo(tolker["_id"], message.photo[-1].file_id, caption=f"{user['name']}, ({user['messenger']}) прислал изображение") return True elif tolker["messenger"] == "viber": photo_id = t_bot.get_file(message.photo[-1].file_id) photo_name = photo_id.file_id file = f'https://api.telegram.org/file/bot{cfg.token}/{photo_id.file_path}' h = httplib2.Http('.cache') response, content = h.request(file) out = open(f'./pic/{photo_name}.jpg', 'wb') out.write(content) out.close() viber = Api(BotConfiguration(name=user['operator']['name'], avatar=cfg.v_avatar, auth_token=cfg.v_token)) viber.send_messages(tolker['_id'], [ PictureMessage(media=f"https://bot.vizit-net.com/new/pics/{photo_name}.jpg")]) out = f'''Изображение отправлено {tolker['name']} ({tolker['messenger']})''' t_bot.send_message(message.chat.id, out) return True if tolker["messenger"] == "telegram": answer = f"{user['name']}, ({user['messenger']}) прислал сообщение:\n{message.text}" if user["admin"] >= 1: answer = f"{user['operator']['name']}\n{message.text}" t_bot.send_message(tolker['_id'], answer) return True elif tolker["messenger"] == "viber": try: viber = Api(BotConfiguration(name=user['operator']['name'], avatar=cfg.v_avatar, auth_token=cfg.v_token)) viber.send_messages(tolker["_id"], [TextMessage(text=message.text)]) except Exception as error: logging.exception(f"Error: {error}") return True return False