How to get telegram bot getUpdates json from vbscript and read it - http

i wanted to create my bot in VBScript (i know its like troll and bad idea probably, i can do it in lua, python, C#, PHP, ...., but i decided to try and make it from vbscript)
the hard part is that i'm trying to Retrieve information from Telegram getUpdates
i've made this code for example and it kind of works, i'll explain what works and what doesn't
Dim fso, outFile, TeleTest
Set fso = CreateObject("Scripting.FileSystemObject")
Set outFile = fso.CreateTextFile("output.txt", True)
set TeleTest = fso.CreateTextFile("TeleTest.txt", True)
Dim url, req, json
Set req = CreateObject("MSXML2.XMLHTTP")
url = "https://api.telegram.org/bot"[TOKEN]"/getUpdates"
req.open "GET", url, False
req.send
If req.Status = 200 Then
TeleTest.Write req.responseText
End If
' Load the JSON array into a JsonArray:
set jsonArray = CreateObject("Chilkat_9_5_0.JsonArray")
success = jsonArray.Load("TeleTest.txt")
If (success <> 1) Then
outFile.WriteLine(jsonArray.LastErrorText)
WScript.Quit
End If
' Get some information from each record in the array.
numRecords = jsonArray.Size
i = 0
Do While i < numRecords
outFile.WriteLine("------ Record " & i & " -------")
' jsonRecord is a Chilkat_9_5_0.JsonObject
Set jsonRecord = jsonArray.ObjectAt(i)
outFile.WriteLine(" ok: " & jsonRecord.StringOf("ok"))
outFile.WriteLine(" result: " & jsonRecord.SizeOfArray("result"))
' Examine information for this record
u = 0
Do While u < nummessage
nummessage = jsonRecord.SizeOfArray("result[u].message")
Loop
outFile.WriteLine("Number of message: " & nummessage)
j = 0
Do While j < nummessage
jsonRecord.J = j
outFile.WriteLine(" message text: " & jsonRecord.StringOf("result[j].message[j].text"))
j = j + 1
Loop
i = i + 1
Loop
outFile.Close
so the first part that should get updates and save it ino TeleTest.txt works fine, it gets updates, it saves the json in to the .txt file (or anything, i can also save it into string in the vbs, or .json file)
the problem is that the second part where i'm using Chilkat gives error
Blockquote
ChilkatLog: Load:
ChilkatVersion: 9.5.0.78
Unable to get array at index 0. --Load
--ChilkatLog
any help or any idea would be appereciated, also if Chilkat is not good for doing this, maybe tell me why and give me something else?! (Chilkat was the only dll i found to work with vbscript and does json reading, stuff)

i got it to working, i found out that from this example
Chilkat needs the Json file to like this
[ { json } ]
but the Telegram json is like this
{ json }
so, the fix would be easy to just change line 15 from TeleTest.Write req.responseText to this code below
TeleTest.Write "[" + req.responseText + "]"
my code now works fine , if anyone else found something wrong or any answer to my question it would be appreciated
i hope someone else who needs this find this

Related

Getting internal server error when trying to list top 100 newest files in folder

I have a folder with 114,000 files in it (not under my control) and I want to list only the latest 100 of them that have been modified. So I hobbled together an ASP script from different sources, but it's giving me an internal server error when I run it.
<%
Function SortFiles(files)
ReDim sorted(files.Count - 1)
Dim file, i, j
i = 0
For Each file in files
Set sorted(i) = file
i = i + 1
Next
For i = 0 to files.Count - 2
For j = i + 1 to files.Count - 1
If sorted(i).DateLastModified < sorted(j).DateLastModified Then
Dim tmp
Set tmp = sorted(i)
Set sorted(i) = sorted(j)
Set sorted(j) = tmp
End If
Next
Next
SortFiles = sorted
End Function
dim fileserver,files,file,i
set fileserver=Server.CreateObject("Scripting.FileSystemObject")
set files=fileserver.GetFolder(Server.MapPath(".")).Files
i = 0
For Each file in SortFiles(files)
Response.write(x.Name & "\t" & x.Size & "\n")
i = i + 1
If i > 100 Then
Exit For
End If
Next
set fo=nothing
set files=nothing
%>
The files I want listed just need to have their name and size separated by new lines. I am new to ASP so I'm not sure how to debug this.
Move the code from aspx to aspx.cs (code behind) and you can debug it by adding breakpoint, and F10/F11 to step over/step into. I don't know if you can debug inline code, looks like you can by some SO answer.
At first glance, SortFiles does not return a list of file, so it can not be used in a For Each loop.
For Each file in SortFiles(files) //exception
And what is this for?
SortFiles = sorted
I don't know VB, but you can debug yourself.

Classic ASP Array not returning values, error 500

I'm working on executing the same code several times to produce a table. My first thoughts went out to using an array to do this.
Here is what i have got so far:
Dim iRow
iRow = 0
'alternate color for rows
Do While Not rsGlobalWeb.EOF
If iRow Mod 2 = 0 Then
response.write "<tr bgcolor=""#FFFFFF"">"
Else
response.write "<tr bgcolor=""#EEEEEE"">"
End If
'some other code
SqlBackup = "SELECT * FROM CMDBbackup WHERE Naam_Cattools = '" & rsGlobalWeb("Device_name") & "'"
Set rsBackup = Server.CreateObject("ADODB.Recordset")
rsBackup.Open SqlBackup, dbGlobalWeb, 3
'declaration of array
Dim fieldname(5),i
fieldname(0) = "Device_name"
fieldname(1) = "Image"
fieldname(2) = "Backup"
fieldname(3) = "Uptime"
fieldname(4) = "Processor"
fieldname(5) = "Nvram"
For i = 0 to 5
If rsGlobalWeb(fieldname(i)) <> "" Then
response.write("<td>" & rsGlobalWeb(fieldname(i)) & "</td>")
Else
If Not rsBackup.EOF Then
If Not IsNull(rsBackup(fieldname(i))) And (rsBackup(fieldname(i)) <> "") Then
response.write("<td>" & rsBackup(fieldname(i)) & " (backup)</td>")
End if
Else
response.write("<td>No data found</td>")
End if
End if
Next
response.write("</tr>")
iRow = iRow + 1
rsGlobalWeb.MoveNext
Loop
The issue i have now is that the following error occurs even tho i have friendly messages turned off:
"500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed."
The logfile shows the following:
"DaEngineSDB.asp |58|800a000d|Type_mismatch 80 -" Where the 58 is the line with the Dim Fieldname.
Without the array it does show the remainder of the code (i have 1 other field which gets added). If i remove the array and fill the fieldname(i) with a normal string value it also works fine.
I was trying out stuff that google says but after attempting several things i am still running up to a wall.
Any ideas what it could be?
Thanks in advance,
Erik
First you should turn on error displaying in your iis, or read the error log for its description, google it if not sure how.
Without error description, it's way too difficult to check what is wrong.
Problem solved!
After banging my head against the wall for a day i found out that i stupidly declared the array inside the DO WHILE loop. Moved the declaration out of it and problem solved.

Need to pull out a link from a website using VBscript

I have got as far as getting the HTML response into a variable and now I am stuck:
Link: http://www.avg.com/gb-en/31.prd-avb
In an ideal world I would be able to get the first and second link for x86 and x64. All I need to get is the actual location of the exe into a variable: IE:
download.avg.com/filedir/inst/avg_ipw_x86_all_2011_1204a3402.exe
Can anyone point me in the right direction?
Thanks in advance for any help provided
This works, but it's far from a stellar technique, because I'm parsing HTML with regex.
However, I'm not aware of an easier method to accomplish this in Classic ASP, and this is a simple task.
<%
url = "http://www.avg.com/gb-en/31.prd-avb"
Dim http
Set http = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
http.SetTimeouts 20000, 20000, 20000, 10000
http.Open "GET", url, False
http.Send
If http.WaitForResponse(5) Then
responseText = http.ResponseText
End If
Set http = Nothing
'Response.Write(Server.HtmlEncode(responseText))
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
re.Pattern = "<a href=""(http://download\.avg\.com/filedir/inst/.*?)"""
Set matches = re.Execute(responseText)
If matches.Count > 0 Then
For Each match In matches
Response.Write(match.SubMatches(0) & "<br />")
Next
Else
Response.Write("No matches.")
End If
%>
Gives output like this:
http://download.avg.com/filedir/inst/avg_ipw_x86_all_2011_1204a3402.exe
http://download.avg.com/filedir/inst/avg_ipw_x64_all_2011_1204a3402.exe
http://download.avg.com/filedir/inst/avg_msw_x86_all_2011_1204a3402.exe
http://download.avg.com/filedir/inst/avg_msw_x64_all_2011_1204a3402.exe
http://download.avg.com/filedir/inst/avg_rad_x86_all_2011_1154.exe
http://download.avg.com/filedir/inst/avg_rad_x64_all_2011_1154.exe

Simple encrypt/decrypt functions in Classic ASP

Are there any simple encrypt/decrypt functions in Classic ASP?
The data that needs to be encrypted and decrypted is not super sensitive. So simple functions would do.
4guysfromrolla.com: RC4 Encryption Using ASP & VBScript
See the attachments at the end of the page.
The page layout looks a bit broken to me, but all the info is there. I made it readable it by deleting the code block from the DOM via bowser development tools.
Try this:
' Encrypt and decrypt functions for classic ASP (by TFI)
'********* set a random string with random length ***********
cryptkey = "GNQ?4i0-*\CldnU+[vrF1j1PcWeJfVv4QGBurFK6}*l[H1S:oY\v#U?i,oD]f/n8oFk6NesH--^PJeCLdp+(t8SVe:ewY(wR9p-CzG<,Q/(U*.pXDiz/KvnXP`BXnkgfeycb)1A4XKAa-2G}74Z8CqZ*A0P8E[S`6RfLwW+Pc}13U}_y0bfscJ<vkA[JC;0mEEuY4Q,([U*XRR}lYTE7A(O8KiF8>W/m1D*YoAlkBK#`3A)trZsO5xv#5#MRRFkt\"
'**************************** ENCRYPT FUNCTION ******************************
'*** Note: bytes 255 and 0 are converted into the same character, in order to
'*** avoid a char 0 which would terminate the string
function encrypt(inputstr)
Dim i,x
outputstr=""
cc=0
for i=1 to len(inputstr)
x=asc(mid(inputstr,i,1))
x=x-48
if x<0 then x=x+255
x=x+asc(mid(cryptkey,cc+1,1))
if x>255 then x=x-255
outputstr=outputstr&chr(x)
cc=(cc+1) mod len(cryptkey)
next
encrypt=server.urlencode(replace(outputstr,"%","%25"))
end function
'**************************** DECRYPT FUNCTION ******************************
function decrypt(byval inputstr)
Dim i,x
inputstr=urldecode(inputstr)
outputstr=""
cc=0
for i=1 to len(inputstr)
x=asc(mid(inputstr,i,1))
x=x-asc(mid(cryptkey,cc+1,1))
if x<0 then x=x+255
x=x+48
if x>255 then x=x-255
outputstr=outputstr&chr(x)
cc=(cc+1) mod len(cryptkey)
next
decrypt=outputstr
end function
'****************************************************************************
Function URLDecode(sConvert)
Dim aSplit
Dim sOutput
Dim I
If IsNull(sConvert) Then
URLDecode = ""
Exit Function
End If
'sOutput = REPLACE(sConvert, "+", " ") ' convert all pluses to spaces
sOutput=sConvert
aSplit = Split(sOutput, "%") ' next convert %hexdigits to the character
If IsArray(aSplit) Then
sOutput = aSplit(0)
For I = 0 to UBound(aSplit) - 1
sOutput = sOutput & Chr("&H" & Left(aSplit(i + 1), 2)) & Right(aSplit(i + 1), Len(aSplit(i + 1)) - 2)
Next
End If
URLDecode = sOutput
End Function
I know is a bit late for BrokenLink, but for the record and others like me who were looking for the same.
I found this https://www.example-code.com/vbscript/crypt_aes_encrypt_file.asp.
It needs to install a chilkat ActiveX component on WindowsServer. But this inconvenient becomes convenient when looking resources and processing time.
Its very easy to use, and the given example is pretty clear. To make it your own, just change the "keyHex" variable value and voilá.

ASP Classic - Type mismatch: 'CInt' - Easy question

Having an issue with type conversion in ASP classic.
heres my code:
Set trainingCost = Server.CreateObject("ADODB.Recordset")
strSQL3 = "SELECT cost1 FROM tblMain WHERE (Booked = 'Booked') AND (Paid IS NULL) AND (PaidDate BETWEEN '01/04/" & startyear & "' AND '31/03/" & endyear & "')"
trainingCost.Open strSQL3, Connection
trainingCost.movefirst
totalTrainCost = 0
do while not trainingCost.eof
trainCost = trainingCost("cost1")
If NOT isNull(trainCost) then
trainCostStr = CStr(trainCost)
trainCostStr = Replace(trainCostStr, "£", "")
trainCostStr = Replace(trainCostStr, ",", "")
totalTrainCost = totalTrainCost + CInt(trainCostStr)
end if
trainingCost.movenext
loop
trainingCost.close
when I run this I get the following error:
Microsoft VBScript runtime (0x800A000D)
Type mismatch: 'CInt'
/systems/RFT/v1.2/Extract.asp, line 43
which is "totalTrainCost = totalTrainCost + CInt(trainCostStr)"
Im guessing that the problem is to do with the String value being uncastable to Int in which case is there any way to catch this error? I havent worked with asp classic much so any help would be usefull
cheers
-EDIT-
the type of column cost1 is String as it may contain a number or a sequence of chars eg £10.00 or TBC
You have a couple of choices. You can be proactive by checking ahead of time whether the value is numeric using the IsNumeric function:
If IsNumeric(trainCostStr) Then
totalTrainCost = totalTrainCost + CInt(trainCostStr)
Else
' Do something appropriate
End If
...or you can be reactive by using error catching; in Classic ASP probably easiest to define a function and use On Error Resume Next:
Function ConvertToInt(val)
On Error Resume Next
ConvertToInt = CInt(val)
If Err.Number <> 0 Then
ConvertToInt = Empty
Err.Clear
End If
End Function
Or return 0 or Null or whatever suits you, then use it in your trainCost code.
Note that CInt expects an integer and will stop at the first non-digit, so "123.45" comes back as 123. Look at the other conversions, CDouble, CCur, etc.
Rather than casting to a string, why not use CCur (Cast as Currency) so that your commas and any currency symbols (I think) are effectively ignored while doing arithmetic operations?
Potentially solving the wrong problem, depends on the type of Cost1 within the database but the code is looping through the records to generate a total.
strSQL3 = "SELECT sum(cost1) FROM tblMain WHERE (Booked = 'Booked') AND (Paid IS NULL) AND (PaidDate BETWEEN '01/04/" & startyear & "' AND '31/03/" & endyear & "')"
trainingCost.Open strSQL3, Connection
etc and just read off the value as a total.
I don't see why the RS is being looped to generate a sum when the database can do that work for you. All the conversion work it has generated just looks artifical.
Heh heh. Classic ASP. You have my pity :) Anyway,
On error resume next
And then on the next line, check that it worked.
Though maybe you want CDouble. Is that a function? I can't remember.

Resources