telegramInvoke static method
Future<Map>
telegramInvoke(
{ - required Map parametersRequest,
- required String tokenBot,
- String urlApi = "https://api.telegram.org/",
- bool isThrowOnError = true,
- Client? httpClient,
- Duration? durationTaskTimeOut,
- Duration? durationFetchTimeOut,
})
Implementation
static Future<Map> telegramInvoke({
required Map parametersRequest,
required String tokenBot,
String urlApi = "https://api.telegram.org/",
bool isThrowOnError = true,
Client? httpClient,
Duration? durationTaskTimeOut,
Duration? durationFetchTimeOut,
}) async {
final Client http_client = () {
if (httpClient != null) {
return httpClient;
}
return Client();
}();
final Map parameters = parametersRequest;
if (parameters["reply_parameters"] is Map == false) {
if (parameters["reply_to_message_id"] is num) {
parameters["reply_parameters"] = {
"message_id": parameters["reply_to_message_id"],
};
}
}
final String url = Uri.parse((urlApi)).replace(pathSegments: [
"bot${tokenBot}",
parameters["@type"],
]).toString();
final DateTime dateTime_expire =
DateTime.now().add(durationTaskTimeOut ?? Duration(minutes: 1));
final Map result = await Future<Map>(() async {
while (true) {
await Future.delayed(Duration(milliseconds: 1));
if (dateTime_expire.isExpired()) {
return {
"ok": false,
"code": 300,
"message": "network_connection_bad",
};
}
try {
final Map<String, String> header = <String, String>{
'Accept': 'application/json',
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
};
final Response response = await http_client
.post(Uri.parse(url),
headers: header, body: json.encode(parameters))
.timeout(durationFetchTimeOut ?? Duration(seconds: 1),
onTimeout: () {
return Response(
json.encode({
"ok": false,
"code": 300,
"message": "network_connection_bad",
}),
300,
);
});
if (response.statusCode == 200) {
if (parameters["@type"].toString().toLowerCase() == "getfile") {
final Map getFile = json.decode(response.body);
final String url = "${urlApi}file/bot${tokenBot.toString()}";
getFile["result"]["file_url"] =
"${url}/${getFile["result"]["file_path"]}";
return getFile;
} else {
return json.decode(response.body);
}
} else {
final Map result = json.decode(response.body);
return result;
}
} catch (e) {
if (e is ClientException) {
continue;
}
if (RegExp(r"^(send)", caseSensitive: false)
.hasMatch(parameters["@type"])) {
if (e is Map) {
if (RegExp("Unsupported start tag", caseSensitive: false)
.hasMatch(e["description"])) {
parameters.remove("parse_mode");
return await telegramInvoke(
parametersRequest: parameters,
isThrowOnError: isThrowOnError,
tokenBot: tokenBot,
urlApi: urlApi,
);
}
}
}
if (e is Map) {
return e;
} else {
return {
"ok": false,
"code": 300,
"message": "network_connection_bad",
};
}
}
}
});
if (isThrowOnError) {
if (result["ok"] == false || result["code"] == 300) {
throw result;
}
}
return result;
}