Skip to main content
Call this API to send bot messages to multiple Person-to-Bot chats (Direct Message between users and bots) in batch. This API is suitable for scenarios where you need to send bot messages to multiple users (up to 20) in batch, such as organization notifications and system alert pushes.

API call description

This API supports bots of internal apps. For more information, see Configure an enterprise bot.

Request

Basic information

FieldValue
HTTP URLhttps://api.dingtalk.io/v1.0/robot/oToMessages/batchSend
HTTP MethodPOST
Supported app typesappType-Internal app appType-Third-party enterprise app
Permissionspermission-qyapi_robot_sendmsg-Permission to send messages with a bot in your organization

Request header

NameTypeRequiredDescription
x-acs-dingtalk-access-tokenStringYesThe access credential used to call this API. Obtain it in the following ways: - For internal apps, call the Get the access token of an internal app API. - For third-party enterprise apps, call the Get the access token of an organization authorized to a third-party app API.

Request body

NameTypeRequiredDescription
robotCodeStringYesThe code of the bot. This parameter must use the robotCode of an internal app bot. For more information, see Bot ID.
userIdsArray of StringYesThe list of user IDs that receive the message. You can pass up to 20 user IDs at a time. You can obtain user IDs by calling the Query user details API or the Get the list of user IDs in a department API.
msgKeyStringYesThe message template key. For more information, see Message types supported by enterprise bots.
msgParamStringYesThe message template parameters. For more information, see Message types supported by enterprise bots.

Request example

HTTP
POST /v1.0/robot/oToMessages/batchSend HTTP/1.1
Host:api.dingtalk.io
x-acs-dingtalk-access-token:asdasdasdasd
Content-Type:application/json

{
  "robotCode" : "dingxxxxxx",
  "userIds" : [ "manager1234" ],
  "msgKey" : "sampleMarkdown",
  "msgParam" : "{\"text\": \"hello text\",\"title\": \"hello title\"}"
}
Java
// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sample;

import com.aliyun.tea.*;
import com.aliyun.teautil.*;
import com.aliyun.teautil.models.*;
import com.aliyun.dingtalkrobot_1_0.*;
import com.aliyun.dingtalkrobot_1_0.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;

public class Sample {

