Last active
June 14, 2019 13:46
-
-
Save kurtgn/c84c7430f4cf7250292fc1fe47c2cadd to your computer and use it in GitHub Desktop.
несколько функций
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_buttons( | |
api_dict: dict, | |
message: Union[FBThreeButtonMessage, FBCarouselMessage] | |
) -> Iterable[dict]: | |
""" | |
Достать кнопки из api_dict. | |
Путь для доставания определяется типом сообщения. | |
Кнопки бывают только у двух типов сообщения, для остальных типов ничего не делаем | |
""" | |
if isinstance(message, FBCarouselMessage): | |
cards = api_dict['attachment']['payload']['elements'] | |
for card in cards: | |
if 'buttons' in card: | |
for button in card['buttons']: | |
yield button | |
else: | |
buttons = api_dict['payload']['buttons'] | |
for button in buttons: | |
yield button | |
flex_regex = re.compile(settings.FLEX_FULL_REGEX) | |
def patch_button(url_button_dict: dict) -> None: | |
""" | |
Добавить ключ 'messenger_extensions' в словарь с кнопкой, если нужно. | |
Сюда попадают только URL-кнопки, у которых есть ключ 'url' | |
""" | |
# является ли урл поддоменом флекса? | |
is_flex = flex_regex.match(url_button_dict['url']) | |
# Или находится в белом списке доменов платформы? | |
is_whitelisted = is_whitelisted_domain(url_button_dict['url']) | |
is_https = 'https://' in url_button_dict['url'] | |
if is_https and (is_flex or is_whitelisted): | |
url_button_dict['messenger_extensions'] = True | |
def api_dict_with_extensions(message: FBMessage) -> dict: | |
""" | |
Хелпер, который генерирует api_dict и в зависимости от урлов, | |
подложенных в кнопки, добавляет им messenger_extensions перед отправкой. | |
Это живет здесь, а не в state_objects, | |
потому что state_objects ничего не знают о настройках джанго | |
и о списке безопасных доменов. | |
""" | |
api_dict = message.api_dict() | |
if not isinstance(message, (FBCarouselMessage, FBThreeButtonMessage)): | |
return api_dict | |
# все кнопки типа web_url патчим | |
for button in get_buttons(api_dict, message): | |
if button['type'] == 'web_url': | |
patch_button(button) | |
return api_dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment