Skip to main content

JuggleIM Python Bot SDK — WebSocket long-connection IM client for bots and server-side agents

Project description

imbot-sdk-python

English | 简体中文

PyPI version Python versions License

imbot-sdk-python is the JuggleIM Python SDK. It keeps a long-lived WebSocket connection to the IM service, making it a good fit for bots, server-side message agents, or any Python program that needs to actively send and receive messages. It covers connection management, messaging, conversation queries, history, chatrooms, user status, RTC rooms and file credential queries.

Installation

pip install imbot-sdk-python

Dependencies (protobuf>=5.0, websocket-client>=1.6) are installed automatically. Python 3.8+.

Install from source:

git clone https://github.com/juggleim/imbot-sdk-python.git
cd imbot-sdk-python
pip install .

Test environment

Item Value
Server API http://127.0.0.1
WebSocket wss://127.0.0.1
AppKey AppKey

A user token is issued by your JuggleIM app server / console using your AppKey

  • AppSecret via the Server API. The SDK itself only establishes the connection and sends/receives messages.

Feature overview

  • Connection management: connect, disconnect, logout, heartbeat keep-alive, automatic reconnect.
  • Messaging: send/receive for private, group, chatroom and public-channel conversations.
  • Message management: history query, recall, modify, mark-read, search, top messages.
  • Conversation management: list, unread count, top, mute, tags.
  • User & group info: user profile, friend profile, group info, online-status subscription.
  • Chatroom: join/quit, chatroom messages, attribute sync.
  • RTC: create / join / query / quit RTC rooms.
  • File: credential query via get_file_cred.

Quick start

1. Create a client

from imbot_sdk import ImBotClient

client = ImBotClient("wss://127.0.0.1", "your-appkey")

Notes:

  • Pass the base address; the SDK appends the path automatically to form ws://host/imbot or wss://host/imbot.
  • client.platform defaults to "Bot".
  • client.auto_reconnect defaults to True.

2. Connect

code, ack = client.connect("your-token")

Notes:

  • On success code == ClientErrorCode.SUCCESS.
  • After success ack.userId is written to client.user_id.
  • connect may only be called while disconnected; a repeated connect returns ClientErrorCode.CONNECT_EXISTED.
  • After an explicit disconnect() or logout(), auto-reconnect stops.

3. Two ways to receive messages

Prefer the high-level listener (you receive a decoded Message):

from imbot_sdk import MessageListener, messages

class MyListener(MessageListener):
    def on_message_receive(self, msg):
        if isinstance(msg.msg_content, messages.TextMessage):
            print("text:", msg.msg_content.content)

client.add_message_listener(MyListener())

If you want the raw protobuf payloads:

client.on_message_callback = lambda down_msg: print(down_msg)
client.on_stream_msg_callback = lambda stream_msg: print(stream_msg)

4. Send a message

from imbot_sdk import Conversation, messages
from imbot_sdk.pb import appmessages_pb2 as pb

text = messages.TextMessage("hello from imbot-sdk-python")
up = client.build_up_msg(text, client_uid="bot-1")

conv = Conversation(conversation_type=pb.Private, conversation="target-user-id")
code, ack = client.send_message(conv, up)
# ack.msgId / ack.msgSeqNo carry the server's acknowledgement

build_up_msg encodes a content model into UpMsg.msgType / msgContent / flags; you can also construct a pb.UpMsg directly.

Full example: connect, listen, echo

import time
from imbot_sdk import ImBotClient, Conversation, MessageListener, ClientErrorCode, messages
from imbot_sdk.pb import appmessages_pb2 as pb

class Echo(MessageListener):
    def __init__(self, client):
        self.client = client
    def on_message_receive(self, msg):
        c = msg.msg_content
        if isinstance(c, messages.TextMessage) and msg.sender_id != self.client.user_id:
            up = self.client.build_up_msg(messages.TextMessage("echo: " + c.content),
                                          client_uid="echo-%d" % time.time_ns())
            self.client.send_message(msg.conversation, up)

client = ImBotClient("wss://127.0.0.1", "AppKey")
client.add_message_listener(Echo(client))

code, ack = client.connect("your-token")
assert code == ClientErrorCode.SUCCESS
print("connected:", ack.userId)

# Proactively send a private message to a user
up = client.build_up_msg(messages.TextMessage("hi"), client_uid="greet-1")
client.send_message(Conversation(conversation_type=pb.Private, conversation="target-user-id"), up)

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    client.disconnect()

A runnable version lives in examples/echo_bot.py. The recommended way is .env + the launch script:

cp examples/.env.example examples/.env
# edit examples/.env, at least set IMBOT_TOKEN (IMBOT_TARGET optional)
bash examples/run.sh

