Problem using webwrite to send image in telegram API

12 ビュー (過去 30 日間)
Abolfazl Nejatian
Abolfazl Nejatian 2021 年 5 月 7 日
コメント済み: Life is Wonderful 2021 年 6 月 29 日
Hey everyone,
i need to send some messages with image throuout the REST API of telegram.
here is my code for text sending, and it works correctly.
token = '1769425585:AAGPOrIaLTKYr9THQDkehlwrjdxfiJxHNuw';
requestType = 'sendMessage?';
id = 54573663;
url = ['https://api.telegram.org/bot' token '/' requestType 'chat_id=' num2str(id) '&text=' msg];
options = weboptions('ContentType','json','UserAgent','Abolfazl','RequestMethod','post','ArrayFormat','json');
resp
onse = webwrite(url,options);
but the problem is with regard to sending photos
here is the python code for photo sending.
the code uses a dictionary for the photo section but I don't know how to convert it to the Matlab code.
here is the python code,
import requests
import json
bot_token = 'BOT TOKEN'
chat_id = "CHAT ID"
file = r"C:\Users\name\OneDrive\Desktop\Capture.PNG"
files = {
'photo': open(file, 'rb')
}
message = ('https://api.telegram.org/bot'+ bot_token + '/sendPhoto?chat_id='
+ chat_id)
send = requests.post(message, files = files)
I will appreciate your help.
kind regards,
Abolfazl Nejatian

採用された回答

Kojiro Saito
Kojiro Saito 2021 年 5 月 11 日
There are MATLAB codes for Telegram Bot APIs.
In this URL, sendPhoto function in telegram_bot.m is very helpful for your case.
I've changed the code so that it fits you as below.
bot_token = "XXX";
chat_id = "XXX";
url = "https://api.telegram.org/bot" + bot_token + "/sendPhoto?chat_id=" + chat_id;
photoname = 'XXX.png';
% Create file provider
fileProvider = matlab.net.http.io.FileProvider(photoname);
% Set media type to multipart/form-data
mediaType = matlab.net.http.MediaType('multipart/form-data');
% Set HTTP header
header = matlab.net.http.field.AcceptField(mediaType);
% Crete multipart form provider
formProvider = matlab.net.http.io.MultipartFormProvider('photo', fileProvider);
% Create HTTP request message
request = matlab.net.http.RequestMessage(matlab.net.http.RequestMethod.POST, header, formProvider);
% Set HTTP options and enable SavePayload for debugging
options = matlab.net.http.HTTPOptions('SavePayload', true);
% Send HTTP request
resp = request.send(url, options);
% Get result
if resp.StatusCode == 200
disp('Uploading is successful!')
response = resp.Body.Data;
end
At the beggining, I tried webwrite, but using matlab.net.http classes works well in this case.
  7 件のコメント
Life is Wonderful
Life is Wonderful 2021 年 6 月 29 日
@Kojiro Saito, I hope you had a look to above link.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCall Web Services from MATLAB Using HTTP についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by