    /**
     * Initialize the account client with a Token
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkrobot_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkrobot_1_0.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkrobot_1_0.Client client = Sample.createClient();
        BatchSendOTOHeaders batchSendOTOHeaders = new BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = "<your access token>";
        BatchSendOTORequest batchSendOTORequest = new BatchSendOTORequest()
                .setRobotCode("dingxxxxxx")
                .setUserIds(java.util.Arrays.asList(
                    "manager1234"
                ))
                .setMsgKey("sampleMarkdown")
                .setMsgParam("{\"text\": \"hello text\",\"title\": \"hello title\"}");
        try {
            client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err contains the code and message attributes, which help locate the issue
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err contains the code and message attributes, which help locate the issue
            }

        }        
    }
}
Python
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import sys

from typing import List

from alibabacloud_dingtalk.robot_1_0.client import Client as dingtalkrobot_1_0Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dingtalk.robot_1_0 import models as dingtalkrobot__1__0_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> dingtalkrobot_1_0Client:
        """
        Initialize the account client with a Token
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        config.protocol = 'https'
        config.region_id = 'central'
        return dingtalkrobot_1_0Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        batch_send_otoheaders = dingtalkrobot__1__0_models.BatchSendOTOHeaders()
        batch_send_otoheaders.x_acs_dingtalk_access_token = '<your access token>'
        batch_send_otorequest = dingtalkrobot__1__0_models.BatchSendOTORequest(
            robot_code='dingxxxxxx',
            user_ids=[
                'manager1234'
            ],
            msg_key='sampleMarkdown',
            msg_param='{"text": "hello text","title": "hello title"}'
        )
        try:
            client.batch_send_otowith_options(batch_send_otorequest, batch_send_otoheaders, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains the code and message attributes, which help locate the issue
                pass

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        batch_send_otoheaders = dingtalkrobot__1__0_models.BatchSendOTOHeaders()
        batch_send_otoheaders.x_acs_dingtalk_access_token = '<your access token>'
        batch_send_otorequest = dingtalkrobot__1__0_models.BatchSendOTORequest(
            robot_code='dingxxxxxx',
            user_ids=[
                'manager1234'
            ],
            msg_key='sampleMarkdown',
            msg_param='{"text": "hello text","title": "hello title"}'
        )
        try:
            await client.batch_send_otowith_options_async(batch_send_otorequest, batch_send_otoheaders, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains the code and message attributes, which help locate the issue
                pass

if __name__ == '__main__':
    Sample.main(sys.argv[1:])
PHP
<?php

// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Dingtalk\Vrobot_1_0\Dingtalk;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dingtalk\Vrobot_1_0\Models\BatchSendOTOHeaders;
use AlibabaCloud\SDK\Dingtalk\Vrobot_1_0\Models\BatchSendOTORequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Sample {

    /**
     * Initialize the account client with a Token
     * @return Dingtalk Client
     */
    public static function createClient(){
        $config = new Config([]);
        $config->protocol = "https";
        $config->regionId = "central";
        return new Dingtalk($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $client = self::createClient();
        $batchSendOTOHeaders = new BatchSendOTOHeaders([]);
        $batchSendOTOHeaders->xAcsDingtalkAccessToken = "<your access token>";
        $batchSendOTORequest = new BatchSendOTORequest([
            "robotCode" => "dingxxxxxx",
            "userIds" => [
                "manager1234"
            ],
            "msgKey" => "sampleMarkdown",
            "msgParam" => "{\"text\": \"hello text\",\"title\": \"hello title\"}"
        ]);
        try {
            $client->batchSendOTOWithOptions($batchSendOTORequest, $batchSendOTOHeaders, new RuntimeOptions([]));
        }
        catch (Exception $err) {
            if (!($err instanceof TeaError)) {
                $err = new TeaError([], $err->getMessage(), $err->getCode(), $err);
            }
            if (!Utils::empty_($err->code) && !Utils::empty_($err->message)) {
                // err contains the code and message attributes, which help locate the issue
            }
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));
Go
// This file is auto-generated, don't edit it. Thanks.
package main

import (
  "os"
  util  "github.com/alibabacloud-go/tea-utils/service"
  dingtalkrobot_1_0  "github.com/alibabacloud-go/dingtalk/robot_1_0"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/client"
  "github.com/alibabacloud-go/tea/tea"
)

/**
 * Initialize the account client with a Token
 * @return Client
 * @throws Exception
 */
func CreateClient () (_result *dingtalkrobot_1_0.Client, _err error) {
  config := &openapi.Config{}
  config.Protocol = tea.String("https")
  config.RegionId = tea.String("central")
  _result = &dingtalkrobot_1_0.Client{}
  _result, _err = dingtalkrobot_1_0.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  client, _err := CreateClient()
  if _err != nil {
    return _err
  }

  batchSendOTOHeaders := &dingtalkrobot_1_0.BatchSendOTOHeaders{}
  batchSendOTOHeaders.XAcsDingtalkAccessToken = tea.String("<your access token>")
  batchSendOTORequest := &dingtalkrobot_1_0.BatchSendOTORequest{
    RobotCode: tea.String("dingxxxxxx"),
    UserIds: []*string{tea.String("manager1234")},
    MsgKey: tea.String("sampleMarkdown"),
    MsgParam: tea.String("{\"text\": \"hello text\",\"title\": \"hello title\"}"),
  }
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    _, _err = client.BatchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, &util.RuntimeOptions{})
    if _err != nil {
      return _err
    }

    return nil
  }()

  if tryErr != nil {
    var err = &tea.SDKError{}
    if _t, ok := tryErr.(*tea.SDKError); ok {
      err = _t
    } else {
      err.Message = tea.String(tryErr.Error())
    }
    if !tea.BoolValue(util.Empty(err.Code)) && !tea.BoolValue(util.Empty(err.Message)) {
      // err contains the code and message attributes, which help locate the issue
    }

  }
  return _err
}

