aiotraq-message 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.1
2
+ Name: aiotraq-message
3
+ Version: 0.1.0
4
+ Summary: aiotraq Plugin that supports interactive message sending using Streamlit-style syntax for traQ
5
+ Home-page: https://github.com/toshi-pono/aiotraq
6
+ License: MIT
7
+ Keywords: traQ,bot,message,aiotraq
8
+ Author: toshi00
9
+ Requires-Python: >=3.10,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: aiotraq (>=0.1.2,<0.2.0)
16
+ Requires-Dist: aiotraq-bot (>=0.1.2,<0.2.0)
17
+ Project-URL: Repository, https://github.com/toshi-pono/aiotraq
18
+ Project-URL: Source Code, https://github.com/toshi-pono/aiotraq/tree/main/libs/message
19
+ Description-Content-Type: text/markdown
20
+
21
+ # aiotraq-message
22
+
23
+ streamlit 風の構文を用いてインタラクティブなメッセージ送信に対応するプラグインです。
24
+
25
+ [![PyPI - Version](https://img.shields.io/pypi/v/aiotraq-message?label=aiotraq-message)](https://pypi.org/project/aiotraq-message/)
26
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/toshi-pono/aiotraq/blob/main/LICENSE)
27
+ [![CI](https://github.com/toshi-pono/aiotraq/actions/workflows/ci.yml/badge.svg)](https://github.com/toshi-pono/aiotraq/actions/workflows/ci.yml)
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install aiotraq-message
33
+ ```
34
+
35
+ ## Requirements
36
+
37
+ aiotraq-message は aiotraq に依存しています
38
+
39
+ - [aiotraq](https://github.com/toshi-pono/aiotraq/tree/main/libs/aiotraq)
40
+ - [aiotraq-bot](https://github.com/toshi-pono/aiotraq/tree/main/libs/bot)
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ import os
46
+ import asyncio
47
+ from aiotraq_bot import TraqHttpBot
48
+ from aiotraq_message import TraqMessage
49
+
50
+ async def component(am: TraqMessage, *args):
51
+ am.write("Hello, World!")
52
+
53
+ with am.spinner():
54
+ # heavy task
55
+ asyncio.sleep(3)
56
+
57
+ am.write(":done: Done!")
58
+
59
+ bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
60
+ response = TraqMessageManager(bot, os.getenv("BOT_ACCESS_TOKEN"), "https://q.trap.jp/api/v3")
61
+
62
+
63
+ @bot.event("MESSAGE_CREATED")
64
+ async def on_message_created(payload) -> None:
65
+ channel_id = payload.message.channelId
66
+
67
+ await response(component, channnel_id=channel_id)
68
+
69
+ if __name__ == "__main__":
70
+ bot.run()
71
+ ```
72
+
73
+ ### Component
74
+
75
+ write, spinner, clear などのメソッドを使うことができます
76
+
77
+ - write: メッセージを送信します
78
+ - spinner: スピナーを表示します
79
+ - clear: 送信したメッセージを空にします
80
+
81
+ ## License
82
+
83
+ This project is licensed under the terms of the MIT license.
84
+
@@ -0,0 +1,63 @@
1
+ # aiotraq-message
2
+
3
+ streamlit 風の構文を用いてインタラクティブなメッセージ送信に対応するプラグインです。
4
+
5
+ [![PyPI - Version](https://img.shields.io/pypi/v/aiotraq-message?label=aiotraq-message)](https://pypi.org/project/aiotraq-message/)
6
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/toshi-pono/aiotraq/blob/main/LICENSE)
7
+ [![CI](https://github.com/toshi-pono/aiotraq/actions/workflows/ci.yml/badge.svg)](https://github.com/toshi-pono/aiotraq/actions/workflows/ci.yml)
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install aiotraq-message
13
+ ```
14
+
15
+ ## Requirements
16
+
17
+ aiotraq-message は aiotraq に依存しています
18
+
19
+ - [aiotraq](https://github.com/toshi-pono/aiotraq/tree/main/libs/aiotraq)
20
+ - [aiotraq-bot](https://github.com/toshi-pono/aiotraq/tree/main/libs/bot)
21
+
22
+ ## Usage
23
+
24
+ ```python
25
+ import os
26
+ import asyncio
27
+ from aiotraq_bot import TraqHttpBot
28
+ from aiotraq_message import TraqMessage
29
+
30
+ async def component(am: TraqMessage, *args):
31
+ am.write("Hello, World!")
32
+
33
+ with am.spinner():
34
+ # heavy task
35
+ asyncio.sleep(3)
36
+
37
+ am.write(":done: Done!")
38
+
39
+ bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
40
+ response = TraqMessageManager(bot, os.getenv("BOT_ACCESS_TOKEN"), "https://q.trap.jp/api/v3")
41
+
42
+
43
+ @bot.event("MESSAGE_CREATED")
44
+ async def on_message_created(payload) -> None:
45
+ channel_id = payload.message.channelId
46
+
47
+ await response(component, channnel_id=channel_id)
48
+
49
+ if __name__ == "__main__":
50
+ bot.run()
51
+ ```
52
+
53
+ ### Component
54
+
55
+ write, spinner, clear などのメソッドを使うことができます
56
+
57
+ - write: メッセージを送信します
58
+ - spinner: スピナーを表示します
59
+ - clear: 送信したメッセージを空にします
60
+
61
+ ## License
62
+
63
+ This project is licensed under the terms of the MIT license.
@@ -0,0 +1,4 @@
1
+ from .manager import TraqMessageManager
2
+ from .message import TraqMessage
3
+
4
+ __all__ = ["TraqMessageManager", "TraqMessage"]
@@ -0,0 +1,144 @@
1
+ import asyncio
2
+ from dataclasses import dataclass
3
+ from datetime import datetime, timedelta
4
+ from aiotraq import AuthenticatedClient
5
+ from aiotraq.api.message import post_message, post_direct_message, edit_message
6
+ from aiotraq.models.post_message_request import PostMessageRequest
7
+ from aiotraq.models.message import Message
8
+ import uuid
9
+
10
+
11
+ WAIT_QUEUE = 0.01
12
+ REQUEST_RATE = 0.9
13
+
14
+
15
+ @dataclass
16
+ class InnerMessage:
17
+ id: str
18
+ message: str
19
+
20
+
21
+ class MessageEngine:
22
+ def __init__(
23
+ self,
24
+ client: AuthenticatedClient,
25
+ channel_id: str | None = None,
26
+ user_id: str | None = None,
27
+ embed: bool = False,
28
+ request_rate: float = REQUEST_RATE,
29
+ ):
30
+ self.client = client
31
+ self.updated_at: datetime | None = None
32
+ self.messages: list[InnerMessage] = []
33
+ self.message_id: str | None = None
34
+ self.channel_id = channel_id
35
+ self.user_id = user_id
36
+ self.embed = embed
37
+ self.request_rate = request_rate
38
+ self.event = asyncio.Event()
39
+ self.prev_message = ""
40
+ self.is_loop = True
41
+
42
+ def add_message(self, message: str) -> str:
43
+ """
44
+ message を追加する
45
+ """
46
+ message_id = str(uuid.uuid4())
47
+ self.messages.append(InnerMessage(id=message_id, message=message))
48
+ self.request_update()
49
+ return message_id
50
+
51
+ def remove_message(self, message_id: str) -> None:
52
+ """
53
+ message を削除する
54
+ """
55
+ self.messages = [msg for msg in self.messages if msg.id != message_id]
56
+ self.request_update()
57
+
58
+ def remove_all_message(self) -> None:
59
+ """
60
+ 全ての message を削除する
61
+ """
62
+ self.messages = []
63
+ self.request_update()
64
+
65
+ async def end(self) -> None:
66
+ self.is_loop = False
67
+
68
+ def request_update(self) -> None:
69
+ self.event.set()
70
+
71
+ async def task(self) -> None:
72
+ with self.client as c:
73
+ while self.is_loop:
74
+ await self.event.wait()
75
+ self.event.clear()
76
+ await self.__update_message(c)
77
+
78
+ await self.__fflush(c)
79
+
80
+ async def __fflush(self, c: AuthenticatedClient) -> None:
81
+ if self.updated_at is None:
82
+ self.updated_at = datetime.now()
83
+ await self.__init_send_message(c)
84
+ else:
85
+ self.updated_at = datetime.now()
86
+ await self.__update_send_message(c)
87
+
88
+ async def __update_message(self, c: AuthenticatedClient) -> None:
89
+ if self.updated_at is None:
90
+ await asyncio.sleep(WAIT_QUEUE)
91
+ self.updated_at = datetime.now()
92
+ await self.__init_send_message(c)
93
+ return
94
+
95
+ if datetime.now() - self.updated_at > timedelta(seconds=REQUEST_RATE):
96
+ await self.__update_send_message(c)
97
+ self.updated_at = datetime.now()
98
+ return
99
+
100
+ async def __init_send_message(self, c: AuthenticatedClient) -> None:
101
+ if self.channel_id is None and self.user_id is None:
102
+ return
103
+
104
+ body = PostMessageRequest(
105
+ content="\n".join([msg.message for msg in self.messages]),
106
+ embed=self.embed,
107
+ )
108
+ self.prev_message = body.content
109
+ if self.user_id is not None:
110
+ # DM
111
+ response = await post_direct_message.asyncio(
112
+ user_id=self.user_id,
113
+ client=c,
114
+ body=body,
115
+ )
116
+ if isinstance(response, Message):
117
+ self.message_id = response.id
118
+ elif self.channel_id is not None:
119
+ # Channel
120
+ response = await post_message.asyncio(
121
+ channel_id=self.channel_id,
122
+ client=c,
123
+ body=body,
124
+ )
125
+ if isinstance(response, Message):
126
+ self.message_id = response.id
127
+
128
+ async def __update_send_message(self, c: AuthenticatedClient) -> None:
129
+ if self.message_id is None:
130
+ return
131
+
132
+ body = PostMessageRequest(
133
+ content="\n".join([msg.message for msg in self.messages]),
134
+ embed=self.embed,
135
+ )
136
+ if self.prev_message == body.content:
137
+ # No change
138
+ return
139
+
140
+ await edit_message.asyncio_detailed(
141
+ message_id=self.message_id,
142
+ client=c,
143
+ body=body,
144
+ )
@@ -0,0 +1,63 @@
1
+ import asyncio
2
+ import threading
3
+ from typing import Callable, Any, Coroutine
4
+ from aiotraq_bot import TraqHttpBot
5
+ from aiotraq import AuthenticatedClient
6
+ from .message import TraqMessage
7
+ from .engine import MessageEngine
8
+
9
+
10
+ class TraqMessageManager:
11
+ """Create a new TraqMessageManager
12
+
13
+ Args:
14
+ bot (TraqHttpBot): TraqHttpBot instance
15
+ access_token (str): The access token for the bot
16
+ base_url (str): The base API URL for the bot
17
+
18
+ Example:
19
+ .. code-block:: python
20
+ from aiotraq_bot import TraqHttpBot
21
+ from aiotraq_message import TraqMessageManager
22
+
23
+ bot = TraqHttpBot(verification_token=BOT_VERIFICATION_TOKEN)
24
+ response = TraqMessageManager(bot, BOT_ACCESS_TOKEN, "https://q.trap.jp/api/v3")
25
+ """
26
+
27
+ def __init__(self, bot: TraqHttpBot, access_token: str, base_url: str):
28
+ self.bot = bot
29
+ self._access_token = access_token
30
+ self._base_url = base_url
31
+
32
+ async def __call__(
33
+ self,
34
+ component: Callable[[TraqMessage, tuple[Any, ...]], Coroutine[Any, Any, None]],
35
+ channnel_id: str | None = None,
36
+ user_id: str | None = None,
37
+ *args: Any,
38
+ ) -> None:
39
+ t = threading.Thread(target=self.__run, args=(component, channnel_id, user_id, *args), daemon=True)
40
+ t.start()
41
+ # joinを待たずに返す
42
+ return
43
+
44
+ def __run(
45
+ self,
46
+ component: Callable[[TraqMessage, tuple[Any, ...]], Coroutine[Any, Any, None]],
47
+ channnel_id: str | None = None,
48
+ user_id: str | None = None,
49
+ *args: Any,
50
+ ) -> None:
51
+ loop = asyncio.new_event_loop()
52
+ client = AuthenticatedClient(base_url=self._base_url, token=self._access_token)
53
+ asyncio.set_event_loop(loop)
54
+ engine = MessageEngine(client, channel_id=channnel_id, user_id=user_id, embed=False)
55
+ message = TraqMessage(engine)
56
+
57
+ # engine.taskをバックグラウンドで実行 -> (componentを実行 -> engine.end)を実行
58
+ async def component_task() -> None:
59
+ await component(message, *args)
60
+ await engine.end()
61
+
62
+ loop.run_until_complete(asyncio.gather(engine.task(), component_task()))
63
+ return
@@ -0,0 +1,60 @@
1
+ from contextlib import contextmanager
2
+ from typing import Any, Generator
3
+ from .engine import MessageEngine
4
+
5
+
6
+ class TraqMessage:
7
+ def __init__(self, engine: MessageEngine):
8
+ self.engine = engine
9
+ self.buttons: list[str] = []
10
+
11
+ def write(self, message: str) -> str:
12
+ """
13
+ message を追加する
14
+
15
+ Args:
16
+ message (str): メッセージ
17
+
18
+ Returns:
19
+ str: メッセージ ID
20
+
21
+ Examples:
22
+ .. code-block:: python
23
+ message_id = am.write("Hello, world!")
24
+ """
25
+ return self.engine.add_message(message)
26
+
27
+ def clear(self) -> None:
28
+ """
29
+ メッセージをすべて削除する
30
+ """
31
+ self.engine.remove_all_message()
32
+
33
+ def clear_message(self, message_id: str) -> None:
34
+ """
35
+ メッセージを削除する
36
+ """
37
+ self.engine.remove_message(message_id)
38
+
39
+ @contextmanager
40
+ def spinner(self, message: str = ":loading: loading...") -> Generator[str, Any, None]:
41
+ """
42
+ loading spinner を表示する
43
+
44
+ Args:
45
+ message (str): メッセージ
46
+
47
+ Yields:
48
+ str: ローディングメッセージ ID
49
+
50
+ Examples:
51
+ .. code-block:: python
52
+ with am.spinner():
53
+ # heavy process
54
+ await asyncio.sleep(5)
55
+ """
56
+ loading_id = self.engine.add_message(message)
57
+ try:
58
+ yield loading_id
59
+ finally:
60
+ self.engine.remove_message(loading_id)
File without changes
@@ -0,0 +1,53 @@
1
+ [tool.poetry]
2
+ name = "aiotraq-message"
3
+ version = "0.1.0"
4
+ description = "aiotraq Plugin that supports interactive message sending using Streamlit-style syntax for traQ"
5
+ authors = ["toshi00"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ repository = "https://github.com/toshi-pono/aiotraq"
9
+ packages = [{ include = "aiotraq_message" }]
10
+ include = ["aiotraq_message/py.typed"]
11
+ keywords = ["traQ", "bot", "message", "aiotraq"]
12
+
13
+
14
+ [tool.poetry.urls]
15
+ "Source Code" = "https://github.com/toshi-pono/aiotraq/tree/main/libs/message"
16
+
17
+
18
+ [tool.poetry.dependencies]
19
+ python = ">=3.10,<4.0"
20
+ aiotraq = "^0.1.2"
21
+ aiotraq-bot = "^0.1.2"
22
+
23
+ [tool.poetry.group.dev.dependencies]
24
+ mypy = "^1.10.0"
25
+ ruff = "^0.4.7"
26
+
27
+
28
+ [build-system]
29
+ requires = ["poetry-core>=1.0.0"]
30
+ build-backend = "poetry.core.masonry.api"
31
+
32
+
33
+ [tool.mypy]
34
+ show_error_context = true
35
+ show_column_numbers = true
36
+ ignore_missing_imports = true
37
+ disallow_untyped_defs = true
38
+ no_implicit_optional = true
39
+ warn_return_any = true
40
+ check_untyped_defs = true
41
+
42
+
43
+ [tool.ruff]
44
+ exclude = [".venv", "venv", "__pycache__", ".git"]
45
+
46
+ line-length = 120
47
+ indent-width = 4
48
+
49
+ [tool.ruff.format]
50
+ quote-style = "double"
51
+
52
+ [tool.ruff.lint.mccabe]
53
+ max-complexity = 10