Difference between revisions of "HTTP API/Examples/Requesting bot balance"
From SmartBots Developers Docs
Line 53: | Line 53: | ||
], "&"); | ], "&"); | ||
− | httpReq = llHTTPRequest(" | + | httpReq = llHTTPRequest("https://api.mysmartbots.com/api/bot.html", [HTTP_METHOD,"POST"], params); |
} | } | ||
Latest revision as of 09:22, 23 December 2016
This scripts requests the bot's avatar balance from LSL. It also demonstrates how to parse HTTP API replies using get_post_value function.
string sbApiKey = "...";
string sbBotName = "OneSmartBot Resident";
string sbBotAccessCode = "...";
key httpReq = NULL_KEY;
// Get posted data's value.
// This function is from http://wiki.secondlife.com/wiki/Http_response
string get_post_value(string content, string returns) {
list params = llParseString2List(content,["&"],[]);
integer index = ~llGetListLength(params);
list keys;
list values;
// Loop through the parameters.
while (++index) {
list parsedParams = llParseString2List(llList2String(params, index), ["="], []);
keys += llUnescapeURL(llList2String(parsedParams, 0));
values += llUnescapeURL(llList2String(parsedParams, 1));
}
//Return our parameter or "FAIL".
integer found = llListFindList(keys, [returns]);
if(~found) {
return llList2String(values, found);
} else {
return "";
}
}
default {
// When the owner touches the object.
touch_start(integer total_number) {
if(llDetectedKey(0) != llGetOwner()) {
llInstantMessage(llDetectedKey(0), "Only my owner can use me!");
return;
}
//Set up the parameters we'll send to SmartBots.
string params = llDumpList2String([
"action=" + "get_balance",
"apikey=" + llEscapeURL(sbApiKey),
"botname=" + llEscapeURL(sbBotName),
"secret=" + llEscapeURL(sbBotAccessCode)
], "&");
httpReq = llHTTPRequest("https://api.mysmartbots.com/api/bot.html", [HTTP_METHOD,"POST"], params);
}
//Get the SmartBots reply from the server.
http_response(key request_id, integer status, list metadata, string body) {
if(request_id! = httpReq) { return; }
// Parse the SmartBots reply.
string action = get_post_value(body, "action");
string result = get_post_value(body, "result");
string resulttext = get_post_value(body, "resulttext");
string balance = get_post_value(body, "balance");
if(result=="FAIL") {
// If the command failed.
llOwnerSay("Command '"+action+"' failed: "+resulttext);
} else {
// If the command was a success.
llOwnerSay("Your bot's balance is L$" + balance);
}
}
}