1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
1. 发送图片
需要先创建应用,开通图片文件上传的权限。
获取开通应用的appId和appSecret,获取Token
public async Task<string> GetTokenAsync()
{
string appId = @"cli_a7a4cdbd480b";
string appSecret = "qDIqT7EIr98cV8Q3ofKqRSnQqDjA";
using var client = new HttpClient();
var requestBody = new
{
app_id = appId,
app_secret = appSecret
};
var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8,
"application/json");
var response =
await client.PostAsync("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/",
content);
string responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var jsonResponse = JObject.Parse(responseContent);
string tenantAccessToken = jsonResponse["tenant_access_token"].ToString();
return tenantAccessToken;
}
return "";
}
拿到Token之后调用上传图片的方法,拿到图片的image_key
private static async Task<string> UploadImage(string accessToken, string imagePath)
{
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using var formData = new MultipartFormDataContent();
using var fileStream = File.OpenRead(imagePath);
var fileContent = new StreamContent(fileStream);
var mimeType = GetMimeType(imagePath);
fileContent.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
formData.Add(fileContent, "image", Path.GetFileName(imagePath));
formData.Add(new StringContent("message"), "image_type"); // 使用"message"作为默认image_type
var response = await client.PostAsync("https://open.feishu.cn/open-apis/image/v4/put/", formData);
string responseBody = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var jsonResponse = JObject.Parse(responseBody);
var imageKey = jsonResponse["data"]["image_key"]?.ToString();
return imageKey;
}
else
{
}
return null;
}
拿到Image_key之后就可以,通过自定义机器人的Webhook地址发送图片
public async Task<bool> SendImageFeishuAsync(string imagePath)
{
var token = await GetTokenAsync();
var imageKey = await UploadImage(token, imagePath);
// 替换为你自己的飞书机器人Webhook地址
string webhookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/05546c09-f7e7-466c-8660-18aa";
// 将图片转换为Base64编码字符串
var message = new
{
msg_type = "image",
content = new
{
image_key = imageKey
}
};
var json = JsonConvert.SerializeObject(message);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(webhookUrl, data);
var result = await response.Content.ReadAsStringAsync();
return response.IsSuccessStatusCode;
}
|