|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +:authors: python273, Helow19274, klassik2k16 |
| 4 | +:license: Apache License, Version 2.0, see LICENSE file |
| 5 | +:copyright: (c) 2019 python273 |
| 6 | +""" |
| 7 | + |
| 8 | +from enum import Enum |
| 9 | + |
| 10 | +import six |
| 11 | + |
| 12 | +from .utils import sjson_dumps |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +class VkKeyboardColor(Enum): |
| 18 | + """ Возможные цвета кнопок """ |
| 19 | + |
| 20 | + #: Синяя |
| 21 | + PRIMARY = 'primary' |
| 22 | + |
| 23 | + #: Белая |
| 24 | + DEFAULT = 'default' |
| 25 | + |
| 26 | + #: Красная |
| 27 | + NEGATIVE = 'negative' |
| 28 | + |
| 29 | + #: Зелёная |
| 30 | + POSITIVE = 'positive' |
| 31 | + |
| 32 | +class VkKeyboardButton(Enum): |
| 33 | + """ Возможные типы кнопки """ |
| 34 | + |
| 35 | + #: Кнопка с текстом |
| 36 | + TEXT = "text" |
| 37 | + |
| 38 | + #: Кнопка с местоположением |
| 39 | + LOCATION = "location" |
| 40 | + |
| 41 | + #: Кнопка с оплатой через VKPay |
| 42 | + VKPAY = "vkpay" |
| 43 | + |
| 44 | + #: Кнопка с приложением VK Apps |
| 45 | + VKAPPS = "open_app" |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +class VkKeyboard(object): |
| 50 | + """ Класс для создания клавиатуры для бота (https://vk.com/dev/bots_docs_3) |
| 51 | + :param one_time: Если True, клавиатура исчезнет после нажатия на кнопку |
| 52 | + :type one_time: bool |
| 53 | + """ |
| 54 | + |
| 55 | + __slots__ = ('one_time', 'lines', 'keyboard') |
| 56 | + |
| 57 | + def __init__(self, one_time=False): |
| 58 | + self.one_time = one_time |
| 59 | + self.lines = [[]] |
| 60 | + |
| 61 | + self.keyboard = { |
| 62 | + 'one_time': self.one_time, |
| 63 | + 'buttons': self.lines |
| 64 | + } |
| 65 | + |
| 66 | + def get_keyboard(self): |
| 67 | + """ Получить json клавиатуры """ |
| 68 | + return sjson_dumps(self.keyboard) |
| 69 | + |
| 70 | + @classmethod |
| 71 | + def get_empty_keyboard(cls): |
| 72 | + """ Получить json пустой клавиатуры. |
| 73 | + Если отправить пустую клавиатуру, текущая у пользователя исчезнет. |
| 74 | + """ |
| 75 | + keyboard = cls() |
| 76 | + keyboard.keyboard['buttons'] = [] |
| 77 | + return keyboard.get_keyboard() |
| 78 | + |
| 79 | + def add_button(self, label, color=VkKeyboardColor.DEFAULT, payload=None): |
| 80 | + """ Добавить кнопку с текстом. |
| 81 | + Максимальное количество кнопок на строке - 4 |
| 82 | +
|
| 83 | + :param label: Надпись на кнопке и текст, отправляющийся при её нажатии. |
| 84 | + :type label: str |
| 85 | + :param color: цвет кнопки. |
| 86 | + :type color: VkKeyboardColor or str |
| 87 | + :param payload: Параметр для callback api |
| 88 | + :type payload: str or list or dict |
| 89 | + """ |
| 90 | + |
| 91 | + current_line = self.lines[-1] |
| 92 | + |
| 93 | + if len(current_line) >= 4: |
| 94 | + raise ValueError('Max 4 buttons on a line') |
| 95 | + |
| 96 | + color_value = color |
| 97 | + |
| 98 | + if isinstance(color, VkKeyboardColor): |
| 99 | + color_value = color_value.value |
| 100 | + |
| 101 | + if payload is not None and not isinstance(payload, six.string_types): |
| 102 | + payload = sjson_dumps(payload) |
| 103 | + |
| 104 | + button_type = VkKeyboardButton.TEXT |
| 105 | + |
| 106 | + current_line.append({ |
| 107 | + 'color': color_value, |
| 108 | + 'action': { |
| 109 | + 'type': button_type, |
| 110 | + 'payload': payload, |
| 111 | + 'label': label, |
| 112 | + } |
| 113 | + }) |
| 114 | + |
| 115 | + def add_location_button(self, payload=None): |
| 116 | + """ Добавить кнопку с местоположением. |
| 117 | + Всегда занимает всю ширину линии. |
| 118 | +
|
| 119 | + :param payload: Параметр для callback api |
| 120 | + :type payload: str or list or dict |
| 121 | + """ |
| 122 | + |
| 123 | + current_line = self.lines[-1] |
| 124 | + |
| 125 | + if len(current_line) != 0: |
| 126 | + raise ValueError('This type of button takes the entire width of the line') |
| 127 | + |
| 128 | + if payload is not None and not isinstance(payload, six.string_types): |
| 129 | + payload = sjson_dumps(payload) |
| 130 | + |
| 131 | + button_type = VkKeyboardButton.LOCATION |
| 132 | + |
| 133 | + current_line.append({ |
| 134 | + 'action': { |
| 135 | + 'type': button_type, |
| 136 | + 'payload': payload |
| 137 | + } |
| 138 | + }) |
| 139 | + |
| 140 | + def add_vkpay_button(self, hash, payload=None): |
| 141 | + """ Добавить кнопку с оплатой с помощью VKPay. |
| 142 | + Всегда занимает всю ширину линии. |
| 143 | +
|
| 144 | + :param hash: Параметры платежа VKPay и ID приложения |
| 145 | + (в поле aid) разделённые & |
| 146 | + :type hash: str |
| 147 | + :param payload: Параметр для совместимости со старыми клиентами |
| 148 | + :type payload: str or list or dict |
| 149 | + """ |
| 150 | + |
| 151 | + current_line = self.lines[-1] |
| 152 | + |
| 153 | + if len(current_line) != 0: |
| 154 | + raise ValueError('This type of button takes the entire width of the line') |
| 155 | + |
| 156 | + if payload is not None and not isinstance(payload, six.string_types): |
| 157 | + payload = sjson_dumps(payload) |
| 158 | + |
| 159 | + button_type = VkKeyboardButton.VKPAY |
| 160 | + |
| 161 | + current_line.append({ |
| 162 | + 'action': { |
| 163 | + 'type': button_type, |
| 164 | + 'payload': payload, |
| 165 | + 'hash': hash |
| 166 | + } |
| 167 | + }) |
| 168 | + |
| 169 | + def add_vkapps_button(self, app_id, owner_id, label, hash, payload=None): |
| 170 | + """ Добавить кнопку с приложением VK Apps. |
| 171 | + Всегда занимает всю ширину линии. |
| 172 | +
|
| 173 | + :param app_id: Идентификатор вызываемого приложения с типом VK Apps |
| 174 | + :type app_id: int |
| 175 | + :param owner_id: Идентификатор сообщества, в котором установлено |
| 176 | + приложение, если требуется открыть в контексте сообщества |
| 177 | + :type owner_id: int |
| 178 | + :param label: Название приложения, указанное на кнопке |
| 179 | + :type label: str |
| 180 | + :param hash: хэш для навигации в приложении, будет передан в строке |
| 181 | + параметров запуска после символа # |
| 182 | + :type hash: str |
| 183 | + :param payload: Параметр для совместимости со старыми клиентами |
| 184 | + :type payload: str or list or dict |
| 185 | + """ |
| 186 | + |
| 187 | + current_line = self.lines[-1] |
| 188 | + |
| 189 | + if len(current_line) != 0: |
| 190 | + raise ValueError('This type of button takes the entire width of the line') |
| 191 | + |
| 192 | + if payload is not None and not isinstance(payload, six.string_types): |
| 193 | + payload = sjson_dumps(payload) |
| 194 | + |
| 195 | + button_type = VkKeyboardButton.VKAPPS |
| 196 | + |
| 197 | + current_line.append({ |
| 198 | + 'action': { |
| 199 | + 'type': button_type, |
| 200 | + 'app_id': app_id, |
| 201 | + 'owner_id': owner_id, |
| 202 | + 'label': label, |
| 203 | + 'payload': payload, |
| 204 | + 'hash': hash |
| 205 | + } |
| 206 | + }) |
| 207 | + |
| 208 | + def add_line(self): |
| 209 | + """ Создаёт новую строку, на которой можно размещать кнопки. |
| 210 | + Максимальное количество строк - 10. |
| 211 | + """ |
| 212 | + |
| 213 | + if len(self.lines) >= 10: |
| 214 | + raise ValueError('Max 10 lines') |
| 215 | + |
| 216 | + self.lines.append([]) |
0 commit comments