MyChat Scripts: HTTPSendGetMessageAsync function, send a network GET request in an asynchronous mode
Send HTTP GET request asynchronously. The function immediately returns the task key without blocking the script execution.
Asynchronous HTTP functions don't return the server's response immediately. They run the request in a separate thread and return a string key, which can be used to retrieve the ready result from the server's internal memory cache via MemCacheExists and MemCacheGet later.
Syntax
function HTTPSendGetMessageAsync(const AURL, AHeaders: string; const ATimeOut: integer): string;
Parameters and return values
|
Parametr |
Type |
Value |
|
AURL |
string |
address, where you send a request. Supports both http and https. You can specify any port for connection, for example, http://yourserver.com:8080/myservice/ |
|
AHeaders |
string |
special headers (if necessary). Separated by CRLF if required more than one. Usually, if the service does not require this — an empty string; |
|
ATimeOut |
integer |
time in milliseconds, maximum time to wait for response from the remote server. |
Function result
String key that allows getting result via MemCacheGet(). If the request has not yet completed, the corresponding cache entry may not exist.
Example
var
sKey, sResult, sValue: string;
i: integer;
begin
sKey := HTTPSendGetMessageAsync(
'https://httpbin.org/get?from=mychat',
'Accept: application/json',
3000);
mLogScript(sKey, 'Key');
// wait for the result to appear in the cache, maximum 3 seconds.
// example code. Similar loops with ScriptSleep in production is a bad idea.
for i := 1 to 30 do begin
if MemCacheExists(sKey) then begin
sResult := MemCacheGet(sKey);
mLogScript(sResult, 'Server answer');
break;
end;
ScriptSleep(100);
end;
end.
Script work result
[19:17:22] (Log "PostMessageAsync"): [Key] httpget_async_{8a9c07cb-38a9-4133-b198-54b812819abd}21032026191722055
[19:17:22] (Log "PostMessageAsync"): [Server answer] { "args": { "from": "mychat" }, "headers": { "Accept": "application/json", "Host": "httpbin.org", "User-Agent": "Mozilla/4.0 (compatible; Synapse)", "X-Amzn-Trace-Id": "Root=1-69bed2a1-5b6688ad4bc1600741b8d3af" }, "origin": "95.67.34.140", "url": "https://httpbin.org/get?from=mychat" }
[19:17:22] (Run "PostMessageAsync"): Script operation time: 574 ms
[19:17:22] (Run "PostMessageAsync"): Script done successfully.