func main() {
  err := _main(tea.StringSlice(os.Args[1:]))
  if err != nil {
    panic(err)
  }
}
Node.js
// This file is auto-generated, don't edit it
import Util, * as $Util from '@alicloud/tea-util';
import dingtalkrobot_1_0, * as $dingtalkrobot_1_0 from '@alicloud/dingtalk/robot_1_0';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import * as $tea from '@alicloud/tea-typescript';

export default class Client {

  /**
   * Initialize the account client with a Token
   * @return Client
   * @throws Exception
   */
  static createClient(): dingtalkrobot_1_0 {
    let config = new $OpenApi.Config({ });
    config.protocol = "https";
    config.regionId = "central";
    return new dingtalkrobot_1_0(config);
  }

  static async main(args: string[]): Promise<void> {
    let client = Client.createClient();
    let batchSendOTOHeaders = new $dingtalkrobot_1_0.BatchSendOTOHeaders({ });
    batchSendOTOHeaders.xAcsDingtalkAccessToken = "<your access token>";
    let batchSendOTORequest = new $dingtalkrobot_1_0.BatchSendOTORequest({
      robotCode: "dingxxxxxx",
      userIds: [
        "manager1234"
      ],
      msgKey: "sampleMarkdown",
      msgParam: "{\"text\": \"hello text\",\"title\": \"hello title\"}",
    });
    try {
      await client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new $Util.RuntimeOptions({ }));
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        // err contains the code and message attributes, which help locate the issue
      }

    }    
  }

}

Client.main(process.argv.slice(2));
C#
// This file is auto-generated, don't edit it. Thanks.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {

        /**
         * Initialize the account client with a Token
         * @return Client
         * @throws Exception
         */
        public static AlibabaCloud.SDK.Dingtalkrobot_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkrobot_1_0.Client(config);
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.SDK.Dingtalkrobot_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkrobot_1_0.Models.BatchSendOTOHeaders batchSendOTOHeaders = new AlibabaCloud.SDK.Dingtalkrobot_1_0.Models.BatchSendOTOHeaders();
            batchSendOTOHeaders.XAcsDingtalkAccessToken = "<your access token>";
            AlibabaCloud.SDK.Dingtalkrobot_1_0.Models.BatchSendOTORequest batchSendOTORequest = new AlibabaCloud.SDK.Dingtalkrobot_1_0.Models.BatchSendOTORequest
            {
                RobotCode = "dingxxxxxx",
                UserIds = new List<string>
                {
                    "manager1234"
                },
                MsgKey = "sampleMarkdown",
                MsgParam = "{\"text\": \"hello text\",\"title\": \"hello title\"}",
            };
            try
            {
                client.BatchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err contains the code and message attributes, which help locate the issue
                }
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err contains the code and message attributes, which help locate the issue
                }
            }
        }

    }
}
C
// This file is auto-generated, don't edit it. Thanks.

#include <alibabacloud/dingtalkrobot__1__0.hpp>
#include <alibabacloud/open_api.hpp>
#include <boost/any.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>

using namespace std;

Alibabacloud_Dingtalkrobot_1_0::Client createClient() {
  shared_ptr<Alibabacloud_OpenApi::Config> config = make_shared<Alibabacloud_OpenApi::Config>();
  config->protocol = make_shared<string>("https");
  config->regionId = make_shared<string>("central");
  return Alibabacloud_Dingtalkrobot_1_0::Client(config);
}

