B4J Question Send file in telegram

red30

Well-Known Member
Licensed User
Longtime User
Through postman, I can send a txt file in telegram.
Here is the code:
PHP:
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.telegram.org/botXXX:YYY/sendDocument?chat_id=ZZZ',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array('document'=> new CURLFILE('/С:/example.txt')),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
Java:
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("document","/C:/example.txt",
    RequestBody.create(MediaType.parse("application/octet-stream"),
    new File("/C:/example.txt")))
  .build();
Request request = new Request.Builder()
  .url("https://api.telegram.org/botXXX:YYY/sendDocument?chat_id=ZZZ")
  .method("POST", body)
  .build();
Response response = client.newCall(request).execute();
But, if I try to send via b4j I get the error ResponseError. Reason: Unsupported Media Type, Response:
B4X:
    Dim jjj As HttpJob
    jjj.Initialize("", Me)
 
    Dim fd As MultipartFileData
    fd.Initialize
    fd.KeyName = "document"
    fd.Dir = Dir
    fd.FileName = Name
    jjj.PostMultipart("https://api.telegram.org/botXXX:YYY/sendDocument?chat_id=ZZZ", CreateMap("document": Name), Array(fd))
    Wait For (jjj) JobDone(jjj As HttpJob)
    If jjj.Success Then
        Log(jjj.GetString)
    End If
    jjj.Release
How can I send a telegram file using OkHttp?
I send the file like this:
B4X:
jjj.PostString("https://api.telegram.org/botXXX:YYY/sendDocument?chat_id=ZZZ","document: "&Dir&Name)
I get the error: ResponseError. Reason: Bad Request, Response: {"ok":false,"error_code":400,"description":"Bad Request: there is no document in the request"}
 

DonManfred

Expert
Licensed User
Longtime User
 
Upvote 0

red30

Well-Known Member
Licensed User
Longtime User
If you want to do it with OkHttpUtils2 then use PostMultipart and try to set fd.ContentType = "application/octet-stream"
I am getting the same error: ResponseError. Reason: Unsupported Media Type, Response:
B4X:
    Dim jjj As HttpJob
    jjj.Initialize("", Me)
    Dim fd As MultipartFileData
    fd.Initialize
    fd.KeyName = "document"
    fd.Dir = Dir
    fd.FileName = Name
    fd.ContentType = "application/octet-stream"
    jjj.PostMultipart("https://api.telegram.org/botXXX:YYY/sendDocument?chat_id=ZZZ", CreateMap("document": Name), Array(fd))
    Wait For (jjj) JobDone(jjj As HttpJob)
    If jjj.Success Then
        Log(jjj.GetString)
    End If
    jjj.Release
 
Upvote 0

red30

Well-Known Member
Licensed User
Longtime User
What is the file name? Not clear to me how it tries to find the media type.
File name:
B4X:
Name=(DateTime.Date(DateTime.Now)&"_"&DateTime.Time(DateTime.Now))&"_file.txt"
DateTime.DateFormat = "dd.MM.yyyy"
DateTime.TimeFormat= "HH-mm-ss"
This is how I choose the directory to write the file:
B4X:
DirectoryChooser.Show(MainForm)
Try
    lbldir.Text=DirectoryChooser.InitialDirectory
Catch
    Log(LastException)
End Try
Dir=lbldir.Text
 
Last edited:
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
What will be the difference?
It depends on what you want to do.
If you want to select a DIRECTORY you should use DirectoryChooser. The Result is never a File. Only E:\ for example
If you want to select the File 17.12.2020 11-27-14_file_0.txt you should use FileChooser to get a result of, for ex, E:\Some\path\17.12.2020 11-27-14_file_0.txt
 
Upvote 0

red30

Well-Known Member
Licensed User
Longtime User
It depends on what you want to do.
If you want to select a DIRECTORY you should use DirectoryChooser. The Result is never a File. Only E:\ for example
If you want to select the File 17.12.2020 11-27-14_file_0.txt you should use FileChooser to get a result of, for ex, E:\Some\path\17.12.2020 11-27-14_file_0.txt
I needed to choose a folder where I would save the files.
 
Upvote 0

red30

Well-Known Member
Licensed User
Longtime User
Ok, how is it then related to Telegram? I thought the code you posted is relevant for your problem here
My program saves the signal to a file. I am using DIRECTORYchooser so that the user can select the folder where he wants to save the file. And after this file is saved on the local computer, I also want to send it in telegram.
lbldir.Text is a label where I simply display the path selected through DIRECTORYchooser by the user.
Next, I want to transfer the file in telegrams:
B4X:
Name=(DateTime.Date(DateTime.Now)&"_"&DateTime.Time(DateTime.Now))&"_file.txt"
Dir=lbldir.Text
File.WriteList (lbldir.Text,Name,data)
Dim jjj As HttpJob
jjj.Initialize("", Me)
Dim fd As MultipartFileData
fd.Initialize
fd.KeyName = "document"
fd.Dir = Dir
fd.FileName = Name
fd.ContentType = "application/octet-stream"
jjj.PostMultipart("https://api.telegram.org/botXXX:YYY/sendDocument?chat_id=ZZZ", CreateMap("document": Name), Array(fd))
Wait For (jjj) JobDone(jjj As HttpJob)
If jjj.Success Then
    Log(jjj.GetString)
End If
jjj.Release
 
Upvote 0

jinyistudio

Well-Known Member
Licensed User
Longtime User
Hi,
Have you used this method to transfer png file ? following code, I always get Job.Success=false o_O

B4X:
private Sub ExeTelegramImg(token As String,chatid As String,msg As String)
    Dim imgName As String="img.png"
    Dim url As String = $"https://api.telegram.org/bot${token}/sendPhoto"$
    '
    Dim fd As MultipartFileData
    fd.Initialize
    fd.KeyName="photo"
    fd.Dir = $"${File.DirApp}"$
    fd.FileName = imgName
    If imgName.Contains(".png") Then
        fd.ContentType = "image/png"
    Else If imgName.Contains(".jpeg") Or imgName.Contains(".jpg") Then
        fd.ContentType = "image/jpeg"
    End If
    
    '
    Dim data As Map
    data.Initialize   
    data.Put("chat_id",chatid)   
    data.Put("caption","dajia")
    '
    Dim job1 As HttpJob
    job1.Initialize($"img,${1}"$, Me)
    job1.PostMultipart(url, data, Array(fd))
    job1.GetRequest.SetHeader("Content-Type","multipart/form-data")
End Sub
 
Upvote 0

red30

Well-Known Member
Licensed User
Longtime User
jinyistudio, I have not been able to send the file in telegrams. All I can poison is messages ...
B4X:
        Dim jjj As HttpJob
        jjj.Initialize("", Me)
        jjj.Download("https://api.telegram.org/botXXX:YYY/sendMessage?chat_id=ZZZ&text="&msg)
        Wait For (jjj) JobDone(jjj As HttpJob)
        If jjj.Success Then
            Log(jjj.GetString)
        End If
        jjj.Release
 
Upvote 0

jinyistudio

Well-Known Member
Licensed User
Longtime User
:eek: Me too, just can send text !
B4X:
Dim url As String = $"https://api.telegram.org/bot${getActive}/sendMessage?chat_id=${chatid}&text=${msg}"$
    ' %0a = newline
    Dim job1 As HttpJob
    job1.Initialize($"txt,${chatid}"$, Me)
    job1.PostString(url,"")
 
Upvote 0
Top