> ## Documentation Index
> Fetch the complete documentation index at: https://help.dingtalk.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 社内ボットからグループチャットへメッセージを送信

> @ メンション時に API インターフェースを呼び出して社内ボットがグループチャットにメッセージを返信します

社内ボットを使ってグループ内でメッセージを送信する場合は、本ドキュメントの手順を参考にしてください。

## 要件の明確化

正式に開発する前に、概要を把握しておきましょう。本ドキュメントでは、Stream モードにおいて、グループ内で社内ボットに対して @ メンションを行い、続いて [ボットからグループチャットへメッセージを送信](/ja/open/development/the-robot-sends-a-group-message) インターフェースを呼び出すことで、ボットからメッセージを返信させる方法を説明します。「クイック体験」で提供されるサンプル demo を実行してみてください。これにより、社内ボットの使い方を直感的に体験できます。

## 前提条件

1. [社内ボットの設定](/ja/open/dingstart/configure-the-robot-application) フロー（メッセージ受信モードは Stream モードを選択）を完了してください。
2. ボットの作成完了後、[ボットをグループに追加](/ja/open/dingstart/add-robot-to-group) してください。
3. OpenAPI インターフェースの [呼び出し権限申請](/ja/open/development/add-api-permission) を完了してください。`社内ボットによるメッセージ送信権限`の申請が必要です。
4. 開発環境の準備：

   | **開発環境** | **説明**                                    |
   | -------- | ----------------------------------------- |
   | Java     | - JDK 1.8 以上がインストール済み - Maven 3 がインストール済み |
   | Python   | - Python 3                                |

## クイック体験

1. サンプル demo をダウンロードできます：

   | **サンプル** | **説明**                                                                                                                                                                                     |
   | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
   | Java     | [stream-robot-group-message-quick-start-java.zip](https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250519/vbadtr/stream-robot-group-message-quick-start-java.zip)     |
   | Python   | [stream-robot-group-message-quick-start-python.zip](https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250519/xifjds/stream-robot-group-message-quick-start-python.zip) |
2. サンプル demo を起動：

   | **タイプ** | **説明**                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
   | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
   | Java    | 1. application.properties 設定ファイルのパラメータを修正します： - app.appKey：アプリの Client ID。詳細は [Client ID](/ja/open/dingstart/basic-concepts-beta) を参照してください。 - app.appSecret：アプリの Client Secret。詳細は [Client Secret](/ja/open/dingstart/basic-concepts-beta) を参照してください。 - robot.code：ボットのコード。詳細は [ボット ID](/ja/open/development/development-robot-overview) を参照してください。 2. Application.java ファイルを起動します。 3. グループ内でボットに @ メンションしてメッセージを送信します。例：ボットに「こんにちは」と送信します。 これで、ボットが送信したメッセージのコンテンツを確認できます。​ |
   | Python  | 1. 依存関係を導入します：`pip install alibabacloud-dingtalk dingtalk-stream`。 2. 現在のファイルディレクトリで起動コマンドを入力します：`python3 send_robot_group_message.py --client_id="your app client id" --client_secret="your app client secret" --robot_code="your robot code"`。 client\_id、client\_secret、robot\_code を必ず置換してください。パラメータの取得方法は Java の説明を参照してください。 3. グループ内でボットに @ メンションしてメッセージを送信します。例：ボットに「こんにちは」と送信します。                                                                                     |

## 操作手順

> 以下は Java のサンプルです。Python のサンプルは上記の体験用 demo をダウンロードしてください。

1. プロジェクトの `pom.xml` ファイルに依存関係を追加します。

   ```xml lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
    <dependencies>
           <dependency>
               <groupId>com.dingtalk.open</groupId>
               <artifactId>dingtalk-stream</artifactId>
               <version>1.1.0</version>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
               <version>2.7.4</version>
           </dependency>

           <dependency>
               <groupId>com.aliyun</groupId>
               <artifactId>dingtalk</artifactId>
               <version>2.0.76</version>
           </dependency>

           <dependency>
               <groupId>org.projectlombok</groupId>
               <artifactId>lombok</artifactId>
               <version>1.18.26</version>
               <optional>true</optional>
           </dependency>

           <dependency>
               <groupId>com.alibaba</groupId>
               <artifactId>fastjson</artifactId>
               <version>1.2.68</version>
           </dependency>
       </dependencies>
   ```
