B4J Question jtelegrambot error when receiving an image

Yoldi

Member
I'm testing the telegram library jtelegrambot ver. 0.23
with his example and when receiving an image he gives me the following error.
main._jtb_onmessagereceived (java line: 558)
java.lang.NullPointerException
at ID.Telegram_Bot.main._jtb_onmessagereceived (main.java:558)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at anywheresoftware.b4a.BA.raiseEvent2 (BA.java:91)
at anywheresoftware.b4a.BA $ 3.run (BA.java:247)
at com.sun.javafx.application.PlatformImpl.lambda $ null $ 172 (PlatformImpl.java:295)
at java.security.AccessController.doPrivileged (Native Method)
at com.sun.javafx.application.PlatformImpl.lambda $ runLater $ 173 (PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher $ Future.run (InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop (Native Method)
at com.sun.glass.ui.win.WinApplication.lambda $ null $ 147 (WinApplication.java:177)
at java.lang.Thread.run (Thread.java:748)

Can you tell me how it can be corrected.

Thank you
 

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Anyway. I can´t reproduce the error but i saw missing Objects when trying to reproduce it. Audio, Document for ex.

I´ve updated the Library to 0.24.

Example of use you can find here. Basically it works like this when you receive a Audio, Video, Photo or Document:
1. You get the info about the Document in the Messageobject.
2. If it is <> null then you need to get the Object out of the Message. For example The Document

B4X:
    Log($"MessageDocument: ${message.Document}"$)
    If message.Document <> Null Then
        Dim fdoc As Document = message.Document ' get the Document out of the Message
        Log($"Document.FileId = ${fdoc.FileId}"$)
        Log($"Document.FileName = ${fdoc.FileName}"$)
        Log($"Document.FileSize = ${fdoc.FileSize}"$)
        Log($"Document.MimeType = ${fdoc.MimeType}"$)
        Dim tfile As TelegramFile = jtb.getFile(fdoc.FileId)  ' Get the Telegramfile out of the Document
        Log($"File.Size = ${tfile.FileSize}"$)
        Log($"File.Path = ${tfile.FilePath}"$)
        Dim furl As String = $"https://api.telegram.org/file/bot${bottoken}/${tfile.FilePath}"$ ' Build the downloadurl for this File/document
        Log(furl)
        File.MakeDir(File.DirApp, "documents") ' Store documents in th documents folder to match it

        Dim j As HttpJob
        j.Initialize("",Me)
        j.Download(furl) ' Download file using okhttputils2
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Dim out As OutputStream = File.OpenOutput(File.DirApp, tfile.FilePath, False)
            File.Copy2(j.GetInputStream, out)
            out.Close '<------ very important
        End If
        j.Release
    End If


Complete code for any kind of file. Document, Audio, Video and Photo

B4X:
Sub JTB_onMessageReceived(api As Object, id As Int, msg As Object)
    bld.Initialize(api)
    Log($"JTB_onMessageReceived( ${id}, ${msg}"$)
    Dim message As Message = msg
    Log($"MessageFrom: ${message.From}"$)

    Log($"MessageAudio: ${message.Audio}"$)
    If message.Audio <> Null Then
        Dim faudio As Audio = message.Audio
        Log($"Audio.FileId = ${faudio.FileId}"$)
        Log($"Audio.Duration = ${faudio.Duration}"$)
        Log($"Audio.Performer = ${faudio.Performer}"$)
        Log($"Audio.Title = ${faudio.Title}"$)
        Log($"Audio.FileSize = ${faudio.FileSize}"$)
        Log($"Audio.MimeType = ${faudio.MimeType}"$)
        Dim tfile As TelegramFile = jtb.getFile(faudio.FileId)
        Log($"File.Size = ${tfile.FileSize}"$)
        Log($"File.Path = ${tfile.FilePath}"$)
        Dim furl As String = $"https://api.telegram.org/file/bot${bottoken}/${tfile.FilePath}"$
        Log(furl)
        File.MakeDir(File.DirApp, "music")

        Dim j As HttpJob
        j.Initialize("",Me)
        j.Download(furl)
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Dim out As OutputStream = File.OpenOutput(File.DirApp, tfile.FilePath, False)
            File.Copy2(j.GetInputStream, out)
            out.Close '<------ very important
        End If
        j.Release
    End If

    Log($"MessageDocument: ${message.Document}"$)
    If message.Document <> Null Then
        Dim fdoc As Document = message.Document
        Log($"Document.FileId = ${fdoc.FileId}"$)
        Log($"Document.FileName = ${fdoc.FileName}"$)
        Log($"Document.FileSize = ${fdoc.FileSize}"$)
        Log($"Document.MimeType = ${fdoc.MimeType}"$)
        Dim tfile As TelegramFile = jtb.getFile(fdoc.FileId)
        Log($"File.Size = ${tfile.FileSize}"$)
        Log($"File.Path = ${tfile.FilePath}"$)
        Dim furl As String = $"https://api.telegram.org/file/bot${bottoken}/${tfile.FilePath}"$
        Log(furl)
        File.MakeDir(File.DirApp, "documents")

        Dim j As HttpJob
        j.Initialize("",Me)
        j.Download(furl)
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Dim out As OutputStream = File.OpenOutput(File.DirApp, tfile.FilePath, False)
            File.Copy2(j.GetInputStream, out)
            out.Close '<------ very important
        End If
        j.Release
    End If
    Log($"MessageDocument: ${message.Document}"$)
    If message.Video <> Null Then
        Dim fvid As Video = message.Video
        Log($"Video.FileId = ${fvid.FileId}"$)
        Log($"Video.Duration = ${fvid.Duration}"$)
        Log($"Video.Width = ${fvid.Width}"$)
        Log($"Video.Height = ${fvid.Height}"$)
        Log($"Video.MimeType = ${fvid.MimeType}"$)
        Log($"Video.FileSize = ${fvid.FileSize}"$)
        Dim tfile As TelegramFile = jtb.getFile(fvid.FileId)
        Log($"File.Size = ${tfile.FileSize}"$)
        Log($"File.Path = ${tfile.FilePath}"$)
        Dim furl As String = $"https://api.telegram.org/file/bot${bottoken}/${tfile.FilePath}"$
        Log(furl)
        File.MakeDir(File.DirApp, "videos")

        Dim j As HttpJob
        j.Initialize("",Me)
        j.Download(furl)
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Dim out As OutputStream = File.OpenOutput(File.DirApp, tfile.FilePath, False)
            File.Copy2(j.GetInputStream, out)
            out.Close '<------ very important
        End If
        j.Release
    End If

    Dim from As User = message.From
    Log($"FromFirstName: ${from.FirstName}"$)
    Log($"FromLastName: ${from.LastName}"$)
    Log($"FromUserName: ${from.Username}"$)
    Log($"FromID: ${from.Id}"$)
    If message.Photo <> Null Then
        Log($"Photosizes: ${message.Photo}"$)
        Dim phsi As List = message.Photo
        If phsi.IsInitialized And phsi.Size > 0 Then
            For i= 0 To phsi.Size-1
                Dim photo As PhotoSize = phsi.Get(i)
                Log(photo)
                Log(photo.FileId)
                Dim tfile As TelegramFile = jtb.getFile(photo.FileId)
                Log($"File.Size = ${tfile.FileSize}"$)
                Log($"File.Path = ${tfile.FilePath}"$)
                Dim furl As String = $"https://api.telegram.org/file/bot${bottoken}/${tfile.FilePath}"$
                Log(furl)
                File.MakeDir(File.DirApp, "photos")

                Dim j As HttpJob
                j.Initialize("",Me)
                j.Download(furl)
                Wait For (j) JobDone(j As HttpJob)
                If j.Success Then
                    Dim out As OutputStream = File.OpenOutput(File.DirApp, tfile.FilePath, False)
                    File.Copy2(j.GetInputStream, out)
                    out.Close '<------ very important
                End If
                j.Release
    
            Next
        End If
    End If
    

    Log($"MessageChat: ${message.Chat}"$)
    Dim chat As Chat = message.Chat
    Log($"ChatFirstName: ${chat.FirstName}"$)
    Log($"ChatFirstName: ${chat.LastName}"$)
    Log($"ChatUserName: ${chat.Username}"$)
    
    If chat.Title <> Null Then
        Log($"ChatTitle: ${chat.Title}"$)
    End If
    Log($"ChatID: ${chat.Id}"$)

    If message.Caption <> Null Then
        Log($"MessageCaption: ${message.Caption}"$)
    End If
    If message.Contact <> Null Then
        Log($"MessageContact: ${message.Contact}"$)
        Dim cont As Contact = message.Contact
        Log($"ContactFirstname: ${cont.FirstName}"$)
        Log($"ContactLastName: ${cont.LastName}"$)
        Log($"ContactPhoneNumber: ${cont.PhoneNumber}"$)
        Log($"ContactUserId: ${cont.UserId}"$)
    End If
    Log($"MessageDate: ${message.Date}"$)
    Dim entitiesList As List = message.Entities
    If entitiesList.IsInitialized And entitiesList.Size > 0 Then
        For i=0 To entitiesList.Size-1
            Dim ent As MessageEntity = entitiesList.Get(i)
            'Log($"Entity.Length = ${ent.Length}"$)
            'Log($"Entity.Offset = ${ent.Offset}"$)
            If ent.Url <> Null Then
                Log($"Entity.URL = ${ent.Url}"$)
            End If
            If ent.User <> Null Then
                Log($"Entity.User = ${ent.User}"$)
            End If
            Log($"Entity.Type = ${ent.Type}"$)
        Next
    End If
    If message.Voice <> Null Then
        Dim voic As Voice = message.Voice
        Log($"Voice.Duration ${voic.Duration}"$)
        Log($"Voice.FileId ${voic.FileId}"$)
        Log($"Voice.Filesize ${voic.FileSize}"$)
        Log($"Voice.MimeType ${voic.MimeType}"$)
    End If
    If message.Video <> Null Then
        Dim vid As Video = message.Video
        Log($"Video.FileId ${vid.FileId}"$)
        Log($"Video.Duration ${vid.Duration}"$)
        Log($"Video Size ${vid.Width}x${vid.Height}"$)
        Log($"Video.MimeType ${vid.MimeType}"$)
        Log($"Video.Filesize ${vid.FileSize}"$)
    End If


    Log($"MessageText: ${message.Text}"$)
    If message.Text <> Null And message.Text <> "null" Then

        If message.Text = "/buttons" Then
            Dim ibld As InlineKeyboardButtonBuilder
            Dim mark As InlineKeyboardMarkup
            
            mark.initialize(ibld.Initialize.newRow.newButton("1").withCallbackData("BTN1").newButton("2").withCallbackData("BTN2").newButton("3").withCallbackData("BTN3").newRow.newButton("Google").withUrl("https://www.google.com").newRow.build)
            Dim buttons As Message = jtb.sendMessage(jtb.byId(from.Id),"Click the Button!","MARKDOWN",False,False,message.MessageId,mark)
            glmap.Put(buttons.MessageId,buttons)
        else If message.Text = "/location" Then
            jtb.sendChatAction(jtb.byId(from.Id),jtb.ChatActionFIND_LOCATION)
            jtb.sendLocation(jtb.byId(from.Id),50.8337006,6.441118,False,message.MessageId,Null)
        else If message.Text = "/url" Then
            jtb.sendMessage(jtb.byId(from.Id),"[jTelegramBot Thread](https://www.b4x.com/android/forum/threads/beta-jtelegrambot-create-your-own-telegram-bot.103821/)","MARKDOWN",False,False,message.MessageId,Null)
        else If message.Text = "/plainurl" Then
            bld.sendMessage(chat.Id,"Link without Preview [jTelegramBot Thread](https://www.b4x.com/android/forum/threads/beta-jtelegrambot-create-your-own-telegram-bot.103821/)",message.MessageId,False,True,Null,jtb.parsemodeMARKDOWN)
        else If message.Text = "/text" Then
            jtb.sendMessage(jtb.byId(from.Id),$"Testtext <b>Bold</b>, <i>Italic</i>
        new row..."$,"HTML",True,False,message.MessageId,Null)
        else If message.Text = "/document" Then
            jtb.sendChatAction(jtb.byId(from.Id),jtb.ChatActionUPLOAD_DOCUMENT)
            jtb.sendDocument(jtb.byId(from.Id),jtb.MediaByFile(File.DirApp,"jtbex.zip"),"DocumentCaption",False,message.MessageId,Null)
        else If message.Text = "/photo" Then
            jtb.sendChatAction(jtb.byId(from.Id),jtb.ChatActionUPLOAD_PHOTO)
            jtb.sendPhoto(jtb.byId(from.Id),jtb.MediaByFile(File.DirApp,"donmanfred.png"),"DocumentCaption",False,message.MessageId,replbld.forceReply)
        else If message.Text = "/audio" Then
            jtb.sendChatAction(jtb.byId(from.Id),jtb.ChatActionUPLOAD_VIDEO)
            'jtb.sendAudio(jtb.byId(from.Id),jtb.MediaByFile(File.DirApp,"EyesOfTheWorld.mp3"),223,"Fleedwood Mac","Eyes of the World",False,message.MessageId,replbld.forceReply)
        else If message.Text = "/sticker" Then
            jtb.sendSticker(jtb.byId(from.Id),jtb.MediaByFile(File.DirApp,"cuppy.webp"),False,message.MessageId,Null)
        else if message.Text = "CloseKB" Then
            Dim hidekb As ReplyKeyboardHide
            hidekb.initialize
            Dim buttons As Message = jtb.sendMessage(jtb.byId(from.Id),"Thank you for using the Keyboard","MARKDOWN",False,False,message.MessageId,hidekb.hideKeyboard)
            '
        else If message.Text = "/replykeyboard" Then
            Log("ReplyKeyboard requested")
            Dim kmark As ReplyKeyboardMarkup
            kmark.initkeyboard(2,3) ' 2 Rows, 3 Columns each
            kmark.SetButton(0,0,"BTN0-0") ' Set Button text for Button at Row 0 and Column 0
            kmark.SetButton(0,1,"BTN0-1")
            kmark.SetButton(0,2,"BTN0-2")
            kmark.SetButton(1,0,"BTN1-0")
            kmark.SetButton(1,1,"BTN1-1")
            kmark.SetButton(1,2,"CloseKB")
            kmark.initialize(kmark.GetKeyboard,True,False,True)
            Dim buttons As Message = jtb.sendMessage(jtb.byId(from.Id),"Yo man","MARKDOWN",False,False,message.MessageId,kmark)
            'glmap.Put(buttons.MessageId,buttons)
        else If message.Text = "/anim" Then
            jtb.sendAnimation(jtb.byId(from.Id),jtb.MediaByFile(File.DirApp,"anim.gif"),5,400,179,jtb.MediaByFile(File.DirApp,"giphy90.jpg"),False,message.MessageId,Null,"Caption...",jtb.parsemodeMARKDOWN)
        else If message.Text = "/start" Then
            jtb.sendMessage(jtb.byId(from.Id),$" Hello ${chat.Username}
    `Command   | Result
    ----------|-------------------------
    /location | Returns a Locationobject
    /document | Returns a Document
    /photo    | Returns a Photo
    /url      | Returns a URL with Preview
    /plainurl | Returns a URL without Preview
    /buttons  | Shows some buttons To Click on
    `
    Thank you For choosing Me :-)"$,"MARKDOWN",False,False,message.MessageId,Null)
        Else
        End If   
    End If
End Sub
 
Upvote 0
Top