aiotraq-bot 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,73 @@
1
+ Metadata-Version: 2.1
2
+ Name: aiotraq-bot
3
+ Version: 0.1.0
4
+ Summary: Async ready traQ Bot library
5
+ Home-page: https://github.com/toshi-pono/aiotraq
6
+ License: MIT
7
+ Keywords: traQ,bot,async,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: fastapi (>=0.100.0)
16
+ Requires-Dist: uvicorn[standard] (>=0.12.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/bot
19
+ Description-Content-Type: text/markdown
20
+
21
+ # aiotraq-bot
22
+
23
+ Async ready traQ Bot library written in Python.
24
+
25
+ ## Installation
26
+
27
+ TODO
28
+
29
+ ## Usage
30
+
31
+ ```python
32
+ import os
33
+ from aiotraq_bot import TraqHttpBot
34
+
35
+ bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
36
+
37
+ @bot.event()
38
+ async def on_message(payload: MessageCreatedPayload):
39
+ print(payload)
40
+
41
+ if __name__ == "__main__":
42
+ bot.run()
43
+ ```
44
+
45
+ ### Event handler の登録
46
+
47
+ イベントの登録は `@bot.event()` デコレータを使って行うことができます。
48
+ event の引数として対象のイベントを指定するか、関数の型ヒントを使って指定することができます。
49
+
50
+ `MESSAGE_CREATED` イベントを型ヒントを使って指定する場合
51
+
52
+ ```python
53
+ @bot.event()
54
+ async def on_message(payload: MessageCreatedPayload):
55
+ print(payload)
56
+ ```
57
+
58
+ `MESSAGE_CREATED`イベントを引数を用いて指定する場合
59
+
60
+ ```python
61
+ @bot.event("MESSAGE_CREATED")
62
+ async def on_message(payload):
63
+ print(payload)
64
+ ```
65
+
66
+ ## Acknowledgements
67
+
68
+ This project is inspired by [python-traq-bot](https://github.com/eyemono-moe/python-traq-bot).
69
+
70
+ ## License
71
+
72
+ This project is licensed under the terms of the MIT license.
73
+
@@ -0,0 +1,52 @@
1
+ # aiotraq-bot
2
+
3
+ Async ready traQ Bot library written in Python.
4
+
5
+ ## Installation
6
+
7
+ TODO
8
+
9
+ ## Usage
10
+
11
+ ```python
12
+ import os
13
+ from aiotraq_bot import TraqHttpBot
14
+
15
+ bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
16
+
17
+ @bot.event()
18
+ async def on_message(payload: MessageCreatedPayload):
19
+ print(payload)
20
+
21
+ if __name__ == "__main__":
22
+ bot.run()
23
+ ```
24
+
25
+ ### Event handler の登録
26
+
27
+ イベントの登録は `@bot.event()` デコレータを使って行うことができます。
28
+ event の引数として対象のイベントを指定するか、関数の型ヒントを使って指定することができます。
29
+
30
+ `MESSAGE_CREATED` イベントを型ヒントを使って指定する場合
31
+
32
+ ```python
33
+ @bot.event()
34
+ async def on_message(payload: MessageCreatedPayload):
35
+ print(payload)
36
+ ```
37
+
38
+ `MESSAGE_CREATED`イベントを引数を用いて指定する場合
39
+
40
+ ```python
41
+ @bot.event("MESSAGE_CREATED")
42
+ async def on_message(payload):
43
+ print(payload)
44
+ ```
45
+
46
+ ## Acknowledgements
47
+
48
+ This project is inspired by [python-traq-bot](https://github.com/eyemono-moe/python-traq-bot).
49
+
50
+ ## License
51
+
52
+ This project is licensed under the terms of the MIT license.
@@ -0,0 +1,3 @@
1
+ from .bot import TraqHttpBot
2
+
3
+ __all__ = ["TraqHttpBot"]
@@ -0,0 +1,184 @@
1
+ import inspect
2
+ from typing import Awaitable, Callable
3
+ from fastapi import FastAPI, Header, Response
4
+ from fastapi.responses import JSONResponse
5
+ from pydantic import ValidationError
6
+ import uvicorn
7
+
8
+ from .models import EventModel, convert_json_to_model, model_to_event_type
9
+
10
+
11
+ EventHandlerType = Callable[..., Awaitable[None]]
12
+
13
+
14
+ class TraqHttpBot:
15
+ """Create a new TraqHttpBot
16
+
17
+ Args:
18
+ verification_token (str): The verification token for the bot
19
+
20
+ Examples:
21
+ .. code-block:: python
22
+ import os
23
+ from aiotraq_bot import TraqHttpBot
24
+
25
+ bot = TraqHttpBot(verification_token=os.getenv("BOT_VERIFICATION_TOKEN"))
26
+
27
+ @bot.event()
28
+ async def on_message(payload: MessageCreatedPayload):
29
+ print(payload)
30
+
31
+ if __name__ == "__main__":
32
+ bot.run()
33
+ """
34
+
35
+ def __init__(self, verification_token: str | None):
36
+ self.verification_token = verification_token
37
+ self.handlers: dict[str, list[EventHandlerType]] = {
38
+ "PING": [],
39
+ "JOINED": [],
40
+ "LEFT": [],
41
+ "MESSAGE_CREATED": [],
42
+ "MESSAGE_DELETED": [],
43
+ "MESSAGE_UPDATED": [],
44
+ "DIRECT_MESSAGE_CREATED": [],
45
+ "DIRECT_MESSAGE_DELETED": [],
46
+ "DIRECT_MESSAGE_UPDATED": [],
47
+ "BOT_MESSAGE_STAMPS_UPDATED": [],
48
+ "CHANNEL_CREATED": [],
49
+ "CHANNEL_TOPIC_CHANGED": [],
50
+ "USER_CREATED": [],
51
+ "STAMP_CREATED": [],
52
+ "TAG_ADDED": [],
53
+ "TAG_REMOVED": [],
54
+ "USER_GROUP_CREATED": [],
55
+ "USER_GROUP_UPDATED": [],
56
+ "USER_GROUP_DELETED": [],
57
+ "USER_GROUP_MEMBER_ADDED": [],
58
+ "USER_GROUP_MEMBER_UPDATED": [],
59
+ "USER_GROUP_MEMBER_REMOVED": [],
60
+ "USER_GROUP_ADMIN_ADDED": [],
61
+ "USER_GROUP_ADMIN_REMOVED": [],
62
+ }
63
+
64
+ async def handle_event(self, json_data: dict, event: str, request_id: str) -> None:
65
+ payload = convert_json_to_model(json_data, event)
66
+ if event not in self.handlers:
67
+ return
68
+
69
+ for handler in self.handlers[event]:
70
+ sig = inspect.signature(handler)
71
+ # 変数名が payload または, dict もしくは eventPayload のアノテーション の引数に payload を渡す
72
+ # 変数名が event の引数に event を渡す
73
+ # 変数名が id の引数に id を渡す
74
+ params: dict[str, str | EventModel | None] = {}
75
+ for param in sig.parameters.values():
76
+ if param.name == "payload":
77
+ params[param.name] = payload
78
+ elif param.name == "event":
79
+ params[param.name] = event
80
+ elif param.name == "id":
81
+ params[param.name] = request_id
82
+ elif param.annotation == dict or model_to_event_type(param.annotation) is not None:
83
+ params[param.name] = payload
84
+ else:
85
+ params[param.name] = None
86
+
87
+ await handler(**params)
88
+
89
+ def _register_handler(self, event: str, func: EventHandlerType) -> None:
90
+ self.handlers[event].append(func)
91
+
92
+ def event(self, event: str | None = None) -> Callable[[EventHandlerType], EventHandlerType]:
93
+ """Register an event handler
94
+
95
+ Args:
96
+ event (str | None): The event to handle
97
+
98
+ Examples:
99
+ .. code-block:: python
100
+ @bot.event("MESSAGE_CREATED")
101
+ async def on_message_created(payload):
102
+ print(payload)
103
+
104
+ @bot.event()
105
+ async def on_ping(payload: MessageCreatedPayload):
106
+ print(payload)
107
+ """
108
+
109
+ def decorator(func: EventHandlerType) -> EventHandlerType:
110
+ if event is None:
111
+ # func の引数の型を見て event を決定する
112
+ sig = inspect.signature(func)
113
+ if len(sig.parameters) == 0:
114
+ raise ValueError("cannot determine event type")
115
+
116
+ params = list(sig.parameters.values())
117
+ for param in params:
118
+ ev_type = model_to_event_type(param.annotation)
119
+ if ev_type is not None:
120
+ self._register_handler(ev_type, func)
121
+ return func
122
+ raise ValueError("cannot determine event type")
123
+
124
+ elif event in self.handlers:
125
+ self._register_handler(event, func)
126
+ else:
127
+ raise ValueError(f"Invalid event: {event}")
128
+
129
+ return func
130
+
131
+ return decorator
132
+
133
+ def run(self, hostname: str = "0.0.0.0", port: int = 8080) -> None:
134
+ """Run the bot
135
+
136
+ Args:
137
+ hostname (str): The hostname to bind to (default: "0.0.0.0")
138
+ port (int): The port to bind to (default: 8080)
139
+ """
140
+ self.server = TraqHttpBotServer(hostname, port, self)
141
+ try:
142
+ self.server.run()
143
+ except KeyboardInterrupt:
144
+ pass
145
+
146
+
147
+ class TraqHttpBotServer:
148
+ def __init__(self, hostname: str, port: int, bot: TraqHttpBot):
149
+ self.hostname = hostname
150
+ self.port = port
151
+ self.bot = bot
152
+ self.app = FastAPI()
153
+
154
+ self.app.add_api_route("/", self.handle_bot_request, methods=["POST"])
155
+
156
+ async def handle_bot_request(
157
+ self,
158
+ json_data: dict,
159
+ x_traq_bot_token: str | None = Header(default=None),
160
+ x_traq_bot_event: str | None = Header(default=None),
161
+ x_traq_bot_request_id: str | None = Header(default=None),
162
+ ) -> Response:
163
+ if x_traq_bot_token != self.bot.verification_token:
164
+ print("Invalid verification token")
165
+ return JSONResponse(status_code=401, content={"message": "Invalid verification token"})
166
+ if x_traq_bot_event is None:
167
+ print("No X-TRAQ-BOT-EVENT")
168
+ return JSONResponse(status_code=400, content={"message": "No X-TRAQ-BOT-EVENT"})
169
+ if x_traq_bot_request_id is None:
170
+ print("No X-TRAQ-BOT-REQUEST-ID")
171
+ return JSONResponse(status_code=400, content={"message": "No X-TRAQ-BOT-REQUEST-ID"})
172
+
173
+ try:
174
+ await self.bot.handle_event(json_data, x_traq_bot_event, x_traq_bot_request_id)
175
+ return Response(status_code=204, content=None)
176
+ except ValidationError as e:
177
+ print(f"Validation error: {e}")
178
+ return JSONResponse(status_code=400, content={"message": "Validation error"})
179
+ except Exception as e:
180
+ print(f"Error handling event: {e}")
181
+ return JSONResponse(status_code=500, content={"message": "Error handling event"})
182
+
183
+ def run(self) -> None:
184
+ uvicorn.run(self.app, host=self.hostname, port=self.port)
@@ -0,0 +1,82 @@
1
+ from .event import (
2
+ BotMessageStampsUpdatedPayload,
3
+ ChannelCreatedPayload,
4
+ ChannelTopicChangedPayload,
5
+ DirectMessageCreatedPayload,
6
+ DirectMessageDeletedPayload,
7
+ DirectMessageUpdatedPayload,
8
+ JoinedPayload,
9
+ LeftPayload,
10
+ MessageCreatedPayload,
11
+ MessageDeletedPayload,
12
+ MessageUpdatedPayload,
13
+ PingPayload,
14
+ StampCreatedPayload,
15
+ TagAddedPayload,
16
+ TagRemovedPayload,
17
+ UserCreatedPayload,
18
+ UserGroupAdminAddedPayload,
19
+ UserGroupAdminRemovedPayload,
20
+ UserGroupCreatedPayload,
21
+ UserGroupDeletedPayload,
22
+ UserGroupMemberAddedPayload,
23
+ UserGroupMemberRemovedPayload,
24
+ UserGroupMemberUpdatedPayload,
25
+ UserGroupUpdatedPayload,
26
+ )
27
+ from .common import (
28
+ BasePayload,
29
+ ChannelPayload,
30
+ MessagePayload,
31
+ MessageStampPayload,
32
+ UserGroupAdminPayload,
33
+ UserGroupPayload,
34
+ UserPayload,
35
+ GroupMemberPayload,
36
+ )
37
+ from .event_models import (
38
+ EventModel,
39
+ EventModelType,
40
+ convert_json_to_model,
41
+ model_to_event_type,
42
+ )
43
+
44
+
45
+ __all__ = [
46
+ "BotMessageStampsUpdatedPayload",
47
+ "ChannelCreatedPayload",
48
+ "ChannelTopicChangedPayload",
49
+ "DirectMessageCreatedPayload",
50
+ "DirectMessageDeletedPayload",
51
+ "DirectMessageUpdatedPayload",
52
+ "JoinedPayload",
53
+ "LeftPayload",
54
+ "MessageCreatedPayload",
55
+ "MessageDeletedPayload",
56
+ "MessageUpdatedPayload",
57
+ "PingPayload",
58
+ "StampCreatedPayload",
59
+ "TagAddedPayload",
60
+ "TagRemovedPayload",
61
+ "UserCreatedPayload",
62
+ "UserGroupAdminAddedPayload",
63
+ "UserGroupAdminRemovedPayload",
64
+ "UserGroupCreatedPayload",
65
+ "UserGroupDeletedPayload",
66
+ "UserGroupMemberAddedPayload",
67
+ "UserGroupMemberRemovedPayload",
68
+ "UserGroupMemberUpdatedPayload",
69
+ "UserGroupUpdatedPayload",
70
+ "BasePayload",
71
+ "ChannelPayload",
72
+ "MessagePayload",
73
+ "MessageStampPayload",
74
+ "UserGroupAdminPayload",
75
+ "UserGroupPayload",
76
+ "UserPayload",
77
+ "GroupMemberPayload",
78
+ "EventModel",
79
+ "EventModelType",
80
+ "convert_json_to_model",
81
+ "model_to_event_type",
82
+ ]
@@ -0,0 +1,166 @@
1
+ from pydantic import BaseModel
2
+ import datetime
3
+
4
+
5
+ class BasePayload(BaseModel):
6
+ """共通部分
7
+
8
+ Attributes:
9
+ eventTime (datetime.datetime): イベント発生日時
10
+ """
11
+
12
+ eventTime: datetime.datetime
13
+
14
+
15
+ class UserPayload(BaseModel):
16
+ """ユーザー情報ペイロード
17
+
18
+ Attributes:
19
+ id (str): ユーザーUUId
20
+ name (str): ユーザーのtraQ Id
21
+ displayName (str): ユーザーの表示名
22
+ iconId (str): ユーザーアイコンのファイルUUId
23
+ bot (bool): ユーザーがBotかどうか
24
+ """
25
+
26
+ id: str
27
+ name: str
28
+ displayName: str
29
+ iconId: str
30
+ bot: bool
31
+
32
+
33
+ class ChannelPayload(BaseModel):
34
+ """チャンネル情報ペイロード
35
+
36
+ Attributes:
37
+ id (str): チャンネルUUId
38
+ name (str): チャンネル名
39
+ path (str): チャンネルパス
40
+ parentId (str): 親チャンネルのUUId, ルートチャンネルの場合は"00000000-0000-0000-0000-000000000000"
41
+ creator (UserPayload): チャンネル作成者
42
+ createdAt (datetime.datetime): チャンネル作成日時
43
+ updatedAt (datetime.datetime): チャンネル更新日時
44
+ """
45
+
46
+ id: str
47
+ name: str
48
+ path: str
49
+ parentId: str
50
+ creator: UserPayload
51
+ createdAt: datetime.datetime
52
+ updatedAt: datetime.datetime
53
+
54
+
55
+ class EmbeddedInfoPayload(BaseModel):
56
+ """メッセージ埋め込み情報
57
+
58
+ Attributes:
59
+ raw (str): 表示文字列
60
+ type (str): タイプ
61
+ id (str): 各種Id(タイプによる)
62
+ """
63
+
64
+ raw: str
65
+ type: str
66
+ id: str
67
+
68
+
69
+ class MessagePayload(BaseModel):
70
+ """メッセージ情報ペイロード
71
+
72
+ Attributes:
73
+ id (str): メッセージUUId
74
+ user (UserPayload): メッセージ投稿者
75
+ channelId (str): 投稿先チャンネルUUId
76
+ text (str): 生メッセージ本文
77
+ plainText (str): メッセージ本文(埋め込み情報・改行なし)
78
+ embedded (list[EmbeddedInfoPayload]): メッセージ埋め込み情報の配列
79
+ createdAt (datetime.datetime): メッセージ投稿日時
80
+ updatedAt (datetime.datetime): メッセージ更新日時
81
+ """
82
+
83
+ id: str
84
+ user: UserPayload
85
+ channelId: str
86
+ text: str
87
+ plainText: str
88
+ embedded: list[EmbeddedInfoPayload]
89
+ createdAt: datetime.datetime
90
+ updatedAt: datetime.datetime
91
+
92
+
93
+ class MessageStampPayload(BaseModel):
94
+ """メッセージスタンプ情報
95
+
96
+ Attributes:
97
+ stampId (str): スタンプUUId
98
+ userId (str): スタンプを押したユーザーUUId
99
+ count (int): このユーザーによって押されたこのスタンプの数
100
+ createdAt (datetime.datetime): 最初にスタンプが押された日時
101
+ updatedAt (datetime.datetime): 最後にスタンプが押された日時
102
+ """
103
+
104
+ stampId: str
105
+ userId: str
106
+ count: int
107
+ createdAt: datetime.datetime
108
+ updatedAt: datetime.datetime
109
+
110
+
111
+ class GroupMemberPayload(BaseModel):
112
+ """グループメンバー情報ペイロード
113
+
114
+ Attributes:
115
+ groupId (str): グループUUId
116
+ userId (str): ユーザーUUId
117
+ """
118
+
119
+ groupId: str
120
+ userId: str
121
+
122
+
123
+ class UserGroupAdminPayload(GroupMemberPayload):
124
+ """グループ管理者情報ペイロード"""
125
+
126
+ pass
127
+
128
+
129
+ class UserGroupMemberPayload(BaseModel):
130
+ """グループメンバー(のより詳細な)情報ペイロード
131
+
132
+ Attributes:
133
+ groupId (str): グループUUId
134
+ userId (str): ユーザーUUId
135
+ role (str): メンバーの役割
136
+ """
137
+
138
+ groupId: str
139
+ userId: str
140
+ role: str
141
+
142
+
143
+ class UserGroupPayload(BaseModel):
144
+ """グループ情報ペイロード
145
+
146
+ Attributes:
147
+ id (str): グループUUId
148
+ name (str): グループ名
149
+ description (str): グループの説明
150
+ type (str): グループの種類
151
+ icon (str): グループアイコンのファイルUUId
152
+ admins (list[UserGroupAdminPayload]): グループ管理者の配列
153
+ members (list[UserGroupMemberPayload]): グループメンバーの配列
154
+ createdAt (datetime.datetime): グループ作成日時
155
+ updatedAt (datetime.datetime): グループ更新日時
156
+ """
157
+
158
+ id: str
159
+ name: str
160
+ description: str
161
+ type: str
162
+ icon: str
163
+ admins: list[UserGroupAdminPayload]
164
+ members: list[UserGroupMemberPayload]
165
+ createdAt: datetime.datetime
166
+ updatedAt: datetime.datetime
@@ -0,0 +1,289 @@
1
+ from pydantic import BaseModel
2
+ from .common import (
3
+ BasePayload,
4
+ ChannelPayload,
5
+ MessagePayload,
6
+ MessageStampPayload,
7
+ UserGroupAdminPayload,
8
+ UserGroupPayload,
9
+ UserPayload,
10
+ GroupMemberPayload,
11
+ )
12
+
13
+
14
+ class PingPayload(BasePayload):
15
+ """PINGイベントペイロード"""
16
+
17
+ pass
18
+
19
+
20
+ class JoinedPayload(BasePayload):
21
+ """JOINEDイベントペイロード
22
+
23
+ Attributes:
24
+ channel (ChannelPayload): 参加したチャンネル
25
+ """
26
+
27
+ channel: ChannelPayload
28
+
29
+
30
+ class LeftPayload(BasePayload):
31
+ """LEFTイベントペイロード
32
+
33
+ Attributes:
34
+ channel (ChannelPayload): 退出したチャンネル
35
+ """
36
+
37
+ channel: ChannelPayload
38
+
39
+
40
+ class MessageCreatedPayload(BasePayload):
41
+ """MESSAGE_CREATEDイベントペイロード
42
+
43
+ Attributes:
44
+ message (MessagePayload): 投稿されたメッセージ
45
+ """
46
+
47
+ message: MessagePayload
48
+
49
+
50
+ class MessageUpdatedPayload(BasePayload):
51
+ """MESSAGE_UPDATEDイベントペイロード
52
+
53
+ Attributes:
54
+ message (MessagePayload): 更新されたメッセージ
55
+ """
56
+
57
+ message: MessagePayload
58
+
59
+
60
+ class DeletedMessage(BaseModel):
61
+ """削除されたメッセージ
62
+
63
+ Attributes:
64
+ id (str): メッセージUUID
65
+ channelId (str): 投稿先チャンネルUUID
66
+ """
67
+
68
+ id: str
69
+ channelId: str
70
+
71
+
72
+ class MessageDeletedPayload(BasePayload):
73
+ """MESSAGE_DELETEDイベントペイロード
74
+
75
+ Attributes:
76
+ message (DeletedMessage): 削除されたメッセージ
77
+ """
78
+
79
+ message: DeletedMessage
80
+
81
+
82
+ class BotMessageStampsUpdatedPayload(BasePayload):
83
+ """BOT_MESSAGE_STAMPS_UPDATEDイベントペイロード
84
+
85
+ Attributes:
86
+ messageId (str): スタンプの更新があったメッセージUUID
87
+ stamps (list[MessageStampPayload]): メッセージに現在ついている全てのスタンプ
88
+ """
89
+
90
+ messageId: str
91
+ stamps: list[MessageStampPayload]
92
+
93
+
94
+ class DirectMessageCreatedPayload(BasePayload):
95
+ """DIRECT_MESSAGE_CREATEDイベントペイロード
96
+
97
+ Attributes:
98
+ message (MessagePayload): 投稿されたメッセージ
99
+ """
100
+
101
+ message: MessagePayload
102
+
103
+
104
+ class DirectMessageUpdatedPayload(BasePayload):
105
+ """DIRECT_MESSAGE_UPDATEDイベントペイロード
106
+
107
+ Attributes:
108
+ message (MessagePayload): 更新されたメッセージ
109
+ """
110
+
111
+ message: MessagePayload
112
+
113
+
114
+ class DeletedDirectMessage(BaseModel):
115
+ """削除されたダイレクトメッセージ
116
+
117
+ Attributes:
118
+ id (str): メッセージUUID
119
+ userId (str): DMの宛先ユーザーUUID
120
+ channelId (str): 投稿先チャンネルUUID
121
+ """
122
+
123
+ id: str
124
+ userId: str
125
+ channelId: str
126
+
127
+
128
+ class DirectMessageDeletedPayload(BasePayload):
129
+ """DIRECT_MESSAGE_DELETEDイベントペイロード
130
+
131
+ Attributes:
132
+ message (DeletedDirectMessage): 削除されたメッセージ
133
+ """
134
+
135
+ message: DeletedDirectMessage
136
+
137
+
138
+ class ChannelCreatedPayload(BasePayload):
139
+ """CHANNEL_CREATEDイベントペイロード
140
+
141
+ Attributes:
142
+ channel (ChannelPayload): 作成されたチャンネル
143
+ """
144
+
145
+ channel: ChannelPayload
146
+
147
+
148
+ class ChannelTopicChangedPayload(BasePayload):
149
+ """CHANNEL_TOPIC_CHANGEDイベントペイロード
150
+
151
+ Attributes:
152
+ channel (ChannelPayload): 変更されたチャンネル
153
+ topic (str): 変更後のトピック
154
+ updater (UserPayload): トピック更新者
155
+ """
156
+
157
+ channel: ChannelPayload
158
+ topic: str
159
+ updater: UserPayload
160
+
161
+
162
+ class UserCreatedPayload(BasePayload):
163
+ """USER_CREATEDイベントペイロード
164
+
165
+ Attributes:
166
+ user (UserPayload): 作成されたユーザー
167
+ """
168
+
169
+ user: UserPayload
170
+
171
+
172
+ class StampCreatedPayload(BasePayload):
173
+ """STAMP_CREATEDイベントペイロード
174
+
175
+ Attributes:
176
+ id (str): スタンプUUID
177
+ name (str): スタンプ名
178
+ fileId (str): スタンプ画像ファイルUUID
179
+ creator (UserPayload): スタンプを作成したユーザー
180
+ """
181
+
182
+ id: str
183
+ name: str
184
+ fileId: str
185
+ creator: UserPayload
186
+
187
+
188
+ class TagAddedPayload(BasePayload):
189
+ """TAG_ADDEDイベントペイロード
190
+
191
+ Attributes:
192
+ tagId (str): タグUUID
193
+ tag (str): タグ名
194
+ """
195
+
196
+ tagId: str
197
+ tag: str
198
+
199
+
200
+ class TagRemovedPayload(BasePayload):
201
+ """TAG_REMOVEDイベントペイロード
202
+
203
+ Attributes:
204
+ tagId (str): タグUUID
205
+ tag (str): タグ名
206
+ """
207
+
208
+ tagId: str
209
+ tag: str
210
+
211
+
212
+ class UserGroupCreatedPayload(BasePayload):
213
+ """USER_GROUP_CREATEDイベントペイロード
214
+
215
+ Attributes:
216
+ group (UserGroupPayload): 作成されたグループ
217
+ """
218
+
219
+ group: UserGroupPayload
220
+
221
+
222
+ class UserGroupUpdatedPayload(BasePayload):
223
+ """USER_GROUP_UPDATEDイベントペイロード
224
+
225
+ Attributes:
226
+ groupId (str): 更新されたグループUUID
227
+ """
228
+
229
+ groupId: str
230
+
231
+
232
+ class UserGroupDeletedPayload(BasePayload):
233
+ """USER_GROUP_DELETEDイベントペイロード
234
+
235
+ Attributes:
236
+ groupId (str): 削除されたグループUUID
237
+ """
238
+
239
+ groupId: str
240
+
241
+
242
+ class UserGroupMemberAddedPayload(BasePayload):
243
+ """USER_GROUP_MEMBER_ADDEDイベントペイロード
244
+
245
+ Attributes:
246
+ groupMember (GroupMemberPayload): 追加されたグループメンバー情報
247
+ """
248
+
249
+ groupMember: GroupMemberPayload
250
+
251
+
252
+ class UserGroupMemberUpdatedPayload(BasePayload):
253
+ """USER_GROUP_MEMBER_UPDATEDイベントペイロード
254
+
255
+ Attributes:
256
+ groupMember (GroupMemberPayload): 更新されたグループメンバー情報
257
+ """
258
+
259
+ groupMember: GroupMemberPayload
260
+
261
+
262
+ class UserGroupMemberRemovedPayload(BasePayload):
263
+ """USER_GROUP_MEMBER_REMOVEDイベントペイロード
264
+
265
+ Attributes:
266
+ groupMember (GroupMemberPayload): 削除されたグループメンバー情報
267
+ """
268
+
269
+ groupMember: GroupMemberPayload
270
+
271
+
272
+ class UserGroupAdminAddedPayload(BasePayload):
273
+ """USER_GROUP_ADMIN_ADDEDイベントペイロード
274
+
275
+ Attributes:
276
+ groupMember (UserGroupAdminPayload): 追加されたグループ管理者情報
277
+ """
278
+
279
+ groupMember: UserGroupAdminPayload
280
+
281
+
282
+ class UserGroupAdminRemovedPayload(BasePayload):
283
+ """USER_GROUP_ADMIN_REMOVEDイベントペイロード
284
+
285
+ Attributes:
286
+ groupMember (UserGroupAdminPayload): 削除されたグループ管理者情報
287
+ """
288
+
289
+ groupMember: UserGroupAdminPayload
@@ -0,0 +1,101 @@
1
+ from typing import Any, Union
2
+ from .event import (
3
+ BotMessageStampsUpdatedPayload,
4
+ ChannelCreatedPayload,
5
+ ChannelTopicChangedPayload,
6
+ DirectMessageCreatedPayload,
7
+ DirectMessageDeletedPayload,
8
+ DirectMessageUpdatedPayload,
9
+ JoinedPayload,
10
+ LeftPayload,
11
+ MessageCreatedPayload,
12
+ MessageDeletedPayload,
13
+ MessageUpdatedPayload,
14
+ PingPayload,
15
+ StampCreatedPayload,
16
+ TagAddedPayload,
17
+ TagRemovedPayload,
18
+ UserCreatedPayload,
19
+ UserGroupAdminAddedPayload,
20
+ UserGroupAdminRemovedPayload,
21
+ UserGroupCreatedPayload,
22
+ UserGroupDeletedPayload,
23
+ UserGroupMemberAddedPayload,
24
+ UserGroupMemberRemovedPayload,
25
+ UserGroupMemberUpdatedPayload,
26
+ UserGroupUpdatedPayload,
27
+ )
28
+ from pydantic import ValidationError
29
+
30
+
31
+ # FIXME: うまく型出し分ける方法わからん
32
+ EventModel = Union[
33
+ BotMessageStampsUpdatedPayload,
34
+ ChannelCreatedPayload,
35
+ ChannelTopicChangedPayload,
36
+ DirectMessageCreatedPayload,
37
+ DirectMessageDeletedPayload,
38
+ DirectMessageUpdatedPayload,
39
+ JoinedPayload,
40
+ LeftPayload,
41
+ MessageCreatedPayload,
42
+ MessageDeletedPayload,
43
+ MessageUpdatedPayload,
44
+ PingPayload,
45
+ StampCreatedPayload,
46
+ TagAddedPayload,
47
+ TagRemovedPayload,
48
+ UserCreatedPayload,
49
+ UserGroupAdminAddedPayload,
50
+ UserGroupAdminRemovedPayload,
51
+ UserGroupCreatedPayload,
52
+ UserGroupDeletedPayload,
53
+ UserGroupMemberAddedPayload,
54
+ UserGroupMemberRemovedPayload,
55
+ UserGroupMemberUpdatedPayload,
56
+ UserGroupUpdatedPayload,
57
+ ]
58
+ EventModelType = type[EventModel]
59
+
60
+
61
+ event_models: dict[str, EventModelType] = {
62
+ "PING": PingPayload,
63
+ "JOINED": JoinedPayload,
64
+ "LEFT": LeftPayload,
65
+ "MESSAGE_CREATED": MessageCreatedPayload,
66
+ "MESSAGE_DELETED": MessageDeletedPayload,
67
+ "MESSAGE_UPDATED": MessageUpdatedPayload,
68
+ "DIRECT_MESSAGE_CREATED": DirectMessageCreatedPayload,
69
+ "DIRECT_MESSAGE_DELETED": DirectMessageDeletedPayload,
70
+ "DIRECT_MESSAGE_UPDATED": DirectMessageUpdatedPayload,
71
+ "BOT_MESSAGE_STAMPS_UPDATED": BotMessageStampsUpdatedPayload,
72
+ "CHANNEL_CREATED": ChannelCreatedPayload,
73
+ "CHANNEL_TOPIC_CHANGED": ChannelTopicChangedPayload,
74
+ "USER_CREATED": UserCreatedPayload,
75
+ "STAMP_CREATED": StampCreatedPayload,
76
+ "TAG_ADDED": TagAddedPayload,
77
+ "TAG_REMOVED": TagRemovedPayload,
78
+ "USER_GROUP_CREATED": UserGroupCreatedPayload,
79
+ "USER_GROUP_UPDATED": UserGroupUpdatedPayload,
80
+ "USER_GROUP_DELETED": UserGroupDeletedPayload,
81
+ "USER_GROUP_MEMBER_ADDED": UserGroupMemberAddedPayload,
82
+ "USER_GROUP_MEMBER_UPDATED": UserGroupMemberUpdatedPayload,
83
+ "USER_GROUP_MEMBER_REMOVED": UserGroupMemberRemovedPayload,
84
+ "USER_GROUP_ADMIN_ADDED": UserGroupAdminAddedPayload,
85
+ "USER_GROUP_ADMIN_REMOVED": UserGroupAdminRemovedPayload,
86
+ }
87
+
88
+
89
+ def convert_json_to_model(json_data: dict, event: str) -> EventModel:
90
+ if event not in event_models:
91
+ raise ValidationError(f"Invalid event: {event}")
92
+
93
+ return event_models[event].model_validate(json_data)
94
+
95
+
96
+ def model_to_event_type(model: Any) -> str | None:
97
+ for event, model_type in event_models.items():
98
+ if model == model_type:
99
+ return event
100
+
101
+ return None
File without changes
@@ -0,0 +1,48 @@
1
+ [tool.poetry]
2
+ name = "aiotraq-bot"
3
+ version = "0.1.0"
4
+ description = "Async ready traQ Bot library"
5
+ authors = ["toshi00"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ repository = "https://github.com/toshi-pono/aiotraq"
9
+ packages = [{ include = "aiotraq_bot" }]
10
+ include = ["aiotraq_bot/py.typed"]
11
+ keywords = ["traQ", "bot", "async", "aiotraq"]
12
+
13
+
14
+ [tool.poetry.urls]
15
+ "Source Code" = "https://github.com/toshi-pono/aiotraq/tree/main/libs/bot"
16
+
17
+
18
+ [tool.poetry.dependencies]
19
+ python = ">=3.10,<4.0"
20
+ fastapi = ">=0.100.0"
21
+ uvicorn = { extras = ["standard"], version = ">=0.12.0" }
22
+
23
+ [build-system]
24
+ requires = ["poetry-core>=1.0.0"]
25
+ build-backend = "poetry.core.masonry.api"
26
+
27
+
28
+ [tool.mypy]
29
+ show_error_context = true
30
+ show_column_numbers = true
31
+ ignore_missing_imports = true
32
+ disallow_untyped_defs = true
33
+ no_implicit_optional = true
34
+ warn_return_any = true
35
+ check_untyped_defs = true
36
+
37
+
38
+ [tool.ruff]
39
+ exclude = [".venv", "venv", "__pycache__", ".git"]
40
+
41
+ line-length = 120
42
+ indent-width = 4
43
+
44
+ [tool.ruff.format]
45
+ quote-style = "double"
46
+
47
+ [tool.ruff.lint.mccabe]
48
+ max-complexity = 10