服务端 API/消息/消息管理/发送消息
# 发送消息

给指定用户或者会话发送消息，支持文本、富文本、可交互的[消息卡片](https://open.larksuite.com/document/ukTMukTMukTM/uczM3QjL3MzN04yNzcDN)、群名片、个人名片、图片、视频、音频、文件、表情包。

**注意事项**：注意事项:
- 需要开启[机器人能力](https://open.larksuite.com/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-enable-bot-ability)  
- 给用户发送消息，需要机器人对用户有[可用性](https://open.larksuite.com/document/home/introduction-to-scope-and-authorization/availability)
- 给群组发送消息，需要机器人在群组中
- 为避免对用户造成打扰，向同一用户发送消息的限频为 ==5 QPS==，向同一群组发送消息的限频为群内机器人共享 ==5 QPS==

## 请求

基本 | &nbsp;
---|---
HTTP URL | https://open.larksuite.com/open-apis/im/v1/messages
HTTP Method | POST
接口频率限制 | [1000 次/分钟、50 次/秒](https://open.larksuite.com/document/ukTMukTMukTM/uUzN04SN3QjL1cDN)
支持的应用类型 | Custom App、Store App
权限要求<br>**调用该 API 所需的权限。开启其中任意一项权限即可调用**<br>开启任一权限即可 | 获取与发送单聊、群组消息(im:message)<br>以应用的身份发消息(im:message:send_as_bot)<br>发送消息V2(im:message:send)
字段权限要求 | **注意事项**：该接口返回体中存在下列敏感字段，仅当开启对应的权限后才会返回；如果无需获取这些字段，则不建议申请<br>获取用户 user ID(contact:user.employee_id:readonly)

### 请求头

名称 | 类型 | 必填 | 描述
---|---|---|---
Authorization | string | 是 | `tenant_access_token`<br>**值格式**："Bearer `access_token`"<br>**示例值**："Bearer t-7f1bcd13fc57d46bac21793a18e560"<br>[了解更多：如何选择与获取 access token](https://open.larksuite.com/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-choose-which-type-of-token-to-use)
Content-Type | string | 是 | **固定值**："application/json; charset=utf-8"

### 查询参数

名称 | 类型 | 必填 | 描述
---|---|---|---
receive_id_type | string | 是 | 消息接收者id类型 open_id/user_id/union_id/email/chat_id<br>**示例值**：open_id<br>**可选值有**：<br>- open_id：标识一个用户在某个应用中的身份。同一个用户在不同应用中的 Open ID 不同。[了解更多：如何获取 Open ID](https://open.larksuite.com/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-openid)<br>- union_id：标识一个用户在某个应用开发商下的身份。同一用户在同一开发商下的应用中的 Union ID 是相同的，在不同开发商下的应用中的 Union ID 是不同的。通过 Union ID，应用开发商可以把同个用户在多个应用中的身份关联起来。[了解更多：如何获取 Union ID？](https://open.larksuite.com/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-union-id)<br>- user_id：标识一个用户在某个租户内的身份。同一个用户在租户 A 和租户 B 内的 User ID 是不同的。在同一个租户内，一个用户的 User ID 在所有应用（包括商店应用）中都保持一致。User ID 主要用于在不同的应用间打通用户数据。[了解更多：如何获取 User ID？](https://open.larksuite.com/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-user-id)。<br>- email：以用户的真实邮箱来标识用户。<br>- chat_id：以群ID来标识群聊。[了解更多：如何获取群ID ](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat-id-description)<br>**当值为 `user_id`，字段权限要求**：<br>获取用户 user ID(contact:user.employee_id:readonly)

### 请求体

名称 | 类型 | 必填 | 描述
---|---|---|---
receive_id | string | 是 | 消息接收者的ID，ID类型应与查询参数==receive_id_type== 对应；推荐使用 OpenID，获取方式可参考文档[如何获取 Open ID？](https://open.larksuite.com/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-obtain-openid)<br>**示例值**："ou_7d8a6e6df7621556ce0d21922b676706ccs"
msg_type | string | 是 | 消息类型 包括：text、post、image、file、audio、media、sticker、interactive、share_chat、share_user等，类型定义请参考[发送消息内容](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/im-v1/message/create_json)<br>**示例值**："text"
content | string | 是 | 消息内容，JSON结构序列化后的字符串。不同msg_type对应不同内容，具体格式说明参考：[发送消息内容](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/im-v1/message/create_json)<br>**注意：**<br>- JSON字符串需进行转义，如换行符转义后为`\\n`<br>- 文本消息请求体最大不能超过150KB<br>- 卡片及富文本消息请求体最大不能超过30KB<br>**示例值**："`{\"text\":\"test content\"}`"
uuid | string | 否 | 由开发者生成的唯一字符串序列，用于发送消息请求去重；持有相同uuid的请求1小时内至多成功发送一条消息<br>**示例值**："选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204"<br>**数据校验规则**：<br>- 最大长度：`50` 字符

### 请求体示例
```json
{
    "receive_id": "ou_7d8a6e6df7621556ce0d21922b676706ccs",
    "msg_type": "text",
    "content": "{\"text\":\"test content\"}",
    "uuid": "选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204"
}
```

**cURL请求示例**

```json 
curl --location --request POST 'https://open.larksuite.com/open-apis/im/v1/messages?receive_id_type=chat_id' \
--header 'Authorization: Bearer t-XXX' \
--header 'Content-Type: application/json; charset=utf-8' \
--data-raw '{
    "receive_id": "oc_84983ff6516d731e5b5f68d4ea2e1da5",
    "msg_type": "text",
    "content": "{\"text\":\"test content\"}"
}'
```

**Python请求示例**
```
import json
import requests

def send():
    url = "https://open.larksuite.com/open-apis/im/v1/messages"
    params = {"receive_id_type":"chat_id"}
    msg = "text content"
    msgContent = {
        "text": msg,
    }
    req = {
        "receive_id": "oc_xxx", # chat id
        "msg_type": "text",
        "content": json.dumps(msgContent)
    }
    payload = json.dumps(req)
    headers = {
        'Authorization': 'Bearer xxx', # your access token
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, params=params, headers=headers, data=payload)
    print(response.headers['X-Tt-Logid']) # for debug or oncall
    print(response.content) # Print Response

if __name__ == '__main__':
    send()
```

Golang请参考[机器人自动拉群报警教程（含 Go 示例代码）](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message-development-tutorial/determine-the-api-and-event-to-call)

## 响应

### 响应体

名称 | 类型 | 描述
---|---|---
code | int | 错误码，非 0 表示失败
msg | string | 错误描述
data | message | \-
message_id | string | 消息id，说明参见：[消息ID说明](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/intro#ac79c1c2)
root_id | string | 根消息id，用于回复消息场景，说明参见：[消息ID说明](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/intro#ac79c1c2)
parent_id | string | 父消息的id，用于回复消息场景，说明参见：[消息ID说明](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/intro#ac79c1c2)
thread_id | string | 消息所属的话题 ID
msg_type | string | 消息类型 包括：text、post、image、file、audio、media、sticker、interactive、share_chat、share_user等，类型定义请参考[接收消息内容](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/im-v1/message/events/message_content)
create_time | string | 消息生成的时间戳（毫秒）
update_time | string | 消息更新的时间戳（毫秒）
deleted | boolean | 消息是否被撤回
updated | boolean | 消息是否被更新
chat_id | string | 所属的群
sender | sender | 发送者，可以是用户或应用
id | string | 该字段标识发送者的id
id_type | string | 该字段标识发送者的id类型<br>**可选值有：**<br>- `open_id`<br>- `app_id`
sender_type | string | 该字段标识发送者的类型<br>**可选值有：**<br>- `user`: 用户<br>- `app`: 应用<br>- `anonymous`: 匿名<br>- `unknown`: 未知
tenant_key | string | 为租户在Lark上的唯一标识，用来换取对应的tenant_access_token，也可以用作租户在应用里面的唯一标识
body | message_body | 消息内容
content | string | 消息内容，json结构序列化后的字符串。不同msg_type对应不同内容。消息类型 包括：text、post、image、file、audio、media、sticker、interactive、share_chat、share_user等，类型定义请参考：[接收消息内容](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/im-v1/message/events/message_content)
mentions | mention\[\] | 被@的用户或机器人的id列表
key | string | 被@的用户或机器人的序号。例如，第3个被@到的成员，值为“@_user_3”
id | string | 被@的用户或者机器人的open_id
id_type | string | 被@的用户或机器人 id 类型，目前仅支持 `open_id` ([什么是 Open ID？](https://open.larksuite.com/document/home/user-identity-introduction/open-id))
name | string | 被@的用户或机器人的姓名
tenant_key | string | 为租户在Lark上的唯一标识，用来换取对应的tenant_access_token，也可以用作租户在应用里面的唯一标识
upper_message_id | string | 合并转发消息中，上一层级的消息id message_id，说明参见：[消息ID说明](https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/intro#ac79c1c2)

### 响应体示例
```json
{
    "code": 0,
    "msg": "success",
    "data": {
        "message_id": "om_dc13264520392913993dd051dba21dcf",
        "root_id": "om_40eb06e7b84dc71c03e009ad3c754195",
        "parent_id": "om_d4be107c616aed9c1da8ed8068570a9f",
        "thread_id": "omt_d4be107c616a",
        "msg_type": "card",
        "create_time": "1615380573411",
        "update_time": "1615380573411",
        "deleted": false,
        "updated": false,
        "chat_id": "oc_5ad11d72b830411d72b836c20",
        "sender": {
            "id": "cli_9f427eec54ae901b",
            "id_type": "app_id",
            "sender_type": "app",
            "tenant_key": "736588c9260f175e"
        },
        "body": {
            "content": "{\"text\":\"@_user_1 test content\"}"
        },
        "mentions": [
            {
                "key": "@_user_1",
                "id": "ou_155184d1e73cbfb8973e5a9e698e74f2",
                "id_type": "open_id",
                "name": "Tom",
                "tenant_key": "736588c9260f175e"
            }
        ],
        "upper_message_id": "om_40eb06e7b84dc71c03e009ad3c754195"
    }
}
```

### 错误码

HTTP状态码 | 错误码 | 描述 | 排查建议
---|---|---|---
400 | 230001 | Your request contains an invalid request parameter. | 参数错误，请根据接口返回的错误信息并参考文档检查输入参数。
400 | 230002 | The bot can not be outside the group. | 机器人不在对应群组中。
400 | 230006 | Bot ability is not activated. | [机器人能力](https://open.larksuite.com/document/uAjLw4CM/ugTN1YjL4UTN24CO1UjN/trouble-shooting/how-to-enable-bot-ability)未启用 。可在[开发者后台](https://open.larksuite.com/app) -> 应用能力 -> 添加应用能力页面添加机器人功能，发布新版本后生效。
400 | 230013 | Bot has NO availability to this user. | 机器人对用户没有[可用性](https://open.larksuite.com/document/home/introduction-to-scope-and-authorization/availability)。可在[开发者后台](https://open.larksuite.com/app) -> 应用发布 -> 版本管理与发布 -> 创建版本页面编辑应用的可用范围，发布新版本后生效。
400 | 230015 | P2P chat can NOT be shared. | 私聊会话不允许被分享。
400 | 230017 | Bot is NOT the owner of the resource. | 机器人不是资源的拥有者。
400 | 230018 | These operations are NOT allowed at current group settings. | 当前操作被群设置禁止，请检查群设置或联系群管理员。
400 | 230019 | The topic does NOT exist. | 当前话题不存在。
400 | 230020 | This operation triggers the frequency limit. | 当前操作触发限频，请降低请求频率。
400 | 230022 | The content of the message contains sensitive information. | 消息包含敏感信息，请检查消息内容。
400 | 230025 | The length of the message content reaches its limit. | 消息体长度超出限制。文本消息最大不能超过150KB、卡片及富文本消息最大不能超过30KB。需要注意：<br>- 若使用卡片模板（template_id）发送消息，实际大小也包含模板对应的卡片数据大小。<br>- 若消息中包含大量样式标签，会使实际消息体长度大于您输入的请求体长度。
400 | 230027 | Lack of necessary permissions. | 无权进行本操作，可能的原因有：<br>1. 缺少相应权限，请根据错误信息进行排查；<br>2. 未检查到用户授权信息；<br>3. 暂不支持在外部群中进行本操作。
400 | 230099 | Failed to create card content. | 创建卡片失败。如有报错信息可根据报错信息排查解决；如无报错信息则需自行检查构造的卡片内容是否有问题。
400 | 230028 | The messages do NOT pass the audit. | 消息DLP审查未通过，当消息内容中含有明文电话号码、明文个人邮箱等内容时可能会触发该错误；请根据接口返回的错误信息检查消息内容。
400 | 230029 | User has resigned. | 用户已离职。
400 | 230034 | The receive_id is invalid. | 请求参数中的receive_id不合法，请检查。
400 | 230035 | Send Message Permission deny. | 没有发送消息的权限，请排查群是否已开启禁言、被对方屏蔽或受到租户维度沟通权限的管控。
400 | 230036 | Tenant crypt key has been deleted. | 租户加密密钥已被删除，请联系企业管理员。
400 | 230038 | Cross tenant p2p chat operate forbid. | 跨租户的单聊不允许通过本接口发送消息。
400 | 230049 | The message is being sent. | 消息正在发送中，请稍后。
400 | 230053 | The user has stopped the bot from sending messages. | 用户已设置不再接收机器人消息，无法主动给用户发送单聊消息。
400 | 230054 | This type of message is unavailable in the connection group. | 私有互通群不支持发送特定的消息类型。如卡片消息。
400 | 230055 | The type of file upload does not match the type of message being sent. | 文件上传时选择的类型与发送的消息类型不匹配。
400 | 230075 | Sending encrypted messages is not supported. | 不支持向密聊、密盾聊中发送消息。
400 | 232009 | Your request specifies a chat which has already been dissolved. | 群组已被解散。

其他未列出的错误码请参见[服务端通用错误码](https://open.larksuite.com/document/ukTMukTMukTM/ugjM14COyUjL4ITN)。