int main(int argc, char *args[]) {
  args;
  shared_ptr<Alibabacloud_Dingtalkrobot_1_0::Client> client = make_shared<Alibabacloud_Dingtalkrobot_1_0::Client>(createClient());
  shared_ptr<Alibabacloud_Dingtalkrobot_1_0::BatchSendOTOHeaders> batchSendOTOHeaders = make_shared<Alibabacloud_Dingtalkrobot_1_0::BatchSendOTOHeaders>();
  batchSendOTOHeaders->xAcsDingtalkAccessToken = make_shared<string>("<your access token>");
  shared_ptr<Alibabacloud_Dingtalkrobot_1_0::BatchSendOTORequest> batchSendOTORequest = make_shared<Alibabacloud_Dingtalkrobot_1_0::BatchSendOTORequest>(map<string, boost::any>({
    {"robotCode", boost::any(string("dingxxxxxx"))},
    {"userIds", boost::any(vector<string>({
      "manager1234"
    }))},
    {"msgKey", boost::any(string("sampleMarkdown"))},
    {"msgParam", boost::any(string("{"text": "hello text","title": "hello title"}"))}
  }));
  try {
    client->batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, make_shared<Darabonba_Util::RuntimeOptions>(Darabonba_Util::RuntimeOptions()));
  }
  catch (std::exception &err) {
    if (!Darabonba_Util::Client::empty(err.code) && !Darabonba_Util::Client::empty(err.message)) {
      // err contains the code and message attributes, which help locate the issue
    }
  }
}

Response

Response body

NameTypeDescription
processQueryKeyStringThe message ID. You can use it in the Batch query the read status of bot messages in Person-to-Bot chats API and the Batch recall bot messages in Person-to-Bot chats API to query whether the messages have been read and to recall messages.
invalidStaffIdListArray of StringThe list of invalid user IDs.
flowControlledStaffIdListArray of StringThe list of rate-limited user IDs.

Response body example

HTTP/1.1 200 OK
Content-Type:application/json

{
  "processQueryKey" : "zcxxczasdafasd",
  "invalidStaffIdList" : [ "manage25231" ],
  "flowControlledStaffIdList" : [ "manage25232" ]
}

Error codes

