[Gambas-user] Request for advice

T Lee Davidson t.lee.davidson at gmail.com
Mon Jul 12 20:22:14 CEST 2021

On 7/12/21 1:25 PM, John Dovey wrote:
> I am working on wrapping theTelegram bot API in Gambas (as recommended
> here before) but I'm not sure of a few things in the best approach.
> Some of the questions I have include:
> - does this make sense as a way to do this?

It looks sensible to me. There are a couple things I might do a bit differently, but what you have obviously works (though I 
don't see where 'botMe' was declared).

One thing I would do is, since you've defined hClient globally, set it's unchanging parameters once and reuse it. Second, I'd 
define one universal function to retrieve the response and return a collection. See the code further down below.

> - What is the best way to store the returned collection?

As a collection? Do you see something wrong with that? For whatever state data needs to be maintained, you can declare as many 
collections as you need to store response data from the only 50-some respective methods. And, the values are very easy to access.

Public Token as string = "xxx"
Public apiURL As String = "https://api.telegram.org/bot" & Token & "/"
Public hClient As HttpClient
'Public cmdResponse As String
'Public cmdJSON As Collection
Public MyBot, ImaginaryData as Collection

Public Sub Main()

     hClient = New HttpClient As "hClient"
     hClient.Async = False
     hClient.Timeout = 60

     ' Get my bot's ID
     MyBot = getResponse("getMe")
     If MyBot Then ' May need to use "If Not IsNull(MyBot) Then" here. My recall is sometimes faulty.
         Print MyBot["id"]
         Print "ERROR"
     End If

     ' Get data from imaginary method
     ImaginaryData = getResponse("virtData")
     If ImaginaryData Then Print ImaginaryData["ether"]


Public Sub getResponse(sMethod) as Variant

     Dim sBuffer as String
     Dim respJSON as Collection

     hClient.URL = apiURL & sMethod

     Print "Begin"
     If hClient.Status < 0 Then
         Print "ERROR"
         ' Success - read the data
         If Lof(hClient) Then sBuffer = Read #hClient, Lof(hClient)
         Print sBuffer
         'cmdResponse = sBuffer
     End If
     Try respJSON = JSON.Decode(sBuffer)
     If Error Then Return Null
     Return respJSON
     Print "End"

One other thing: if there is the possibility for the API to return a JSON object with null values, you will want to use 
JSONCollection as opposed to the Gambas native Collection.


More information about the User mailing list