2. main メソッドを作成し、起動します。

   ```java lines theme={"theme":{"light":"github-light","dark":"github-dark"}}
   import com.alibaba.fastjson.JSONObject;

   import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
   import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
   import com.aliyun.dingtalkrobot_1_0.Client;
   import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders;
   import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest;
   import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendResponse;
   import com.aliyun.tea.TeaException;
   import com.aliyun.teaopenapi.models.Config;
   import com.dingtalk.open.app.api.OpenDingTalkClient;
   import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
   import com.dingtalk.open.app.api.callback.OpenDingTalkCallbackListener;
   import com.dingtalk.open.app.api.security.AuthClientCredential;
   import lombok.extern.slf4j.Slf4j;

   import java.util.Objects;

   @Slf4j
   public class sendGroupMessage {

       public static final String CLIENT_ID = "< your client id>";

       public static final String CLIENT_SECRET = "<your client secret>";

       public static void main(String[] args) throws Exception {
           OpenDingTalkClient client = OpenDingTalkStreamClientBuilder
                   .custom()
                   .credential(new AuthClientCredential(CLIENT_ID, CLIENT_SECRET))
                   .registerCallbackListener("/v1.0/im/bot/messages/get", new RobotMsgCallbackConsumer())
                   .build();
           client.start();
       }

       public static class RobotMsgCallbackConsumer implements OpenDingTalkCallbackListener<JSONObject, JSONObject> {

           /*
            * @param request
            * @return
            */
           @Override
           public JSONObject execute(JSONObject request) {
               String userId = request.get("senderStaffId").toString();
               String content = request.getJSONObject("text").getString("content");
               String openConversationId = request.get("conversationId").toString();
               String robotCode = request.get("robotCode").toString();
               log.info("receive bot message from user={}, msg={},openConversationId={},robotCode={} ", userId, content, openConversationId, robotCode);

               OrgGroupSendHeaders orgGroupSendHeaders = new OrgGroupSendHeaders();
               orgGroupSendHeaders.setXAcsDingtalkAccessToken(getToken());

               OrgGroupSendRequest orgGroupSendRequest = new OrgGroupSendRequest();
               orgGroupSendRequest.setMsgKey("sampleText");
               orgGroupSendRequest.setRobotCode(robotCode);

               orgGroupSendRequest.setOpenConversationId(openConversationId);

               JSONObject msgParam = new JSONObject();
               msgParam.put("content", "java-getting-start say : " + "hello");
               orgGroupSendRequest.setMsgParam(msgParam.toJSONString());
               try {
                   Config config = new Config();
                   config.protocol = "https";
                   config.regionId = "central";
                   com.aliyun.dingtalkrobot_1_0.Client client = new Client(config);
                   OrgGroupSendResponse orgGroupSendResponse = client.orgGroupSendWithOptions(orgGroupSendRequest,
                           orgGroupSendHeaders, new com.aliyun.teautil.models.RuntimeOptions());
                   if (Objects.isNull(orgGroupSendResponse) || Objects.isNull(orgGroupSendResponse.getBody())) {
                       log.error("RobotGroupMessagesService_send orgGroupSendWithOptions return error, response={}",
                               orgGroupSendResponse);
                       return null;
                   }
                   return new JSONObject();
               } catch (TeaException e) {
                   log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw TeaException, errCode={}, " +
                           "errorMessage={}", e.getCode(), e.getMessage(), e);
                   throw e;
               } catch (Exception e) {
                   log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw Exception", e);
                   try {
                       throw e;
                   } catch (Exception ex) {
                       throw new RuntimeException(ex);
                   }
               }
           }

           public static String getToken() {
               GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest();
               getAccessTokenRequest.setAppKey(CLIENT_ID);
               getAccessTokenRequest.setAppSecret(CLIENT_SECRET);
               Config config = new Config();
               config.protocol = "https";
               config.regionId = "central";
               try {
                   com.aliyun.dingtalkoauth2_1_0.Client client = new com.aliyun.dingtalkoauth2_1_0.Client(config);
                   GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
                   return accessToken.getBody().getAccessToken();
               } catch (Exception e) {
                   throw new RuntimeException(e);
               }
           }
       }
   }
   ```
3. グループ内でボットに @ メンションしてメッセージを送信できます。

   これで、ボットが送信したメッセージのコンテンツを確認できます。​

## 関連ドキュメント

* [ボットによるメッセージ受信](/ja/open/dingstart/robot-receive-message)
* サーバーサイド Stream モード
* [ボットからグループチャットへメッセージを送信](/ja/open/development/the-robot-sends-a-group-message)
* 社内ボットが送信するメッセージのタイプ