run.sh loads examples/.env and starts the echo bot; extra arguments are passed through (e.g. bash examples/run.sh --target some-user-id). You can also skip the script and pass args / export env vars directly:

python examples/echo_bot.py --token <your-token> --target <target-user-id>

Configuration (env vars / .env):

Variable Description Required
IMBOT_TOKEN User token Yes
IMBOT_TARGET Target user id to greet on startup No
IMBOT_ADDRESS WebSocket base address No
IMBOT_APPKEY App AppKey No

Additional notes:

  • Use pb.Private for private chats, pb.Group for groups, pb.Chatroom for chatrooms, pb.PublicChannel for public channels.
  • Chatroom messages can also be sent via client.send_chatroom_msg(chatroom_id, up_msg).
  • A received msg.msg_content is already decoded by content type, so you can isinstance-check it directly.

Message types

Built-in content models live in imbot_sdk.messages:

Type Identifier Class
Text jg:text TextMessage
Image jg:img ImageMessage
File jg:file FileMessage
Video jg:video VideoMessage
Voice jg:voice VoiceMessage
Stream text jg:streamtext StreamTextMessage
Recall notice jg:recallinfo RecallInfoMessage
Merged message jg:merge MergeMessage
Thumbnail-packed image jg:tpimg ThumbnailPackedImageMessage
Snapshot-packed video jg:spvideo SnapshotPackedVideoMessage

For content types that are not built in, the SDK falls back to messages.UnknownMessage. The JSON encode/decode fields of these models are stable, so messages interoperate with the other JuggleIM client SDKs.

Common APIs

See docs/API.md for the full method list. Naming follows Python conventions (snake_case).

Connection & state

connect(token), reconnect(), disconnect(), logout(), ping(), add_connection_status_change_listener(listener)

Messages

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)

Conversations

get_conversation(req), get_conversations(req), sync_conversations(req), clear_unread_count(req), set_conversation_top(req), set_mute(req), delete_conversations(req)

Users, groups, status

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)

Chatroom

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)

RTC

create_rtc_room(req), join_rtc_room(req), qry_rtc_room(room_id), quit_rtc_room(room_id), rtc_invite(req)

File

get_file_cred(req)

The SDK provides file credential queries; the actual file upload/download flow must be handled by your application against your storage service.

Usage notes

  • publish and query both require the connection state to be CONNECTED, otherwise they return ClientErrorCode.CONNECT_CLOSED.
  • Sends and queries wait up to 10 seconds for an ACK, returning ClientErrorCode.SEND_TIMEOUT / ClientErrorCode.QUERY_TIMEOUT on timeout.
  • The SDK handles heartbeats automatically; if no downstream data arrives for more than two heartbeat windows (~20s), it disconnects and tries to reconnect.
  • Message listener callbacks run on internal threads — avoid long blocking work, and hand off to a worker queue if needed.
  • Image / file / voice / video content models only encode/decode content; they do not upload the underlying files.

Regenerating protobuf

The .proto sources live in proto/. Regenerate after editing:

bash proto/gen.sh

Module layout

Module Description
imbot_sdk.ImBotClient Main client entry point
imbot_sdk.ClientErrorCode / ConnectState Error codes and connection state
imbot_sdk.models Domain models (Conversation / Message / UserInfo …)
imbot_sdk.messages Message content models
imbot_sdk.pb Protobuf types (appmessages_pb2 / connect_pb2 / chatroom_pb2 / rtcroom_pb2)

License

LICENSE (Apache-2.0)

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

imbot_sdk_python-0.1.1.tar.gz (61.8 kB view details)

Uploaded Source

Built Distribution

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

imbot_sdk_python-0.1.1-py3-none-any.whl (43.0 kB view details)

Uploaded Python 3

File details

Details for the file imbot_sdk_python-0.1.1.tar.gz.

File metadata

  • Download URL: imbot_sdk_python-0.1.1.tar.gz
  • Upload date:
  • Size: 61.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for imbot_sdk_python-0.1.1.tar.gz
Algorithm Hash digest
SHA256 43b55d74f80e75e20ab02cc9992c710e7e352891469c0905c6766488ad18133d
MD5 ecb67eef037d5580ff309a9895ddf2fa
BLAKE2b-256 3cdb2e2f537b21717a5df686e21c73dcead2c108a9f21660d5804a4739a48c55

See more details on using hashes here.

File details

Details for the file imbot_sdk_python-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for imbot_sdk_python-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 288218161e1486f5e3dc4e95c4b8f2855e0b56fd3a0076bc6fc2eebce5f73952
MD5 c6515fd7a1ec7900b090809918156e61
BLAKE2b-256 0c1c629214dd405a6b648f7374ab4fa2fec5fd2ccefc2d87dbfeca79a23d7ecc

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