imbot-sdk-python 0.1.0__py3-none-any.whl → 0.1.2__py3-none-any.whl

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.
imbot_sdk/__init__.py CHANGED
@@ -35,7 +35,7 @@ from .models import (
35
35
  UserInfo,
36
36
  )
37
37
 
38
- __version__ = "0.1.0"
38
+ __version__ = "0.1.2"
39
39
 
40
40
  __all__ = [
41
41
  "ImBotClient",
@@ -0,0 +1,366 @@
1
+ Metadata-Version: 2.4
2
+ Name: imbot-sdk-python
3
+ Version: 0.1.2
4
+ Summary: JuggleIM Python Bot SDK — WebSocket long-connection IM client for bots and server-side agents
5
+ Author-email: Tyler <tyler@juggle.im>
6
+ Maintainer-email: Tyler <tyler@juggle.im>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/juggleim/imbot-sdk-python
9
+ Project-URL: Repository, https://github.com/juggleim/imbot-sdk-python
10
+ Project-URL: Issues, https://github.com/juggleim/imbot-sdk-python/issues
11
+ Project-URL: Documentation, https://github.com/juggleim/imbot-sdk-python#readme
12
+ Keywords: juggleim,im,instant-messaging,chat,bot,websocket,sdk
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Communications :: Chat
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: protobuf>=5.0
29
+ Requires-Dist: websocket-client>=1.6
30
+ Provides-Extra: dev
31
+ Requires-Dist: build; extra == "dev"
32
+ Requires-Dist: twine; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # imbot-sdk-python
36
+
37
+ **English** | [简体中文](README.zh-CN.md)
38
+
39
+ [![PyPI version](https://img.shields.io/pypi/v/imbot-sdk-python.svg)](https://pypi.org/project/imbot-sdk-python/)
40
+ [![Python versions](https://img.shields.io/pypi/pyversions/imbot-sdk-python.svg)](https://pypi.org/project/imbot-sdk-python/)
41
+ [![License](https://img.shields.io/pypi/l/imbot-sdk-python.svg)](https://github.com/juggleim/imbot-sdk-python/blob/main/LICENSE)
42
+
43
+ `imbot-sdk-python` is the JuggleIM Python SDK. It keeps a long-lived WebSocket
44
+ connection to the IM service, making it a good fit for bots, server-side message
45
+ agents, or any Python program that needs to actively send and receive messages.
46
+ It covers connection management, messaging, conversation queries, history,
47
+ chatrooms, user status, RTC rooms and file credential queries.
48
+
49
+ - Source: <https://github.com/juggleim/imbot-sdk-python>
50
+ - Distribution name: `imbot-sdk-python`; import name: `import imbot_sdk`
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pip install imbot-sdk-python
56
+ ```
57
+
58
+ Dependencies (`protobuf>=5.0`, `websocket-client>=1.6`) are installed
59
+ automatically. Python 3.8+.
60
+
61
+ Install from source:
62
+
63
+ ```bash
64
+ git clone https://github.com/juggleim/imbot-sdk-python.git
65
+ cd imbot-sdk-python
66
+ pip install .
67
+ ```
68
+
69
+ ## Test environment
70
+
71
+ | Item | Value |
72
+ | --- | --- |
73
+ | Server API | `http://127.0.0.1` |
74
+ | WebSocket | `wss://127.0.0.1` |
75
+ | AppKey | `AppKey` |
76
+
77
+ > A user token is issued by your JuggleIM app server / console using your AppKey
78
+ > + AppSecret via the Server API. The SDK itself only establishes the
79
+ > connection and sends/receives messages.
80
+
81
+ ## Obtaining a token
82
+
83
+ `connect(token)` needs a per-user token. Tokens are minted by your app server
84
+ through the JuggleIM Server API using your AppKey + AppSecret. Registering a bot
85
+ (or a user) returns a token:
86
+
87
+ - Endpoint: `POST {ServerAPI}/bots/register` (or `/users/register`)
88
+ - Auth headers: `appkey`, `nonce` (random 0-9999), `timestamp` (epoch ms),
89
+ `signature = lowercase_hex( SHA1(AppSecret + nonce + timestamp) )`,
90
+ `Content-Type: application/json`
91
+ - Response: `{"code":0,"msg":"success","data":{"user_id":"...","token":"..."}}`
92
+
93
+ A ready-to-use helper (standard library only, no hard-coded credentials) is
94
+ [`examples/register_bot.py`](examples/register_bot.py):
95
+
96
+ ```bash
97
+ export IMBOT_API_URL="https://api.juggleim.com/apigateway"
98
+ export IMBOT_APPKEY="<your-appkey>"
99
+ export IMBOT_APPSECRET="<your-appsecret>"
100
+
101
+ # register a bot and print its token
102
+ python examples/register_bot.py --bot-id my-bot --nickname "My Bot"
103
+
104
+ # or register a normal user
105
+ python examples/register_bot.py --user --user-id u1 --nickname "User 1"
106
+ ```
107
+
108
+ > Keep your AppSecret on the server side — never ship it inside client apps.
109
+ > If the Server API host presents an expired/invalid TLS certificate, pass
110
+ > `--insecure` to bypass verification (use only against endpoints you trust).
111
+
112
+ ## Feature overview
113
+
114
+ - Connection management: `connect`, `disconnect`, `logout`, heartbeat keep-alive,
115
+ automatic reconnect.
116
+ - Messaging: send/receive for private, group, chatroom and public-channel
117
+ conversations.
118
+ - Message management: history query, recall, modify, mark-read, search, top
119
+ messages.
120
+ - Conversation management: list, unread count, top, mute, tags.
121
+ - User & group info: user profile, friend profile, group info, online-status
122
+ subscription.
123
+ - Chatroom: join/quit, chatroom messages, attribute sync.
124
+ - RTC: create / join / query / quit RTC rooms.
125
+ - File: credential query via `get_file_cred`.
126
+
127
+ ## Quick start
128
+
129
+ ### 1. Create a client
130
+
131
+ ```python
132
+ from imbot_sdk import ImBotClient
133
+
134
+ client = ImBotClient("wss://127.0.0.1", "your-appkey")
135
+ ```
136
+
137
+ Notes:
138
+
139
+ - Pass the base `address`; the SDK appends the path automatically to form
140
+ `ws://host/imbot` or `wss://host/imbot`.
141
+ - `client.platform` defaults to `"Bot"`.
142
+ - `client.auto_reconnect` defaults to `True`.
143
+
144
+ ### 2. Connect
145
+
146
+ ```python
147
+ code, ack = client.connect("your-token")
148
+ ```
149
+
150
+ Notes:
151
+
152
+ - On success `code == ClientErrorCode.SUCCESS`.
153
+ - After success `ack.userId` is written to `client.user_id`.
154
+ - `connect` may only be called while disconnected; a repeated connect returns
155
+ `ClientErrorCode.CONNECT_EXISTED`.
156
+ - After an explicit `disconnect()` or `logout()`, auto-reconnect stops.
157
+
158
+ ### 3. Two ways to receive messages
159
+
160
+ Prefer the high-level listener (you receive a decoded `Message`):
161
+
162
+ ```python
163
+ from imbot_sdk import MessageListener, messages
164
+
165
+ class MyListener(MessageListener):
166
+ def on_message_receive(self, msg):
167
+ if isinstance(msg.msg_content, messages.TextMessage):
168
+ print("text:", msg.msg_content.content)
169
+
170
+ client.add_message_listener(MyListener())
171
+ ```
172
+
173
+ If you want the raw protobuf payloads:
174
+
175
+ ```python
176
+ client.on_message_callback = lambda down_msg: print(down_msg)
177
+ client.on_stream_msg_callback = lambda stream_msg: print(stream_msg)
178
+ ```
179
+
180
+ ### 4. Send a message
181
+
182
+ ```python
183
+ from imbot_sdk import Conversation, messages
184
+ from imbot_sdk.pb import appmessages_pb2 as pb
185
+
186
+ text = messages.TextMessage("hello from imbot-sdk-python")
187
+ up = client.build_up_msg(text, client_uid="bot-1")
188
+
189
+ conv = Conversation(conversation_type=pb.Private, conversation="target-user-id")
190
+ code, ack = client.send_message(conv, up)
191
+ # ack.msgId / ack.msgSeqNo carry the server's acknowledgement
192
+ ```
193
+
194
+ `build_up_msg` encodes a content model into `UpMsg.msgType / msgContent /
195
+ flags`; you can also construct a `pb.UpMsg` directly.
196
+
197
+ ## Full example: connect, listen, echo
198
+
199
+ ```python
200
+ import time
201
+ from imbot_sdk import ImBotClient, Conversation, MessageListener, ClientErrorCode, messages
202
+ from imbot_sdk.pb import appmessages_pb2 as pb
203
+
204
+ class Echo(MessageListener):
205
+ def __init__(self, client):
206
+ self.client = client
207
+ def on_message_receive(self, msg):
208
+ c = msg.msg_content
209
+ if isinstance(c, messages.TextMessage) and msg.sender_id != self.client.user_id:
210
+ up = self.client.build_up_msg(messages.TextMessage("echo: " + c.content),
211
+ client_uid="echo-%d" % time.time_ns())
212
+ self.client.send_message(msg.conversation, up)
213
+
214
+ client = ImBotClient("wss://127.0.0.1", "AppKey")
215
+ client.add_message_listener(Echo(client))
216
+
217
+ code, ack = client.connect("your-token")
218
+ assert code == ClientErrorCode.SUCCESS
219
+ print("connected:", ack.userId)
220
+
221
+ # Proactively send a private message to a user
222
+ up = client.build_up_msg(messages.TextMessage("hi"), client_uid="greet-1")
223
+ client.send_message(Conversation(conversation_type=pb.Private, conversation="target-user-id"), up)
224
+
225
+ try:
226
+ while True:
227
+ time.sleep(1)
228
+ except KeyboardInterrupt:
229
+ client.disconnect()
230
+ ```
231
+
232
+ A runnable version lives in [`examples/echo_bot.py`](examples/echo_bot.py). The
233
+ recommended way is `.env` + the launch script:
234
+
235
+ ```bash
236
+ cp examples/.env.example examples/.env
237
+ # edit examples/.env, at least set IMBOT_TOKEN (IMBOT_TARGET optional)
238
+ bash examples/run.sh
239
+ ```
240
+
241
+ `run.sh` loads `examples/.env` and starts the echo bot; extra arguments are
242
+ passed through (e.g. `bash examples/run.sh --target some-user-id`). You can also
243
+ skip the script and pass args / export env vars directly:
244
+
245
+ ```bash
246
+ python examples/echo_bot.py --token <your-token> --target <target-user-id>
247
+ ```
248
+
249
+ Configuration (env vars / `.env`):
250
+
251
+ | Variable | Description | Required |
252
+ | --- | --- | --- |
253
+ | `IMBOT_TOKEN` | User token | Yes |
254
+ | `IMBOT_TARGET` | Target user id to greet on startup | No |
255
+ | `IMBOT_ADDRESS` | WebSocket base address | No |
256
+ | `IMBOT_APPKEY` | App AppKey | No |
257
+
258
+ Additional notes:
259
+
260
+ - Use `pb.Private` for private chats, `pb.Group` for groups, `pb.Chatroom` for
261
+ chatrooms, `pb.PublicChannel` for public channels.
262
+ - Chatroom messages can also be sent via `client.send_chatroom_msg(chatroom_id, up_msg)`.
263
+ - A received `msg.msg_content` is already decoded by content type, so you can
264
+ `isinstance`-check it directly.
265
+
266
+ ## Message types
267
+
268
+ Built-in content models live in `imbot_sdk.messages`:
269
+
270
+ | Type | Identifier | Class |
271
+ | --- | --- | --- |
272
+ | Text | `jg:text` | `TextMessage` |
273
+ | Image | `jg:img` | `ImageMessage` |
274
+ | File | `jg:file` | `FileMessage` |
275
+ | Video | `jg:video` | `VideoMessage` |
276
+ | Voice | `jg:voice` | `VoiceMessage` |
277
+ | Stream text | `jg:streamtext` | `StreamTextMessage` |
278
+ | Recall notice | `jg:recallinfo` | `RecallInfoMessage` |
279
+ | Merged message | `jg:merge` | `MergeMessage` |
280
+ | Thumbnail-packed image | `jg:tpimg` | `ThumbnailPackedImageMessage` |
281
+ | Snapshot-packed video | `jg:spvideo` | `SnapshotPackedVideoMessage` |
282
+
283
+ For content types that are not built in, the SDK falls back to
284
+ `messages.UnknownMessage`. The JSON encode/decode fields of these models are
285
+ stable, so messages interoperate with the other JuggleIM client SDKs.
286
+
287
+ ## Common APIs
288
+
289
+ > See [`docs/API.md`](docs/API.md) for the full method list. Naming follows
290
+ > Python conventions (snake_case).
291
+
292
+ ### Connection & state
293
+
294
+ `connect(token)`, `reconnect()`, `disconnect()`, `logout()`, `ping()`,
295
+ `add_connection_status_change_listener(listener)`
296
+
297
+ ### Messages
298
+
299
+ `send_message(conversation, up_msg)`, `qry_history_msgs(req)`, `recall_msg(req)`,
300
+ `modify_msg(req)`, `mark_read_msg(req)`, `msg_search(req)`,
301
+ `msg_global_search(req)`, `set_top_msg(req)`, `del_top_msg(req)`
302
+
303
+ ### Conversations
304
+
305
+ `get_conversation(req)`, `get_conversations(req)`, `sync_conversations(req)`,
306
+ `clear_unread_count(req)`, `set_conversation_top(req)`, `set_mute(req)`,
307
+ `delete_conversations(req)`
308
+
309
+ ### Users, groups, status
310
+
311
+ `fetch_user_info(user_id)`, `fetch_group_info(group_id)`,
312
+ `fetch_friend_info(friend_user_id)`, `get_user_status(req)`,
313
+ `subscribe_user_status(req)`, `unsubscribe_user_status(req)`
314
+
315
+ ### Chatroom
316
+
317
+ `join_chatroom(chatroom_id)`, `quit_chatroom(chatroom_id)`,
318
+ `send_chatroom_msg(chatroom_id, up_msg)`, `set_attributes(chatroom_id, attributes)`,
319
+ `remove_attributes(chatroom_id, keys)`
320
+
321
+ ### RTC
322
+
323
+ `create_rtc_room(req)`, `join_rtc_room(req)`, `qry_rtc_room(room_id)`,
324
+ `quit_rtc_room(room_id)`, `rtc_invite(req)`
325
+
326
+ ### File
327
+
328
+ `get_file_cred(req)`
329
+
330
+ > The SDK provides file credential queries; the actual file upload/download flow
331
+ > must be handled by your application against your storage service.
332
+
333
+ ## Usage notes
334
+
335
+ - `publish` and `query` both require the connection state to be `CONNECTED`,
336
+ otherwise they return `ClientErrorCode.CONNECT_CLOSED`.
337
+ - Sends and queries wait up to 10 seconds for an ACK, returning
338
+ `ClientErrorCode.SEND_TIMEOUT` / `ClientErrorCode.QUERY_TIMEOUT` on timeout.
339
+ - The SDK handles heartbeats automatically; if no downstream data arrives for
340
+ more than two heartbeat windows (~20s), it disconnects and tries to reconnect.
341
+ - Message listener callbacks run on internal threads — avoid long blocking work,
342
+ and hand off to a worker queue if needed.
343
+ - Image / file / voice / video content models only encode/decode content; they
344
+ do not upload the underlying files.
345
+
346
+ ## Regenerating protobuf
347
+
348
+ The `.proto` sources live in [`proto/`](proto/). Regenerate after editing:
349
+
350
+ ```bash
351
+ bash proto/gen.sh
352
+ ```
353
+
354
+ ## Module layout
355
+
356
+ | Module | Description |
357
+ | --- | --- |
358
+ | `imbot_sdk.ImBotClient` | Main client entry point |
359
+ | `imbot_sdk.ClientErrorCode` / `ConnectState` | Error codes and connection state |
360
+ | `imbot_sdk.models` | Domain models (`Conversation` / `Message` / `UserInfo` …) |
361
+ | `imbot_sdk.messages` | Message content models |
362
+ | `imbot_sdk.pb` | Protobuf types (`appmessages_pb2` / `connect_pb2` / `chatroom_pb2` / `rtcroom_pb2`) |
363
+
364
+ ## License
365
+
366
+ [LICENSE](LICENSE) (Apache-2.0)
@@ -1,4 +1,4 @@
1
- imbot_sdk/__init__.py,sha256=04mbVzRjopiXkSBc5Q-rKO0HI-a9vJn7bH3IHlg0fEc,1456
1
+ imbot_sdk/__init__.py,sha256=NFKl861qKklXQpKq1aiLm4sq_pN8P0IzshwUKErxC7k,1456
2
2
  imbot_sdk/client.py,sha256=qOG3BZOBZH_JA_0iDpxrFVQGgfwdyRJ2NZzWNop2Y2M,46357
3
3
  imbot_sdk/consts.py,sha256=EQhnWoc0RFDMIpZl7posvVwFDblnpQ0VJaW-bgAC6IQ,754
4
4
  imbot_sdk/data_accessor.py,sha256=om_UzAAgCGtNqWZbLcpU0VFq_Tmi-Xi3lkwv-E-unHw,1018
@@ -13,8 +13,8 @@ imbot_sdk/pb/appmessages_pb2.py,sha256=7yyt_KqDs7rO8TtYO88AJIqfB5yLfoPV3PwRSpidu
13
13
  imbot_sdk/pb/chatroom_pb2.py,sha256=2SD6pyFKZuFhOvvZbDffX591OrYqv8q7eNm4SA-7s9o,9452
14
14
  imbot_sdk/pb/connect_pb2.py,sha256=k3QU7PAaYL_umjV5WXloxgWlYvKrM7CSV6Fj0eBxhzo,4777
15
15
  imbot_sdk/pb/rtcroom_pb2.py,sha256=v9uuWxbEvsmwHHt9OLuDvE4w1v0wQX7e1Xxv0mKFQPo,8037
16
- imbot_sdk_python-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
17
- imbot_sdk_python-0.1.0.dist-info/METADATA,sha256=EIbaMnjWWsczumOZ8wsZZs3_od7syuMxnESSuFf6jp8,11119
18
- imbot_sdk_python-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
19
- imbot_sdk_python-0.1.0.dist-info/top_level.txt,sha256=Q636V3MNhiMZGfV2FfiBcNaYh4bHlVB0iXVMQgVuoeo,10
20
- imbot_sdk_python-0.1.0.dist-info/RECORD,,
16
+ imbot_sdk_python-0.1.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
17
+ imbot_sdk_python-0.1.2.dist-info/METADATA,sha256=IeEszLrZnszijy28ns-IH2783qO5f5DFFRb-T1uXLmE,12792
18
+ imbot_sdk_python-0.1.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
19
+ imbot_sdk_python-0.1.2.dist-info/top_level.txt,sha256=Q636V3MNhiMZGfV2FfiBcNaYh4bHlVB0iXVMQgVuoeo,10
20
+ imbot_sdk_python-0.1.2.dist-info/RECORD,,
@@ -1,296 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: imbot-sdk-python
3
- Version: 0.1.0
4
- Summary: JuggleIM Python Bot SDK — WebSocket long-connection IM client for bots and server-side agents
5
- Author-email: Tyler <tyler@juggle.im>
6
- Maintainer-email: Tyler <tyler@juggle.im>
7
- License-Expression: Apache-2.0
8
- Project-URL: Homepage, https://github.com/juggleim/imbot-sdk-python
9
- Project-URL: Repository, https://github.com/juggleim/imbot-sdk-python
10
- Project-URL: Issues, https://github.com/juggleim/imbot-sdk-python/issues
11
- Project-URL: Documentation, https://github.com/juggleim/imbot-sdk-python#readme
12
- Keywords: juggleim,im,instant-messaging,chat,bot,websocket,sdk
13
- Classifier: Development Status :: 3 - Alpha
14
- Classifier: Intended Audience :: Developers
15
- Classifier: Operating System :: OS Independent
16
- Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.8
18
- Classifier: Programming Language :: Python :: 3.9
19
- Classifier: Programming Language :: Python :: 3.10
20
- Classifier: Programming Language :: Python :: 3.11
21
- Classifier: Programming Language :: Python :: 3.12
22
- Classifier: Programming Language :: Python :: 3.13
23
- Classifier: Topic :: Communications :: Chat
24
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
- Requires-Python: >=3.8
26
- Description-Content-Type: text/markdown
27
- License-File: LICENSE
28
- Requires-Dist: protobuf>=5.0
29
- Requires-Dist: websocket-client>=1.6
30
- Provides-Extra: dev
31
- Requires-Dist: build; extra == "dev"
32
- Requires-Dist: twine; extra == "dev"
33
- Dynamic: license-file
34
-
35
- # imbot-sdk-python
36
-
37
- [![PyPI version](https://img.shields.io/pypi/v/imbot-sdk-python.svg)](https://pypi.org/project/imbot-sdk-python/)
38
- [![Python versions](https://img.shields.io/pypi/pyversions/imbot-sdk-python.svg)](https://pypi.org/project/imbot-sdk-python/)
39
- [![License](https://img.shields.io/pypi/l/imbot-sdk-python.svg)](https://github.com/juggleim/imbot-sdk-python/blob/main/LICENSE)
40
-
41
- `imbot-sdk-python` 是 JuggleIM 的 Python SDK,基于 WebSocket 与 IM 服务建立长连接,适合 Bot、服务端消息代理或需要主动收发消息的 Python 程序。覆盖连接管理、消息收发、会话查询、历史消息、聊天室、用户状态、RTC 房间和文件凭证查询等常用能力。
42
-
43
- - 源码:<https://github.com/juggleim/imbot-sdk-python>
44
- - 包名:`imbot-sdk-python`;导入名:`import imbot_sdk`
45
-
46
- ## 安装
47
-
48
- ```bash
49
- pip install imbot-sdk-python
50
- ```
51
-
52
- 依赖(`protobuf>=5.0`、`websocket-client>=1.6`)会自动安装。Python 3.8+。
53
-
54
- 从源码安装:
55
-
56
- ```bash
57
- git clone https://github.com/juggleim/imbot-sdk-python.git
58
- cd imbot-sdk-python
59
- pip install .
60
- ```
61
-
62
- ## 测试环境
63
-
64
- | 项目 | 值 |
65
- | --- | --- |
66
- | Server API | `http://127.0.0.1` |
67
- | WebSocket | `wss://127.0.0.1` |
68
- | AppKey | `AppKey` |
69
-
70
- > Token 由你的 JuggleIM 应用服务端 / 控制台用 AppKey + AppSecret 通过 Server API 颁发。SDK 本身只负责建立长连接与收发消息。
71
-
72
- ## 能力概览
73
-
74
- - 连接管理:`connect`、`disconnect`、`logout`、心跳保活、断线自动重连
75
- - 消息收发:单聊、群聊、聊天室、公共频道消息发送与接收
76
- - 消息管理:历史消息查询、撤回、修改、已读标记、搜索、置顶消息
77
- - 会话管理:会话列表、未读数、置顶、免打扰、标签
78
- - 用户与群信息:用户资料、好友资料、群信息、在线状态订阅
79
- - 聊天室:加入/退出聊天室、聊天室消息、聊天室属性同步
80
- - RTC:创建/加入/查询/退出 RTC 房间
81
- - 文件:文件凭证查询 `get_file_cred`
82
-
83
- ## 快速说明
84
-
85
- ### 1. 创建客户端
86
-
87
- ```python
88
- from imbot_sdk import ImBotClient
89
-
90
- client = ImBotClient("wss://127.0.0.1", "your-appkey")
91
- ```
92
-
93
- 说明:
94
-
95
- - `address` 传基础地址即可,SDK 会自动拼接为 `ws://host/imbot` 或 `wss://host/imbot`
96
- - `client.platform` 默认是 `"Bot"`
97
- - `client.auto_reconnect` 默认是 `True`
98
-
99
- ### 2. 建立连接
100
-
101
- ```python
102
- code, ack = client.connect("your-token")
103
- ```
104
-
105
- 说明:
106
-
107
- - 连接成功时 `code == ClientErrorCode.SUCCESS`
108
- - 成功后 `ack.userId` 会写入 `client.user_id`
109
- - `connect` 只能在断开状态下调用;重复连接会返回 `ClientErrorCode.CONNECT_EXISTED`
110
- - 主动调用 `disconnect()` 或 `logout()` 后,不会继续自动重连
111
-
112
- ### 3. 接收消息的两种方式
113
-
114
- 推荐优先使用高层监听(拿到的是已经解码后的 `Message`):
115
-
116
- ```python
117
- from imbot_sdk import MessageListener, messages
118
-
119
- class MyListener(MessageListener):
120
- def on_message_receive(self, msg):
121
- if isinstance(msg.msg_content, messages.TextMessage):
122
- print("text:", msg.msg_content.content)
123
-
124
- client.add_message_listener(MyListener())
125
- ```
126
-
127
- 如果你想拿到底层 protobuf 数据:
128
-
129
- ```python
130
- client.on_message_callback = lambda down_msg: print(down_msg)
131
- client.on_stream_msg_callback = lambda stream_msg: print(stream_msg)
132
- ```
133
-
134
- ### 4. 发送消息
135
-
136
- ```python
137
- from imbot_sdk import Conversation, messages
138
- from imbot_sdk.pb import appmessages_pb2 as pb
139
-
140
- text = messages.TextMessage("hello from imbot-sdk-python")
141
- up = client.build_up_msg(text, client_uid="bot-1")
142
-
143
- conv = Conversation(conversation_type=pb.Private, conversation="target-user-id")
144
- code, ack = client.send_message(conv, up)
145
- # ack.msgId / ack.msgSeqNo 为服务端确认结果
146
- ```
147
-
148
- `build_up_msg` 会把内容模型编码进 `UpMsg.msgType / msgContent / flags`;你也可以直接构造 `pb.UpMsg`。
149
-
150
- ## 完整示例:连接、监听、回声
151
-
152
- ```python
153
- import time
154
- from imbot_sdk import ImBotClient, Conversation, MessageListener, ClientErrorCode, messages
155
- from imbot_sdk.pb import appmessages_pb2 as pb
156
-
157
- class Echo(MessageListener):
158
- def __init__(self, client):
159
- self.client = client
160
- def on_message_receive(self, msg):
161
- c = msg.msg_content
162
- if isinstance(c, messages.TextMessage) and msg.sender_id != self.client.user_id:
163
- up = self.client.build_up_msg(messages.TextMessage("echo: " + c.content),
164
- client_uid="echo-%d" % time.time_ns())
165
- self.client.send_message(msg.conversation, up)
166
-
167
- client = ImBotClient("wss://127.0.0.1", "AppKey")
168
- client.add_message_listener(Echo(client))
169
-
170
- code, ack = client.connect("your-token")
171
- assert code == ClientErrorCode.SUCCESS
172
- print("connected:", ack.userId)
173
-
174
- # 主动给某用户发一条单聊
175
- up = client.build_up_msg(messages.TextMessage("hi"), client_uid="greet-1")
176
- client.send_message(Conversation(conversation_type=pb.Private, conversation="target-user-id"), up)
177
-
178
- try:
179
- while True:
180
- time.sleep(1)
181
- except KeyboardInterrupt:
182
- client.disconnect()
183
- ```
184
-
185
- 可运行的版本见 [`examples/echo_bot.py`](examples/echo_bot.py)。推荐用 `.env` + 启动脚本:
186
-
187
- ```bash
188
- cp examples/.env.example examples/.env
189
- # 编辑 examples/.env,至少填入 IMBOT_TOKEN(可选 IMBOT_TARGET)
190
- bash examples/run.sh
191
- ```
192
-
193
- `run.sh` 会自动加载 `examples/.env` 并启动 echo bot,多余参数会透传给脚本(如
194
- `bash examples/run.sh --target some-user-id`)。也可以不用脚本,直接传参或导出环境变量:
195
-
196
- ```bash
197
- python examples/echo_bot.py --token <your-token> --target <target-user-id>
198
- ```
199
-
200
- 配置项(环境变量 / `.env`):
201
-
202
- | 变量 | 说明 | 必填 |
203
- | --- | --- | --- |
204
- | `IMBOT_TOKEN` | 用户 Token | 是 |
205
- | `IMBOT_TARGET` | 启动时打招呼的目标用户 ID | 否 |
206
- | `IMBOT_ADDRESS` | WebSocket 基础地址 | 否 |
207
- | `IMBOT_APPKEY` | 应用 AppKey | 否 |
208
-
209
- 补充说明:
210
-
211
- - 单聊发送使用 `pb.Private`,群聊使用 `pb.Group`,聊天室使用 `pb.Chatroom`,公共频道使用 `pb.PublicChannel`
212
- - 聊天室消息也可以直接 `client.send_chatroom_msg(chatroom_id, up_msg)`
213
- - 接收到的 `msg.msg_content` 已按消息类型解码,可直接 `isinstance` 判断
214
-
215
- ## 消息类型
216
-
217
- 内置的消息内容模型位于 `imbot_sdk.messages`:
218
-
219
- | 类型 | 标识 | 类 |
220
- | --- | --- | --- |
221
- | 文本 | `jg:text` | `TextMessage` |
222
- | 图片 | `jg:img` | `ImageMessage` |
223
- | 文件 | `jg:file` | `FileMessage` |
224
- | 视频 | `jg:video` | `VideoMessage` |
225
- | 语音 | `jg:voice` | `VoiceMessage` |
226
- | 流式文本 | `jg:streamtext` | `StreamTextMessage` |
227
- | 撤回通知 | `jg:recallinfo` | `RecallInfoMessage` |
228
- | 合并消息 | `jg:merge` | `MergeMessage` |
229
- | 缩略图打包图片 | `jg:tpimg` | `ThumbnailPackedImageMessage` |
230
- | 快照打包视频 | `jg:spvideo` | `SnapshotPackedVideoMessage` |
231
-
232
- 收到未内置支持的消息类型时,SDK 会回落为 `messages.UnknownMessage`。这些模型的 JSON 编解码字段保持稳定,因此消息可与其它 JuggleIM 客户端互通。
233
-
234
- ## 常用 API
235
-
236
- > 完整方法清单见 [`docs/API.md`](docs/API.md)。命名采用 Python 风格(snake_case)。
237
-
238
- ### 连接与状态
239
-
240
- `connect(token)`、`reconnect()`、`disconnect()`、`logout()`、`ping()`、`add_connection_status_change_listener(listener)`
241
-
242
- ### 消息
243
-
244
- `send_message(conversation, up_msg)`、`qry_history_msgs(req)`、`recall_msg(req)`、`modify_msg(req)`、`mark_read_msg(req)`、`msg_search(req)`、`msg_global_search(req)`、`set_top_msg(req)`、`del_top_msg(req)`
245
-
246
- ### 会话
247
-
248
- `get_conversation(req)`、`get_conversations(req)`、`sync_conversations(req)`、`clear_unread_count(req)`、`set_conversation_top(req)`、`set_mute(req)`、`delete_conversations(req)`
249
-
250
- ### 用户、群组、状态
251
-
252
- `fetch_user_info(user_id)`、`fetch_group_info(group_id)`、`fetch_friend_info(friend_user_id)`、`get_user_status(req)`、`subscribe_user_status(req)`、`unsubscribe_user_status(req)`
253
-
254
- ### 聊天室
255
-
256
- `join_chatroom(chatroom_id)`、`quit_chatroom(chatroom_id)`、`send_chatroom_msg(chatroom_id, up_msg)`、`set_attributes(chatroom_id, attributes)`、`remove_attributes(chatroom_id, keys)`
257
-
258
- ### RTC
259
-
260
- `create_rtc_room(req)`、`join_rtc_room(req)`、`qry_rtc_room(room_id)`、`quit_rtc_room(room_id)`、`rtc_invite(req)`
261
-
262
- ### 文件
263
-
264
- `get_file_cred(req)`
265
-
266
- > 当前 SDK 提供文件凭证查询能力,文件上传/下载流程需由业务侧结合存储服务自行处理。
267
-
268
- ## 使用注意事项
269
-
270
- - `publish` 和 `query` 都要求当前连接状态为 `CONNECTED`,否则返回 `ClientErrorCode.CONNECT_CLOSED`
271
- - 发送和查询默认等待 10 秒 ACK,超时分别返回 `ClientErrorCode.SEND_TIMEOUT`、`ClientErrorCode.QUERY_TIMEOUT`
272
- - SDK 内部会自动处理心跳;连续超过两个心跳周期(约 20 秒)未收到下行数据,会断开并尝试自动重连
273
- - 消息监听回调运行在内部线程上,请避免长时间阻塞操作,必要时投递到工作队列
274
- - 图片、文件、语音、视频等消息体只负责内容编解码,不负责上传文件本身
275
-
276
- ## 重新生成 protobuf
277
-
278
- `.proto` 源文件位于 [`proto/`](proto/)。修改后重新生成:
279
-
280
- ```bash
281
- bash proto/gen.sh
282
- ```
283
-
284
- ## 模块结构
285
-
286
- | 模块 | 说明 |
287
- | --- | --- |
288
- | `imbot_sdk.ImBotClient` | 客户端主入口 |
289
- | `imbot_sdk.ClientErrorCode` / `ConnectState` | 错误码与连接状态 |
290
- | `imbot_sdk.models` | 领域模型(`Conversation` / `Message` / `UserInfo` …)|
291
- | `imbot_sdk.messages` | 消息内容模型 |
292
- | `imbot_sdk.pb` | protobuf 类型(`appmessages_pb2` / `connect_pb2` / `chatroom_pb2` / `rtcroom_pb2`)|
293
-
294
- ## 许可证
295
-
296
- [LICENSE](LICENSE)