java代码实现企业微信机器人艾特群内成员
时间: 2024-01-06 12:05:22 浏览: 209
可以使用企业微信的API来实现机器人艾特群内成员的功能。以下是一个简单的Java代码示例:
```java
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
public class ChatRobot {
private static final String CORP_ID = "your_corp_id";
private static final String AGENT_ID = "your_agent_id";
private static final String SECRET = "your_secret";
private static final String BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin";
public static void main(String[] args) throws IOException {
// 获取access_token
String accessToken = getAccessToken(CORP_ID, SECRET);
// 发送消息
String groupId = "group_id"; // 要艾特的群组ID
String content = "@all 请注意!"; // 艾特全体成员的消息内容
sendGroupMessage(accessToken, AGENT_ID, groupId, content);
}
/**
* 获取access_token
*/
private static String getAccessToken(String corpId, String secret) throws IOException {
String url = BASE_URL + "/gettoken?corpid=" + corpId + "&corpsecret=" + secret;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
JSONObject responseBody = new JSONObject(response.body().string());
return responseBody.getString("access_token");
}
/**
* 发送群消息,艾特全体成员
*/
private static void sendGroupMessage(String accessToken, String agentId, String groupId, String content) throws IOException {
String url = BASE_URL + "/message/send?access_token=" + accessToken;
OkHttpClient client = new OkHttpClient();
JSONObject requestBody = new JSONObject();
requestBody.put("agentid", agentId);
requestBody.put("msgtype", "text");
JSONObject textContent = new JSONObject();
textContent.put("content", content);
requestBody.put("text", textContent);
JSONObject mentionContent = new JSONObject();
JSONArray mentionList = new JSONArray();
mentionList.put("@all");
mentionContent.put("user_list", mentionList);
requestBody.put("mention", mentionContent);
JSONObject chatIdContent = new JSONObject();
chatIdContent.put("chatid", groupId);
requestBody.put("chatid", chatIdContent);
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody.toString());
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
JSONObject responseBody = new JSONObject(response.body().string());
int errcode = responseBody.getInt("errcode");
if (errcode != 0) {
throw new IOException("Send group message failed, errcode: " + errcode);
}
}
}
```
需要注意的是,发送消息需要使用企业微信的API密钥,所以需要先在企业微信后台中创建一个应用,并获取相应的CORP_ID、AGENT_ID和SECRET。此外,还需要获取access_token,用于接口调用的身份验证。具体实现可以参考上面的代码示例。
阅读全文