用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/green-api/whatsapp-api-webhook-server-cpp --skill green-api-c-sdk命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | GREEN API C++ SDK |
| version | 1.0.0 |
| description | Complete guide for AI agents to write correct C++ code using GREEN-API WhatsApp SDK |
| author | GREEN-API Team |
| keywords | ["green-api","whatsapp","sdk","c++","messaging","webhook"] |
The GREEN-API C++ SDK enables programmatic interaction with WhatsApp through a RESTful API. This guide teaches AI agents to write production-ready code.
greenapi namespace@c.us suffix for personal chats, @g.us for group chatsgreenapi::Response object// ❌ WRONG - Will fail
api.sending.sendMessage(nlohmann::json::parse(R"({
"chatId": "71234567890"
})");
// ✅ CORRECT - Personal chat
api.sending.sendMessage(nlohmann::json::parse(R"({
"chatId": "71234567890@c.us"
})");
// ✅ CORRECT - Group chat
api.sending.sendMessage(nlohmann::json::parse(R"({
"chatId": "123456789-987654321@g.us"
})");
getStateInstance() to check: should return "authorized" or "got qr code"qr() to get QR codeAlways check success() method on response:
greenapi::Response resp = api.sending.sendMessage(msg);
if (resp.success()) {
std::cout << "Message sent: " << resp.getResult() << std::endl;
} else {
std::cerr << "Error: " << resp.getError() << std::endl;
}
#include "greenapi.hpp"
using json = nlohmann::json;
int main() {
greenapi::GreenApi api(
"https://api.green-api.com", // apiUrl
"https://media.green-api.com", // mediaUrl
"1101234567", // idInstance (from GREEN-API account)
"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPq" // apiTokenInstance (from GREEN-API account)
);
// Now use api.sending, api.receiving, api.account, etc.
return 0;
}
greenapi::GreenApi api(); // Uses hardcoded defaults - NOT for production
unsigned int count = api.getNumberOfInstances();
std::cout << "Active instances: " << count << std::endl;
api.sending.*)Send messages, files, locations, contacts, polls, and interactive buttons.
Key methods:
sendMessage(message) - Text messagesendFileByUrl(message) - File via URLsendFileByUpload(file, text) - File via form uploaduploadFile(file, header) - Upload file to storagesendLocation(message) - Location messagesendContact(message) - Contact cardsendPoll(message) - Poll/votingsendInteractiveButtons(message) - Interactive button messagesforwardMessages(message) - Forward messageExample:
json msg = json::parse(R"({
"chatId": "71234567890@c.us",
"message": "Hello, World!"
})");
greenapi::Response resp = api.sending.sendMessage(msg);
→ See: references/sending.md
api.receiving.*)Receive incoming notifications via HTTP polling.
Key methods:
receiveNotification(timeout) - Get one notification (polling, 5-60 seconds)deleteNotification(receiptId) - Delete received notificationdownloadFile(message) - Download file by file dataImportant: Use webhook endpoint (not SDK method) for production. HTTP polling is inefficient.
Example (Polling Loop):
while (true) {
greenapi::Response notif = api.receiving.receiveNotification(30); // 30 sec timeout
if (notif.success()) {
nlohmann::json data = notif.getResult();
unsigned int receiptId = data.value("receiptId", 0);
// Process notification...
std::cout << "Got notification: " << data.dump() << std::endl;
// Delete after processing
api.receiving.deleteNotification(receiptId);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
→ See: references/receiving.md
api.account.*)Manage account settings, authorization, and status.
Key methods:
getSettings() - Get account settingssetSettings(settings) - Update settings (webhook URL, notification types)getStateInstance() - Get auth state ("authorized", "not authorized", "got qr code")getStatusInstance() - Get socket connection statusqr() - Get QR code for authorization (base64)getAuthorizationCode(phoneNumber) - Get auth code via SMS alternativelogout() - Logout accountreboot() - Reboot instanceExample:
greenapi::Response settings = api.account.getSettings();
if (settings.success()) {
nlohmann::json data = settings.getResult();
std::cout << "Account: " << data["wid"] << std::endl;
}
→ See: references/account.md
api.groups.*)Manage group chats, participants, and permissions.
Key methods:
createGroup(group) - Create new group (max 1 group per 5 minutes)updateGroupName(group) - Change group namegetGroupData(group) - Get group infoaddGroupParticipant(group) - Add memberremoveGroupParticipant(group) - Remove membersetGroupAdmin(group) - Promote to adminremoveAdmin(group) - Demote from adminupdateGroupSettings(group) - Change permissionsleaveGroup(group) - Bot leaves groupExample:
json grp = json::parse(R"({
"groupName": "My Group",
"chatIds": ["71234567890@c.us", "71987654321@c.us"]
})");
greenapi::Response resp = api.groups.createGroup(grp);
→ See: references/groups.md
api.journals.*)Retrieve message and call history.
Key methods:
getChatHistory(message) - Get messages from chatgetMessage(message) - Get single messagelastIncomingMessages(minutes) - Get incoming messages (default 1440 min = 24h)lastOutgoingMessages(minutes) - Get sent messageslastIncomingCalls(minutes) - Get incoming callslastOutgoingCalls(minutes) - Get outgoing callsExample:
greenapi::Response msgs = api.journals.lastIncomingMessages(60); // Last hour
if (msgs.success()) {
for (auto& msg : msgs.getResult()) {
std::cout << msg.dump() << std::endl;
}
}
→ See: references/journals.md
api.serviceMethods.*)General operations like contacts, typing status, chat management.
Key methods:
checkWhatsapp(phoneNumber) - Check if number has WhatsAppgetContacts() - Get all contactsgetContactInfo(message) - Get contact detailsgetAvatar(message) - Get profile pictureeditMessage(message) - Edit sent messagedeleteMessage(message) - Delete messagegetChats(count) - Get chat listarchiveChat(message) - Archive chatunarchiveChat(message) - Unarchive chatsetDisappearingChat(message) - Set disappearing message timersendTyping(message) - Show "typing" indicatorExample:
greenapi::Response contacts = api.serviceMethods.getContacts();
if (contacts.success()) {
for (auto& contact : contacts.getResult()) {
std::cout << contact["id"] << ": " << contact["name"] << std::endl;
}
}
→ See: references/service.md
api.queues.*)Manage message send queue.
Key methods:
showMessagesQueue() - List pending messagesclearMessagesQueue() - Clear all pending messagesExample:
greenapi::Response queue = api.queues.showMessagesQueue();
std::cout << "Queued messages: " << queue.getResult().size() << std::endl;
→ See: references/queues.md
api.readMark.*)Mark messages as read.
Key methods:
readChat(message) - Mark chat as readExample:
json msg = json::parse(R"({"chatId": "71234567890@c.us"})");
api.readMark.readChat(msg);
→ See: references/readmark.md
api.statuses.*)Send and manage WhatsApp statuses (stories).
Key methods:
sendTextStatus(status) - Post text statussendVoiceStatus(status) - Post voice statussendMediaStatus(status) - Post picture/video statusdeleteStatus(status) - Delete own statusgetIncomingStatuses(minutes) - Get received statusesgetOutgoingStatuses(minutes) - Get posted statusesgetStatusStatistic(idMessage) - Get status views/reactionsExample:
json status = json::parse(R"({"text": "I am online!"})");
api.statuses.sendTextStatus(status);
→ See: references/statuses.md
#include "greenapi.hpp"
#include <iostream>
#include <thread>
#include <chrono>
using json = nlohmann::json;
int main() {
greenapi::GreenApi api(
"https://api.green-api.com",
"https://media.green-api.com",
"YOUR_ID_INSTANCE",
"YOUR_API_TOKEN"
);
// Check if authorized
greenapi::Response state = api.account.getStateInstance();
if (state.success()) {
std::string status = state.getResult()["stateInstance"];
if (status == "authorized") {
// Send message
json msg = json::parse(R"({
"chatId": "71234567890@c.us",
"message": "Hello from C++ SDK!"
})");
greenapi::Response resp = api.sending.sendMessage(msg);
if (resp.success()) {
std::cout << "Message sent with ID: "
<< resp.getResult()["idMessage"] << std::endl;
} else {
std::cerr << "Error: " << resp.getError() << std::endl;
}
} else {
std::cout << << status << std::endl;
greenapi::Response qr = api.account.();
(qr.()) {
std::string qrCode = qr.()[];
std::cout << << std::endl;
}
}
}
;
}
#include "greenapi.hpp"
#include <thread>
#include <chrono>
#include <iostream>
using json = nlohmann::json;
int main() {
greenapi::GreenApi api(
"https://api.green-api.com",
"https://media.green-api.com",
"YOUR_ID_INSTANCE",
"YOUR_API_TOKEN"
);
std::cout << "Starting message polling..." << std::endl;
while (true) {
// Poll with 30 second timeout
greenapi::Response notif = api.receiving.receiveNotification(30);
if (notif.success()) {
json data = notif.getResult();
unsigned int receiptId = data["receiptId"];
// Process based on notification type
if (data.contains("body")) {
std::string type = data["body"].value("typeWebhook", "");
if (type == "incomingMessageReceived") {
std::string sender = data["body"]["senderData"][];
std::string messageText = data[][][][];
std::cout << << sender << << messageText << std::endl;
json reply = json::();
reply[] = sender;
api.sending.(reply);
}
}
api.receiving.(receiptId);
}
std::this_thread::(std::chrono::());
}
;
}
json fileMsg = json::parse(R"({
"chatId": "71234567890@c.us",
"urlFile": "https://example.com/document.pdf",
"fileName": "document.pdf",
"caption": "Please review this document"
})");
greenapi::Response resp = api.sending.sendFileByUrl(fileMsg);
// Step 1: Upload file
json file = json::parse(R"({"file": ""})");
file["file"] = "/path/to/local/image.jpg";
json header = json::parse(R"({"fileName": "image.jpg"})");
greenapi::Response upload = api.sending.uploadFile(file, header);
if (upload.success()) {
std::string fileUrl = upload.getResult()["urlFile"];
// Step 2: Send via URL
json msg = json::parse(R"({
"chatId": "71234567890@c.us",
"urlFile": "",
"fileName": "image.jpg",
"caption": "My photo"
})");
msg["urlFile"] = fileUrl;
api.sending.sendFileByUrl(msg);
}
json group = json::parse(R"({
"groupName": "Project Team",
"chatIds": [
"71234567890@c.us",
"71987654321@c.us",
"71555555555@c.us"
]
})");
greenapi::Response created = api.groups.createGroup(group);
if (created.success()) {
std::string groupId = created.getResult()["chatId"];
std::cout << "Group created: " << groupId << std::endl;
// Promote one member to admin
json admin = json::parse(R"({
"groupId": "",
"participantChatId": "71234567890@c.us"
})");
admin["groupId"] = groupId;
api.groups.setGroupAdmin(admin);
}
All methods return greenapi::Response:
greenapi::Response resp = api.sending.sendMessage(msg);
// Check success
if (resp.success()) {
// Get result data
nlohmann::json result = resp.getResult();
std::cout << "Success: " << result.dump() << std::endl;
} else {
// Get error details
std::string error = resp.getError();
std::cout << "Error: " << error << std::endl;
}
success() - Returns boolgetResult() - Returns nlohmann::jsongetError() - Returns error message stringauto state = api.account.getStateInstance();
if (state.success() &&
state.getResult()["stateInstance"] != "authorized") {
// Handle not authorized
return;
}
// Between messages: 3-5 seconds minimum
std::this_thread::sleep_for(std::chrono::seconds(4));
api.sending.sendMessage(msg1);
std::this_thread::sleep_for(std::chrono::seconds(4));
api.sending.sendMessage(msg2);
Instead of polling in a loop, set webhook in account settings:
json settings = json::parse(R"({
"webhookUrl": "https://your-server.com/webhook",
"webhookUrlToken": "your-secret-token",
"incomingWebhook": "yes",
"outgoingMessageWebhook": "yes",
"outgoingAPIMessageWebhook": "yes",
"incomingCallWebhook": "yes"
})");
api.account.setSettings(settings);
json reply = json::parse(R"({
"chatId": "71234567890@c.us",
"message": "Agreed!",
"quotedMessageId": "FALSE..." // ID of message to quote
})");
api.sending.sendMessage(reply);
bool isValidChatId(const std::string& chatId) {
return (chatId.find("@c.us") != std::string::npos) ||
(chatId.find("@g.us") != std::string::npos);
}
| Error | Cause | Solution |
|---|---|---|
instance not authorized | Account not logged in | Call qr(), scan, wait for auth |
invalid chatId | Wrong format or missing @c.us/@g.us | Add correct suffix: "123@c.us" |
message sending is disabled | Instance settings issue | Enable in dashboard |
invalid file url | File URL unreachable | Verify URL is public and accessible |
request timeout | Slow connection or server overload | Retry with exponential backoff |
rate limit | Too many messages too fast | Add 5+ second delay between sends |
All message parameters use nlohmann::json for maximum flexibility:
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// Method 1: Parse from string
json msg = json::parse(R"({"chatId": "123@c.us", "message": "Hi"})");
// Method 2: Build object
json msg;
msg["chatId"] = "123@c.us";
msg["message"] = "Hi";
// Method 3: Array support
json buttons = json::array();
buttons.push_back({{"type", "url"}, {"buttonText", "Click"}, {"url", "https://..."}});
msg["buttons"] = buttons;
Full method reference: See references/ folder
Official Documentation: https://green-api.com/en/docs/api/
GitHub Repository: https://github.com/green-api/whatsapp-api-client-cpp
Last Updated: 2024-07-20
Status: Production Ready
Tested With: C++11+, nlohmann/json 3.2+