If an error is returned when you call this API, find the solution in the Global error codes document based on the error message.
HttpCodeError codeError messageDescription
400invalidParameter.robotCode.empty%sThe robotCode is invalid.
400invalidParameter.userIds.empty%sThe user ID list is empty.
400invalidParameter.userIds.overMax%sThe user ID list exceeds the maximum limit of 100. Split the user IDs into multiple arrays with a length of no more than 100 and call this API in batches.
400invalidParameter.msgKey.empty%sThe msgKey is empty.
400invalidParameter.msgKey.invalid%sThe msgKey is invalid. Pass a correct msgKey.
400invalidParameter.msgParam.invalid%sThe msgParam format is invalid. It must be in JSON format.
400invalidParameter.param.invalid%sThe parameter is invalid. Check whether any parameter is empty.
400invalidParameter.msg.unsupport%sThe message type is not supported.
400invalidParameter.msgParam.tooLong%sThe message content is too long. Reduce the content length.
400invalidParameter.robotCode.notExsit%sThe bot does not exist. Check whether the bot corresponding to the robotCode is installed in your organization.
400invalidParameter.msgBody.invalid%sThe message body must be in JSON format.
400invalidParameter.userId.empty%sThe staffId is missing.
400invalidParameter.token.invalid%sThe token is not authorized.
400invalidParameter.robotCode.invalid%sThe robotCode is invalid.
400token.notExisted%sThe TOKEN does not exist.
400template.not.existed%sThe bot template does not exist. Check whether the robotCode is correct.
400template.stopped%sThe bot template has been disabled. Check the bot status.
400miss.param.text%sThe message content is invalid. The text attribute is required.
400miss.param.contentOfText%sThe message content is invalid. The text->content attribute is required.
400miss.param.link%sThe message content is invalid. The link attribute is required.
400miss.param.textOfLink%sThe message content is invalid. The link->text attribute is required.
400miss.param.titleOfLink%sThe message content is invalid. The link->title attribute is required.
400miss.param.messageUrlOfLink%sThe message content is invalid. The link->messageUrl attribute is required.
400miss.param.markdown%sThe message content is invalid. The markdown attribute is required.
400miss.param.markdownTotitle%sThe message content is invalid. The markdown->text attribute is required.
400miss.param.markdownTotext%sThe message content is invalid. The markdown->text attribute is required.
400miss.param.actionCard%sThe message content is invalid. The actionCard attribute is required.
400miss.param.actionCardTotitle%sThe message content is invalid. The actionCard->title attribute is required.
400miss.param.actionCardTotext%sThe message content is invalid. The actionCard->text attribute is required.
400miss.param.actionCardTosingleTitle%sThe message content is invalid. The actionCard->singleTitle attribute is required.
400miss.param.actionCardTosingleUrl%sThe message content is invalid. The actionCard->singleURL attribute is required.
400miss.param.actionCardTobtns%sThe message content is invalid. The actionCard->btns attribute is required.
400miss.param.actionCardTobtnsTotitle%sThe message content is invalid. The actionCard->btns->title attribute is required.
400miss.param.actionCardTobtnsToactionUrl%sThe message content is invalid. The actionCard->btns->actionURL attribute is required.
400invalid.param.actionCardTobtnOrientation%sThe message content is invalid. The actionCard->btnOrientation value is incorrect.
400invalid.param.actionCardTocanForward%sThe message content is invalid. The actionCard->canForward value is incorrect.
400miss.param.feedCard%sThe message content is invalid. The feedCard attribute is required.
400miss.param.feedCardTolinks%sThe message content is invalid. The feedCard->links attribute is required.
400miss.param.feedCardTolinksTotitle%sThe message content is invalid. The feedCard->links->title attribute is required.
400miss.param.feedCardTolinksTomessageUrl%sThe message content is invalid. The feedCard->links->messageURL attribute is required.
400miss.param.feedCardTolinksTopicUrl%sThe message content is invalid. The feedCard->links->picURL attribute is required.
400miss.param.photo%sThe message content is invalid. The photo attribute is required.
400miss.param.photoTophotoUrl%sThe message content is invalid. The photo->photoURL attribute is required.
400miss.param.image%sThe message content is invalid. The image attribute is required.
400miss.param.imageTopicUrl%sThe message content is invalid. The image->picURL attribute is required.
400miss.param.beautifulCard%sThe message content is invalid. The beautifulCard attribute is required.
400miss.param.beautifulCardToimage%sThe message content is invalid. The beautifulCard->image attribute is required.
400miss.param.beautifulCardTotitle%sThe message content is invalid. The beautifulCard->title attribute is required.
400miss.param.beautifulCardToactionUrl%sThe message content is invalid. The beautifulCard->actionUrl attribute is required.
400miss.param.beautifulCardTointroduction%sThe message content is invalid. The beautifulCard->introduction attribute is required.
400send.byToken.tooFast%sA rate limit error occurred when sending with the TOKEN. Try again later.
400send.too.fast%sMessages are being sent too frequently. Try again later.
400send.forbidden%sThis bot is prohibited from sending messages.
400ip.not.match%sThe IP does not match. You do not have permission to send messages with this bot.
400keywords.not.match%sThe keywords for the bot to send messages do not match.
400sign.not.match%sThe signature does not match. You do not have permission to send messages.
400contain.unsafe.url%sThe content contains unsafe external links.
400contain.notAllowed.text%sThe content contains inappropriate text.
400contain.notAllowed.picture%sThe content contains inappropriate images.
400contain.notAllowed.content%sThe content contains inappropriate content.
400illegal.receivers%sThe recipient list is invalid.
400receivers.exceed%sThe recipient list exceeds the limit.
400illegal.excludes%sThe exclusion list is invalid.
400too.many.group%sSending is rate-limited due to high frequency.
400too.many.people%sSending is rate-limited due to high frequency.
400bot.forbidden.sendMessage%sThe account has been muted.
400session.notExisted%sThe session does not exist.
400session.expired%sThe session has expired.
400staffId.notExisted%sThe staffId does not exist.
400chatbotId.notAllow.sendOTO%sInitiating a Direct Message is not allowed. Check whether the bot status is enabled.
400robot.oto.notExist%sNo valid bot Direct Message chat exists.
400sendMessage.model.notMatch%sNo matching message model.
400miss.param.file%sThe message content is invalid. The file attribute is required.
400miss.param.video%sThe message content is invalid. The video->videoMediaId attribute is required.
400miss.param.audio%sThe message content is invalid. The audio attribute is required.
500system.error%sUnknown system error.