antares-bot


Nameantares-bot JSON
Version 21.4 PyPI version JSON
download
home_pagehttps://github.com/Antares0982/antares-bot
SummaryA Telegram bot framework wrapping many things.
upload_time2024-09-01 14:36:45
maintainerNone
docs_urlNone
authorAntares0982
requires_python>=3.10
licenseNone
keywords python telegram bot api wrapper
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # AntaresBot
A Telegram bot framework wrapping many things.

### How to use

* `pip install antares_bot`. If you want to use pika for logging, `pip install antares_bot[pika]`
* Run `antares_bot` once in working directory to generate the `bot_cfg.py`
* Complete the `bot_cfg.py`
* Write your module in `modules` directory under working directory
* Run `antares_bot` to start your bot

### Examples

The documentation is far from completed, so here we only introduce a small part of features. We assume that you are already familiar with [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot).

Creating a bot with command `/echo`. First create a file `modules/echo.py`.

```python
from typing import TYPE_CHECKING

from antares_bot.module_base import TelegramBotModuleBase
from antares_bot.framework import command_callback_wrapper

if TYPE_CHECKING:
    from telegram import Update

    from antares_bot.context import RichCallbackContext


class Echo(TelegramBotModuleBase):
    def mark_handlers(self):
        return [self.echo]

    @command_callback_wrapper
    async def echo(self, update: "Update", context: "RichCallbackContext") -> bool:
        assert update.message is not None
        assert update.message.text is not None
        text = update.message.text.strip()
        if text.startswith("/echo"):
            text = text[len("/echo"):].strip()
        if text:
            await self.reply(text)
```

`antares_bot` will automatically scan the files under `modules` directory and find the class derived from `TelegramBotModuleBase`, with the same name pattern as the file (`CamelCase` for class name, `snake_case` for file name, for example: `my_example.py` corresponds to `class MyExample(TelegramBotModuleBase):`)

Module interfaces:

* Override `mark_handlers` to define the handlers. Handler wrappers can be found in `antares_bot.framework`.
* Override `do_init` to init. `__init__` is not recommanded.
* Override `post_init` to run some async function right after all modules are inited.
* Override `do_stop` to run some async function when exiting.

We use contexts to store the needed information for sending a message, so you only need to pass the message text when using the method `reply`.

Methods sending texts like `reply` (defined in `TelegramBotBaseWrapper`, `bot_method_wrapper.py`) have 4 different versions. These methods will automatically split the long text into parts, so it may send many messages. The original version returns id of the last message. V2 returns a list of ids of all messages (sorted). V3 returns the last `Message` object, and V4 returns all `Message` objects (sorted).

Creating a bot with command `/timer`

```python
import time
from typing import TYPE_CHECKING

from antares_bot.framework import command_callback_wrapper
from antares_bot.module_base import TelegramBotModuleBase
from antares_bot.context_manager import callback_job_wrapper


if TYPE_CHECKING:
    from telegram import Update

    from antares_bot.context import RichCallbackContext


class Timer(TelegramBotModuleBase):
    def mark_handlers(self):
        return [self.timer]

    @command_callback_wrapper
    async def timer(self, update: "Update", context: "RichCallbackContext") -> bool:
        assert update.message is not None
        assert update.message.text is not None

        @callback_job_wrapper
        async def cb(context_new):
            await self.reply("Time up!")
        self.job_queue.run_once(cb, 5, name=f"{time.time()}")
        return True
```

We use `callback_job_wrapper` to wrap the outer context for the nested function `cb`, and thus `reply` can reply to the correct message after 5 seconds.

i18n:

```python
from antares_bot.basic_language import BasicLanguage as Lang
await self.send_to(self.get_master_id(), Lang.t(Lang.UNKNOWN_ERROR))
```

You can define any i18n config like `Lang.UNKNOWN_ERROR`

```python
UNKNOWN_ERROR = {
    "zh-CN": "哎呀,出现了未知的错误呢……",
    "en": "Oops, an unknown error occurred...",
}
```

Call `set_lang` for each user to define their language.

Custom commands:

* `/exec` execute some python code (master only). `self` is defined to be the `TelegramBot` object in `bot_inst.py`.

  ```python
  /exec import objgraph
  return list(map(lambda x:x.misfire_grace_time, objgraph.by_type("Job")))
  # Execution succeeded, return value: [60, 60]
  ```

* `restart`, `stop` restart/stop the bot (master only). If `AntaresBotConfig.SYSTEMD_SERVICE_NAME` is configured, `/restart` will try to call `systemctl restart` for you. If `AntaresBotConfig.PULL_WHEN_STOP` is configured, these two commands will perform `git pull`.

* `get_id` see `/help get_id`.

* `help` check the docstring of command. For more information see `/help help`.

* `debug_mode` switch the logging level to `DEBUG` (master only).

Also, you can start the bot by yourself, without calling `antares_bot` in the command line.

```python
if __name__ == "__main__":
    from antares_bot import __main__
    inst = __main__.bootstrap()
    inst.run()
```



### Note

* Only support Python version >= 3.10


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Antares0982/antares-bot",
    "name": "antares-bot",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "python, telegram, bot, api, wrapper",
    "author": "Antares0982",
    "author_email": "Antares <antares@alyr.dev>",
    "download_url": "https://files.pythonhosted.org/packages/ff/b8/2f4251e6fa7d355a958ee5893eca50497fff65668551b94cc942e6ddb01a/antares_bot-21.4.tar.gz",
    "platform": "any",
    "description": "# AntaresBot\nA Telegram bot framework wrapping many things.\n\n### How to use\n\n* `pip install antares_bot`. If you want to use pika for logging, `pip install antares_bot[pika]`\n* Run `antares_bot` once in working directory to generate the `bot_cfg.py`\n* Complete the `bot_cfg.py`\n* Write your module in `modules` directory under working directory\n* Run `antares_bot` to start your bot\n\n### Examples\n\nThe documentation is far from completed, so here we only introduce a small part of features. We assume that you are already familiar with [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot).\n\nCreating a bot with command `/echo`. First create a file `modules/echo.py`.\n\n```python\nfrom typing import TYPE_CHECKING\n\nfrom antares_bot.module_base import TelegramBotModuleBase\nfrom antares_bot.framework import command_callback_wrapper\n\nif TYPE_CHECKING:\n    from telegram import Update\n\n    from antares_bot.context import RichCallbackContext\n\n\nclass Echo(TelegramBotModuleBase):\n    def mark_handlers(self):\n        return [self.echo]\n\n    @command_callback_wrapper\n    async def echo(self, update: \"Update\", context: \"RichCallbackContext\") -> bool:\n        assert update.message is not None\n        assert update.message.text is not None\n        text = update.message.text.strip()\n        if text.startswith(\"/echo\"):\n            text = text[len(\"/echo\"):].strip()\n        if text:\n            await self.reply(text)\n```\n\n`antares_bot` will automatically scan the files under `modules` directory and find the class derived from `TelegramBotModuleBase`, with the same name pattern as the file (`CamelCase` for class name, `snake_case` for file name, for example: `my_example.py` corresponds to `class MyExample(TelegramBotModuleBase):`)\n\nModule interfaces:\n\n* Override `mark_handlers` to define the handlers. Handler wrappers can be found in `antares_bot.framework`.\n* Override `do_init` to init. `__init__` is not recommanded.\n* Override `post_init` to run some async function right after all modules are inited.\n* Override `do_stop` to run some async function when exiting.\n\nWe use contexts to store the needed information for sending a message, so you only need to pass the message text when using the method `reply`.\n\nMethods sending texts like `reply` (defined in `TelegramBotBaseWrapper`, `bot_method_wrapper.py`) have 4 different versions. These methods will automatically split the long text into parts, so it may send many messages. The original version returns id of the last message. V2 returns a list of ids of all messages (sorted). V3 returns the last `Message` object, and V4 returns all `Message` objects (sorted).\n\nCreating a bot with command `/timer`\n\n```python\nimport time\nfrom typing import TYPE_CHECKING\n\nfrom antares_bot.framework import command_callback_wrapper\nfrom antares_bot.module_base import TelegramBotModuleBase\nfrom antares_bot.context_manager import callback_job_wrapper\n\n\nif TYPE_CHECKING:\n    from telegram import Update\n\n    from antares_bot.context import RichCallbackContext\n\n\nclass Timer(TelegramBotModuleBase):\n    def mark_handlers(self):\n        return [self.timer]\n\n    @command_callback_wrapper\n    async def timer(self, update: \"Update\", context: \"RichCallbackContext\") -> bool:\n        assert update.message is not None\n        assert update.message.text is not None\n\n        @callback_job_wrapper\n        async def cb(context_new):\n            await self.reply(\"Time up!\")\n        self.job_queue.run_once(cb, 5, name=f\"{time.time()}\")\n        return True\n```\n\nWe use `callback_job_wrapper` to wrap the outer context for the nested function `cb`, and thus `reply` can reply to the correct message after 5 seconds.\n\ni18n:\n\n```python\nfrom antares_bot.basic_language import BasicLanguage as Lang\nawait self.send_to(self.get_master_id(), Lang.t(Lang.UNKNOWN_ERROR))\n```\n\nYou can define any i18n config like `Lang.UNKNOWN_ERROR`\n\n```python\nUNKNOWN_ERROR = {\n    \"zh-CN\": \"\u54ce\u5440\uff0c\u51fa\u73b0\u4e86\u672a\u77e5\u7684\u9519\u8bef\u5462\u2026\u2026\",\n    \"en\": \"Oops, an unknown error occurred...\",\n}\n```\n\nCall `set_lang` for each user to define their language.\n\nCustom commands:\n\n* `/exec` execute some python code (master only). `self` is defined to be the `TelegramBot` object in `bot_inst.py`.\n\n  ```python\n  /exec import objgraph\n  return list(map(lambda x:x.misfire_grace_time, objgraph.by_type(\"Job\")))\n  # Execution succeeded, return value: [60, 60]\n  ```\n\n* `restart`, `stop` restart/stop the bot (master only). If `AntaresBotConfig.SYSTEMD_SERVICE_NAME` is configured, `/restart` will try to call `systemctl restart` for you. If `AntaresBotConfig.PULL_WHEN_STOP` is configured, these two commands will perform `git pull`.\n\n* `get_id` see `/help get_id`.\n\n* `help` check the docstring of command. For more information see `/help help`.\n\n* `debug_mode` switch the logging level to `DEBUG` (master only).\n\nAlso, you can start the bot by yourself, without calling `antares_bot` in the command line.\n\n```python\nif __name__ == \"__main__\":\n    from antares_bot import __main__\n    inst = __main__.bootstrap()\n    inst.run()\n```\n\n\n\n### Note\n\n* Only support Python version >= 3.10\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A Telegram bot framework wrapping many things.",
    "version": "21.4",
    "project_urls": {
        "Bug Tracker": "https://github.com/Antares0982/antares-bot/issues",
        "Download": "https://github.com/Antares0982/antares-bot",
        "Homepage": "https://github.com/Antares0982/antares-bot",
        "Source Code": "https://github.com/Antares0982/antares-bot"
    },
    "split_keywords": [
        "python",
        " telegram",
        " bot",
        " api",
        " wrapper"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ffb82f4251e6fa7d355a958ee5893eca50497fff65668551b94cc942e6ddb01a",
                "md5": "fc2ac5f4b7b87c5bdbb4c08e75ca5c96",
                "sha256": "60f426bb45c990f436317e83d73c6d325ea27399886dffe96093da8b1bff6988"
            },
            "downloads": -1,
            "filename": "antares_bot-21.4.tar.gz",
            "has_sig": false,
            "md5_digest": "fc2ac5f4b7b87c5bdbb4c08e75ca5c96",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 59915,
            "upload_time": "2024-09-01T14:36:45",
            "upload_time_iso_8601": "2024-09-01T14:36:45.964160Z",
            "url": "https://files.pythonhosted.org/packages/ff/b8/2f4251e6fa7d355a958ee5893eca50497fff65668551b94cc942e6ddb01a/antares_bot-21.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-01 14:36:45",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Antares0982",
    "github_project": "antares-bot",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "antares-bot"
}
        
Elapsed time: 1.34875s