Using the following function for flutter, you can send an image as a document via telegram bot.
Required Files/ Variables:
- File file: The image you want to send
- botToken
- chatId: Id of the chat where you want to upload the file
Add dependencies:
http: ^0.13.5
This function will return the file Id which can be used further to get the file path
Future<String> send(File file) async {
Uri url = Uri.parse(
"https://api.telegram.org/bot$botToken/sendDocument?chat_id=$chatId");
http.MultipartRequest request = http.MultipartRequest("POST", url);
request.files.add(await http.MultipartFile.fromPath('document', file.path));
http.Response r = await http.Response.fromStream(await request.send());
// file sent
if (r.statusCode == 200) {
debugPrint("Uploaded!");
} else {
debugPrint("Unable to send the data");
return "";
}
debugPrint(r.body);
Map sentResponse = jsonDecode(r.body);
if (sentResponse["ok"] == true) {
fileId = sentResponse['result']["document"]["file_id"];
} else {
debugPrint("Data is not uploaded. Try again");
return "";
}
return fileId;
}