-
Notifications
You must be signed in to change notification settings - Fork 323
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* VkKeyboard + api version 5.80 * Refactor; Use six module
- Loading branch information
Showing
13 changed files
with
158 additions
and
21 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
VkKeyboard | ||
======= | ||
|
||
Модуль для удобного создания клавиатур для ботов | ||
|
||
.. module:: vk_api.keyboard | ||
.. autoclass:: VkKeyboard | ||
:members: | ||
.. autoclass:: KeyboardColor | ||
:members: |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# -*- coding: utf-8 -*- | ||
import vk_api | ||
from vk_api.keyboard import KeyboardColor | ||
|
||
|
||
def main(): | ||
""" Пример создания клавиатуры для отправки ботом """ | ||
|
||
vk_session = vk_api.VkApi(token='bot_api_token') | ||
vk = vk_session.get_api() | ||
|
||
keyboard = vk_api.VkKeyboard(one_time=True) | ||
|
||
keyboard.add_button('Белая кнопка', color=KeyboardColor.DEFAULT) | ||
keyboard.add_button('Зелёная кнопка', color=KeyboardColor.POSITIVE) | ||
|
||
keyboard.add_line() # Переход на вторую строку | ||
keyboard.add_button('Красная кнопка', color=KeyboardColor.NEGATIVE) | ||
|
||
keyboard.add_line() | ||
keyboard.add_button('Синяя кнопка', color=KeyboardColor.PRIMARY) | ||
|
||
vk.messages.send( | ||
peer_id=123456, | ||
message='Пример клавиатуры', | ||
keyboard=keyboard.get_keyboard() | ||
) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
beautifulsoup4 | ||
requests | ||
enum34 | ||
six |
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
from enum import Enum | ||
|
||
import six | ||
|
||
from .utils import sjson_dumps | ||
|
||
|
||
class KeyboardColor(Enum): | ||
""" Возможные цвета кнопок """ | ||
PRIMARY = 'primary' # синяя | ||
DEFAULT = 'default' # белая | ||
NEGATIVE = 'negative' # красная | ||
POSITIVE = 'positive' # зелёная | ||
|
||
|
||
class VkKeyboard(object): | ||
""" Класс для создания клавиатуры для бота (https://vk.com/dev/bots_docs_3) | ||
:param one_time: Если True, клавиатура исчезнет после нажатия на кнопку | ||
:type one_time: bool | ||
""" | ||
|
||
__slots__ = ('one_time', 'lines', 'keyboard') | ||
|
||
def __init__(self, one_time=False): | ||
self.one_time = one_time | ||
self.lines = [[]] | ||
|
||
self.keyboard = { | ||
'one_time': self.one_time, | ||
'buttons': self.lines | ||
} | ||
|
||
def get_keyboard(self): | ||
""" Получить json клавиатуры """ | ||
return sjson_dumps(self.keyboard) | ||
|
||
@classmethod | ||
def get_empty_keyboard(cls): | ||
""" Получить json пустой клавиатуры. | ||
Если отправить пустую клавиатуру, текущая у пользователя исчезнет. | ||
""" | ||
keyboard = cls() | ||
keyboard.keyboard['buttons'] = [] | ||
return keyboard.get_keyboard() | ||
|
||
def add_button(self, label, color=KeyboardColor.DEFAULT, payload=None): | ||
""" Добавить кнопку. Максимальное количество кнопок на строке - 4 | ||
:param label: Надпись на кнопке и текст, отправляющийся при её нажатии. | ||
:type: str | ||
:param color: цвет кнопки. | ||
:type color: KeyboardColor or str | ||
:param payload: Параметр для callback api | ||
:type payload: str or list or dict | ||
""" | ||
|
||
current_line = self.lines[-1] | ||
|
||
if len(current_line) >= 4: | ||
raise ValueError('Max 4 buttons on a line') | ||
|
||
color_value = color | ||
|
||
if isinstance(color, KeyboardColor): | ||
color_value = color_value.value | ||
|
||
if payload is not None and not isinstance(payload, six.string_types): | ||
payload = sjson_dumps(payload) | ||
|
||
current_line.append({ | ||
'color': color_value, | ||
'action': { | ||
'type': 'text', | ||
'payload': payload, | ||
'label': label, | ||
} | ||
}) | ||
|
||
def add_line(self): | ||
""" Создаёт новую строчку, на которой можно размещать кнопки. | ||
Максимальное количество строк - 10 | ||
""" | ||
|
||
if len(self.lines) >= 10: | ||
raise ValueError('Max 10 lines') | ||
|
||
self.lines.append([]) |
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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