Skip to main content

Bot framework

Project description

TTAgent

Утилита для создания чат бота на базе SSE протокола. Переподключается при сетевых сбоях или временного отключения сервера. Для работы с АПИ, в т.ч. ответных постов, используется клиентская библиотека ttclient (устанавливается как зависимость).

INSTALL

Достаточно установить библиотеку ttagent

$ pip install ttagent

CODE

Create agent.py

from ttagent import Action, Post, TTAgent


class MyAgent(TTAgent):
    async def on_post(self, post: Post) -> None:
        ''' Вызывается, когда боту приходит пост '''
        post.user_id            # int, who send post
        post.user_unique_name   # str, who send post
        post.chat_id    # int, in what chat
        post.post_no    # int, post number
        post.team_id    # int | None, if chat from team
        post.text       # str, post text
        post.text_parsed    # list[dict], parsed post text
        post.attachments    # list[str], guids of attached files
        post.reply_no       # int, if post has reply to other post (number)
        post.reply_text     # str, if post has reply to other post (text)
        post.file_name      # str, if post is file filename here
        post.file_guid      # str, if post is file guid here

        # Отправляем ответ
        await self.client.send_post(post.chat_id, 'answer')

    async def on_action(self, action: Action) -> None:
        ''' Вызывается когда пользователь кликает по ссылке-экшену '''
        action.action   # str, action name
        action.params   # dict, params of action
        action.user_id          # int, who send post
        action.user_unique_name   # str, who send post
        action.chat_id    # int, in what chat
        action.post_no    # int, post number
        action.team_id    # int | None, if chat from team

    async def on_startup(self) -> None:
        '''
            Вызывается до подключения к потоку.
            Можно запустить веб-сервер или подключиться к БД.
        '''
        self.log.debug('Called on_startup handler')

    async def on_shutdown(self) -> None:
        '''
            Вызывается при завершении работы сервера.
            Можно корректно завершить работу с внешними ресурсами.
        '''
        self.log.debug('Called on_shutdown handler')

    async def on_connect(self) -> None:
        '''
            Открыто подключение к потоку, но сообщения еще не принимаются.
            Можно инициализировать/проверить ресурсы,
            которые могли отключиться за время простоя.
        '''
        self.log.debug('Called on_connect handler (retry: %s)', self._retry_counter)

    async def on_retry(self) -> None:
        '''
            Попытка переподключения к потоку, вызывается сразу после
            возникновения сбоя.
            Можно отправить уведомления в системы мониторинга.
        '''
        self.log.debug('Called on_retry handler (retry: %s)', self._retry_counter)

RUN

SECRET given when bot created

DOMAIN of server hostname

SECRET=<...> API_HOST=<hostname> ttagent example.agent:MyAgent

Запуск с uvx простого агента.

Нужно создать файл окружения cfg.env

export DOMAIN=example.com
export SECRET=1ni...ph7
export PYTHONPATH=.

Запускаем

uvx --env-file cfg.env ttagent agent:MyAgent

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ttagent-0.2.tar.gz (13.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ttagent-0.2-py3-none-any.whl (9.9 kB view details)

Uploaded Python 3

File details

Details for the file ttagent-0.2.tar.gz.

File metadata

  • Download URL: ttagent-0.2.tar.gz
  • Upload date:
  • Size: 13.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.10

File hashes

Hashes for ttagent-0.2.tar.gz
Algorithm Hash digest
SHA256 d6dcbda7196d847b91b59cd10ab0cb6bb8c3a9b17a94df30d25931540f5f9e13
MD5 6f6c8a773b2309efdcddaf0c1bbc7da8
BLAKE2b-256 d6787c29beb232ca4b144af2bb5893e87681516ec670caa282db70f3a4cc0bd7

See more details on using hashes here.

File details

Details for the file ttagent-0.2-py3-none-any.whl.

File metadata

  • Download URL: ttagent-0.2-py3-none-any.whl
  • Upload date:
  • Size: 9.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.10

File hashes

Hashes for ttagent-0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 07c579fe56105cfad75f80b2f528b20f98ca9aca28d86feca39768423798e17f
MD5 78fa50bf102c683fe797fe24eae9a4f7
BLAKE2b-256 a5d9fec30f3d94319e150126cf3efc8a61cdabf599ecad56878747fb69ec8331

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page