I want to send Pushbullet requests from VBA within an Excel macro. In particular, I want to read the latest SMS that I have received and work with the text. In the API description, there is guidance for how to make API requests with CURL, and how to SEND an SMS, but nothing about getting the content of an SMS, and how this can be done with any other tool than CURL.
How can it be done with Selenium VBA?
So far I have found a post that shows an Outlook macro to push notifications to android devices using PushBullet (https://gist.github.com/jdpilgrim/0248938949b64f8f54ad).
While this gives a clue about how Pushbullet API requests can be made with VBA, it does not help GETTING notifications FROM the device. I have these notifications popping up on my PC but have no idea how to access them with VBA.
I guess the mentioned VBA code could be modified in some way to achieve this, but without knowing the API requirements to get the body of a message, there is no useful way to try.
This is the code, my ideas what might be necessary to change are in the comments:
Title = Item.Location & " at " & Format(Item.Start, "Short Time") & " " & Format(Item.Start, "Short Date")
Body = Item.Subject '"Body", "Title" would not make sense in a "get message" request
TargetURL = "https://api.pushbullet.com/v2/pushes" 'maybe "sms" instead of "pushes"?
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Option(4) = 13056 '
HTTPReq.Open "POST", TargetURL, False 'maybe "GET" instead of "POST"?
HTTPReq.SetCredentials "user", "password", 0
HTTPReq.setRequestHeader "Authorization", "Bearer YOUR_ACCESS_TOKEN"
HTTPReq.setRequestHeader "Content-Type", "application/json"
Message = "{""type"": ""note"", ""title"": " & _
vbDoubleQuote & Title & vbDoubleQuote & ", ""body"": " & _
vbDoubleQuote & Body & vbDoubleQuote & "}"
HTTPReq.Send (Message)
' this would get the API response
Response = HTTPReq.responseText
Even if I get something like this to work, how does one get all the latest messages, so they can be scanned in VBA?
I hope someone from Pushbullet reads this and can complete the API documentation. I have not found a way of how to send them the question directly.
Related
I'd like to use excel to ask ChatGPT questions and get them back in a other cell.
I have an API which is given in cell "A1".
The question should be taken out of "A3" - the answer should be in "A6":
Sub SendQuestionToGPT3()
'Declare variables
Dim request As Object
Dim response As String
Dim API As String
API = Worksheets("API").Range("A1").Value
'Set the question in a variable
Dim question As String
question = Range("A3").Value
'Create an HTTP request object
Set request = CreateObject("MSXML2.XMLHTTP")
'Set the API endpoint and make the request
request.Open "POST", "https://api.openai.com/v1/engines/davinci/jobs", False
request.setRequestHeader "Content-Type", "application/json"
request.setRequestHeader "Authorization", "Bearer " & API
request.send "{""prompt"":""" & question & """,""max_tokens"":1000}"
'Get the response and parse it into a string
response = request.responseText
response = Replace(response, ",""choices"":[]", "")
response = Replace(response, """text"":""", "")
response = Replace(response, """}", "")
'Display the response in a cell
Range("A6").Value = response
'Clean up the object
Set request = Nothing
End Sub
But i get this error back:
{
"error": {
"message": "Unknown endpoint for this model.",
"type": "invalid_request_error",
"param": null,
"code": null
} }
Whats wrong with this code?
Thanks!
A few things that will help.
Don't use the Engines endpoints because it's deprecated.
GET https://api.openai.com/v1/engines/davinci/
Also the Engines endpoint does not respond to a prompt. What it does is
Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability.
Instead use the Completion endpoint.
POST https://api.openai.com/v1/completions
In order to use the API you'll have to add model to your request. Something like this.
{
"model": "text-davinci-003",
"prompt": "How are you?",
"max_tokens": 256
}
Hope that helps.
Ok, works as mike says. My problem was/is now ".. exceeded your current quota, please check your plan and billing details". So i have to buy a "plan".
Thanks for your help.
excel novice here; good with formulas for basic office work but no experience with macros.
I have a list of approx 1100 items in an inventory with prices that fluctuate almost daily. I am trying to apply a macro to fetch the prices from a website (face-to-face games) and apply a 10% reduction when the document is opened. I have read a few how-to articles but the explanations quickly went over my head.
I agree with PEH, If the websites have API, its way easier to get data from them. Here's my extremely lacking function that I use for very simple API calls:
Public Function API( _
ByVal URL As String, _
ByVal Action As String, _
Optional Body As String = "") As String
'Action is GET, POST, PUT or DELETE
Dim http As Object
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.Open Action, URL, False
If Action <> "GET" Then http.SetRequestHeader "Content-Type", "application/json"
If Body <> "" Then
http.Send Body
Else
http.Send
End If
If http.Status = 200 And Action <> "GET" Then
API = "Successfully Sent!"
Else
If http.Status <> 200 And http.responsetext = "" Then
API = http.statustext
Else
API = http.responsetext
End If
End If
End Function
This is just a very basic function to plug in a URL and send a block of text or ask for that URL to send you its text. What you would do is find out the URL scheme for the website you're trying to get data from and send a series of these API calls with Action="GET" at those URLs. Then you just have to parse the text they send back to you.
I need to login a https website via httprequest.
I am trying to use the code from this post VBA WinHTTP to download file from password proteced https website
but i only get that answer: "User not found" - but I know the user and password works fine when I login manually.
My main doubt is where the parameters in the string strAuthenticate came from?
And also why I can not see any http header with the "authorization" word in it or with my username/password in it when i use a http sniffer program.
The website is a form-base authentication type. Is there a way (or should I) inform in my code any reference to the HTML textboxes objects for username and password?(And in this case how could I do it?)
Sub SaveFileFromURL()
Dim WHTTP As WinHttp.WinHttpRequest
Set WHTTP = New WinHttpRequest
mainUrl = "https://www.somesite.com.br/Login.php"
myuser = "userA"
mypass = "passuserA"
strAuthenticate = "start-url=%2F&user=" & myuser & "&password=" & mypass & "&switch=Log+In"
WHTTP.Open "POST", mainUrl, False
WHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WHTTP.SetRequestHeader "Authorization", "Basic " & EncodeBase64(StrConv( myuser & ":" & mypass, vbFromUnicode))
WHTTP.Send
End Sub
Thanks very much for all the help. Turns out the key for find the answer was to use the right tools.
As #chillin recommended using a traffic analyser was essential. I was trying to get the HTTP headers with "Live HTTP Headers" chrome extension, but that only gives my information about tha manual authentication process and even then INCOMPLETE information.
So I downloaded "WireShark" and try to sniff the HTTP traffic, but I couldn't since it was encrypted. Then I did some research and found this way of workaround the encryption:
https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/
After this step-by-step guide and apliccate an http packets filter (just write http in the wireshark filter textbox) I was able to sniff the HTTP traffic (the one I generate when I log in manually to the website and the one generated via excel(vba) HTTPREQUEST.
After this everything got easier and I end up with the code below:
Sub HTTPRESQUEST()
'https://stackoverflow.com/questions/22051960/vba-winhttp-to-download-file-from-password-proteced-https-website/
'https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/
'https://wiki.wireshark.org/TLS?action=show&redirect=SSL
'https://wiki.wireshark.org/TLS#Using_the_.28Pre.29-Master-Secret
Dim WHTTP As WinHttp.WinHttpRequest
Set WHTTP = New WinHttpRequest
'Logon page:
mainUrl = "https://www.somewebsite/Logar.php"
myuser = "myuser"
mypass = "mypassword"
strAuthenticate = "username=" & myuser & "&bypass=" & mypass
WHTTP.Open "POST", mainUrl, False
WHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WHTTP.Send strAuthenticate
End Sub
That was enough to do the website log in. No need to encode the username and password.
PS: In the strAuthenticate the "username" and the "bypass" are the HTML objects ids for the username textbox and the password textbox.
I hope this answear can help other people. Thanks again for all the help!
i am trying to get past the simple log template in with DocuSign. Can anyone kindly tell me what is missing in the VBA code. Is there quotes or anything I need to make this work. I added some quotes around my email address. I have a sandbox account and my developer key, but i get a 401 error whether i send execute the "GET" or not. i did take this code from another tread in stackoverflow but i dont know what was in the excel cells to make this code work.
Public Sub APICallTest()
Dim httpRequest As MSXML2.XMLHTTP60
Dim httpResult As MSXML2.DOMDocument60
' defined request and result variables
Set httpRequest = New XMLHTTP60
Set httpResult = New DOMDocument60
'open login information url https://demo.docusign.net/restapi/v2
httpRequest.Open "GET", "https://demo.docusign.net/restapi/v2/login_information.XML", False
httpRequest.setRequestHeader "X-DocuSign-Authentication: <DocuSignCredentials><Username>MyUserName</Username><Password>" + Chr(34) + "my#myemail.com" + Chr(34)</Password><IntegratorKey>myintegratorkey</IntegratorKey></DocuSignCredentials>Accept: application/xml Content-Type: application/xml", "text"
' send login information request
httpRequest.send
Debug.Print httpRequest.Status, "A"
Debug.Print httpRequest.statusText, "B"
Debug.Print httpRequest.responseText, "C"
Exit Sub
The error message is telling you what the problem is- your Integrator Key is either not present in the request or is invalid (i.e. incorrect). I see your VB code that shows you apparently including the key in the header, however since you haven't posted the raw request you're sending out my guess is that your code is not working properly and the key or the header is not being set properly.
Try doing this:
Login to your demo account, go into your preference, and enable the Request Logging feature. (more on how to do that below)
Run your code.
Go back into your account preferences and retrieve the log that would have been created.
Inspect the log and make sure your Integrator Key and X-DocuSign-Authentication header are present and correct.
For a more complete guide on how to enable request logging in your account see here:
https://support.docusign.com/guides/ndse-user-guide-api-request-logging
Or here if you're using the Classic DocuSIgn UI:
https://support.docusign.com/articles/API-Request-Logging
I suspect that the issue is caused because you are trying to set more than one header in the httpRequest.setRequestHeader statement.
I recommend splitting them up to seperate statements
httpRequest.setRequestHeader("X-DocuSign-Authentication","<DocuSignCredentials><Username>MyUserName</Username><Password>" + Chr(34) + "my#myemail.com" + Chr(34)+"</Password><IntegratorKey>myintegratorkey</IntegratorKey></DocuSignCredentials>")
httpRequest.setRequestHeader("Accept","application/xml");
httpRequest.setRequestHeader("Content-Type","application/xml");
https://msdn.microsoft.com/en-us/library/ms766589(v=vs.85).aspx
Hope this proves helpful.
It works now!! this is what it ended up looking in VBA. How does someone know to put "application/xml" on the end of the Header definition?
Public Sub APICallTest()
Dim httpRequest As MSXML2.XMLHTTP60
Dim httpResult As MSXML2.DOMDocument60
'defined request and result variables
Set httpRequest = New XMLHTTP60
Set httpResult = New DOMDocument60
'open login information url https://demo.docusign.net/restapi/v2
httpRequest.Open "GET", "https://demo.docusign.net/restapi/v2/login_information"
httpRequest.setRequestHeader "X-DocuSign-Authentication", "<DocuSignCredentials><Username>my#email.com</Username><Password>mypassword</Password><IntegratorKey>mykey</IntegratorKey></DocuSignCredentials>"
httpRequest.setRequestHeader "Accept", "application/xml"
httpRequest.setRequestHeader "Content-Type", "application/xml"
httpRequest.send
Debug.Print httpRequest.Status, "A"
Debug.Print httpRequest.statusText, "B"
Debug.Print httpRequest.responseText, "C"
Set httpRequest = Nothing
Set httpResult = Nothing
Exit Sub
I'm building a VB macro that shortens URLs in bulk (we're talking thousands). My macro works just fine, until I encountered a long URL with "%3d", which translates into the equals symbol (=).
Here is and example of the long URL: http://domain.com/se/?st=YmUQaIg9PCoCs3vex5XHE1NnqfurVpWsXMXix0QkyO4%3d&p=A43S8C
My macro sends the entirety of the URL to Bit.ly, but Bit.ly's response text shows that it shortened this: http://domain.com/se/?st=YmUQaIg9PCoCs3vex5XHE1NnqfurVpWsXMXix0QkyO4=
And in fact, when I go to the shortened link, I'm not directed to the full URL.
This is the portion of my code that prompts Bit.ly and gets the response:
ApiRequest = "https://api-ssl.bitly.com/v3/shorten?access_token=" & Token & "&longUrl=" & LongURL
With HttpRequest
.Open "GET", ApiRequest, False
.Send
End With
Response = HttpRequest.ResponseText
HttpRequest.WaitForResponse
BeginCar = InStr(Response, "hash")
EndCar = BeginCar + 15
BitlyResult = Right(Mid(Response, BeginCar, (EndCar - BeginCar)), 7)
Range("J" & l).Value = "http://bit.ly/" & BitlyResult
How can I tell Bit.ly not to shorten a truncated URL and to keep the symbols such as "%3d"?
Thanks,
I'd think that you must escape the entire url when it is used as a parameter inside another url. The problem may not be %3d but the & that follows after it (it starts the next parameter in the bitly-url).
Try to escape this
http://domain.com/se/?st=YmUQaIg9PCoCs3vex5XHE1NnqfurVpWsXMXix0QkyO4%3d&p=A43S8C
entirely to
http%3A%2F%2Fdomain.com%2Fse%2F%3Fst%3DYmUQaIg9PCoCs3vex5XHE1NnqfurVpWsXMXix0QkyO4%253d%26p%3DA43S8C
Here are ways to do this in Excel.