DingTalk Stream SDK for Python

0.24.3 · active · verified Mon Apr 13

The `dingtalk-stream` library is the official Python SDK for interacting with the DingTalk Streaming API. It enables developers to build chatbots, AI assistants, and other applications that receive real-time messages and events from DingTalk, and send messages or interact with cards. The current version is 0.24.3, with an active release cadence addressing features and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `DingTalkStreamClient`, register a default handler for incoming messages, and start the asynchronous client. Ensure `DINGTALK_APP_KEY` and `DINGTALK_APP_SECRET` environment variables are set for authentication.

import os
import asyncio
from dingtalk_stream import DingTalkStreamClient
from dingtalk_stream.message import DingTalkMessageType

async def quickstart_handler(msg):
    """A simple message handler that prints received message info."""
    print(f"\nReceived message type: {msg.type}\nContent: {msg.data}")
    if msg.type == DingTalkMessageType.INTERACTION_MESSAGE:
        # For interactive messages, you might want to reply to a card.
        # Example (requires card_instance_id and conversation_id from msg):
        # await msg.reply_to_card(card_data={'content': 'Acknowledged!'})
        print("Received an interactive message.")

async def main():
    app_key = os.environ.get("DINGTALK_APP_KEY", "YOUR_APP_KEY")
    app_secret = os.environ.get("DINGTALK_APP_SECRET", "YOUR_APP_SECRET")

    if app_key == "YOUR_APP_KEY" or app_secret == "YOUR_APP_SECRET":
        print("Please set DINGTALK_APP_KEY and DINGTALK_APP_SECRET environment variables.")
        print("Example: export DINGTALK_APP_KEY='...' DINGTALK_APP_SECRET='...' ")
        return

    client = DingTalkStreamClient(
        client_id=app_key,
        client_secret=app_secret
    )

    client.set_default_handler(quickstart_handler)

    print("DingTalk Stream Client starting... (Press Ctrl+C to stop)")
    try:
        await client.start()
    except asyncio.CancelledError:
        print("Client start cancelled.")
    finally:
        await client.stop()
        print("Client stopped.")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Application terminated by user.")

view raw JSON →