Skip to content

Commit

Permalink
demos: add dynamic_keyboard demo
Browse files Browse the repository at this point in the history
  • Loading branch information
Themanwhosmellslikesugar authored and warewarewapain committed Aug 29, 2024
1 parent 291f558 commit 2cfe939
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
7 changes: 7 additions & 0 deletions demos/dynamic_keyboard/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Dynamic keyboard demo

To run the demo use the following command:

```bash
env PYTHONPATH=$(pwd) HAMMETT_SETTINGS_MODULE=demos.dynamic_keyboard.settings TOKEN=your-token python3 demos/dynamic_keyboard/demo.py
```
3 changes: 3 additions & 0 deletions demos/dynamic_keyboard/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""The module contains a bot that is intended to demonstrate how to
create and work with a dynamic keyboard.
"""
59 changes: 59 additions & 0 deletions demos/dynamic_keyboard/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""The module is a script to run the bot."""

from hammett.core import Button
from hammett.core.application import Application
from hammett.core.constants import DEFAULT_STATE, RenderConfig, SourcesTypes
from hammett.core.handlers import register_button_handler
from hammett.core.mixins import StartMixin


async def request_dynamic_keyboard(handler): # noqa: RUF029
"""Emulate an API request, pass a payload and return the keyboard."""
buttons = range(3) # do some API request

return [
[Button(
f'Button {button_num + 1}',
handler,
source_type=SourcesTypes.HANDLER_SOURCE_TYPE,
payload=f"You pressed button number {button_num + 1}, I'm right?",
)]
for button_num in buttons
]


class MainMenu(StartMixin):
"""The class implements Main menu screen."""

description = 'Just press any button'

async def add_default_keyboard(self, _update, _context):
"""Set up the default keyboard for the screen."""
return await request_dynamic_keyboard(self.handle_button_click)

@register_button_handler
async def handle_button_click(self, update, context):
"""Handle a button click by getting text from the payload and
passing it as a new description.
"""
payload = await self.get_payload(update, context)

await self.render(update, context, config=RenderConfig(description=payload))
return DEFAULT_STATE


def main():
"""Run the bot."""
name = 'dynamic_keyboard'
app = Application(
name,
entry_point=MainMenu,
states={
DEFAULT_STATE: [MainMenu],
},
)
app.run()


if __name__ == '__main__':
main()
5 changes: 5 additions & 0 deletions demos/dynamic_keyboard/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""The module contains the settings of the demo."""

import os

TOKEN = os.getenv('TOKEN', '')

0 comments on commit 2cfe939

Please sign in to comment.