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
| #include <windows.h>
#include <winhttp.h>
#include <iostream>
#pragma comment(lib, "winhttp.lib")
bool PostSlackMessage(const std::wstring& accessToken, const std::string& channel, const std::string& text) {
const wchar_t* host = L"slack.com";
const wchar_t* path = L"/api/chat.postMessage";
HINTERNET hSession = WinHttpOpen(L"SlackPoster/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) return false;
HINTERNET hConnect = WinHttpConnect(hSession, host, INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) return false;
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"POST", path,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE);
// AuthorizationヘッダーとContent-Type
std::wstring headers = L"Content-Type: application/json\r\n";
headers += L"Authorization: Bearer " + accessToken + L"\r\n";
// JSONボディ
std::string body = R"({"channel":")" + channel + R"(","text":")" + text + R"("})";
BOOL result = WinHttpSendRequest(hRequest,
headers.c_str(),
(DWORD)-1,
(LPVOID)body.c_str(),
body.length(),
body.length(),
0);
if (!result || !WinHttpReceiveResponse(hRequest, NULL)) {
std::cerr << "送信エラー\n";
return false;
}
// ステータスコード確認
DWORD statusCode = 0;
DWORD size = sizeof(statusCode);
WinHttpQueryHeaders(hRequest,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&statusCode, &size, WINHTTP_NO_HEADER_INDEX);
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return (statusCode == 200);
}
int main() {
std::wstring token = L"xoxb-あなたのアクセストークン"; // アクセストークン
std::string channel = "チャンネルIDまたは#general"; // 例: "#general" or "C0123456789"
std::string message = "C++からSlackに投稿してみた!";
if (PostSlackMessage(token, channel, message)) {
std::cout << "投稿成功!\n";
} else {
std::cerr << "投稿失敗。\n";
}
return 0;
}
|