How do ask ChatGPT with API from Excel macros (vba)? - excel

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.

Related

Access Pushbullet API from Selenium VBA

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.

Creating a spreadsheet for MTG cards that automatically updates prices based on a specific website

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.

Trying to get ResponseText from a GET request in Twitter

I'm trying to improve my knowledge of VBA, learning about GET, POST and stuff, because I've seen many examples, and can't get what I'm doing wrong. Probably is the Oauth part.
The main problem is that I'm just an Excel guy. I'm not web developer, so my knowledge is almost null, and probably I'm missing a lot of basic stuff.
I hope this question is not too broad.
BACKGROUND: I'm trying to get the ResponseText of a JSON object, from a tweet. The information is public and you don't need to be logged in to see the info I want to get, and you don't need a Twitter account.
For testing, I'm using this tweet: https://twitter.com/StackOverflow/status/1273391252357201922
WHAT I WANT: Checking the code with Developer Tools (I'm using Firefox), I've seen this:
This GET request returns this ResponseText:
So I would like to get that ResponseText into VBA.
MY CODE: Checking different codes here in SO, I've build up this:
Sub test()
Dim MiHttp As Object
Dim MiUrl As String
Set MiHttp = CreateObject("MSXML2.XMLHTTP")
MiUrl = "https://api.twitter.com/2/timeline/conversation/1273391252357201922.json?include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&skip_status=1&cards_platform=Web-12&include_cards=1&include_ext_alt_text=true&include_reply_count=1&tweet_mode=extended&include_entities=true&include_user_entities=true&include_ext_media_color=true&include_ext_media_availability=true&send_error_codes=true&simple_quoted_tweet=true&count=20&ext=mediaStats%2ChighlightedLabel&include_quote_count=true"
With MiHttp
.Open "GET", MiUrl
.Send
DoEvents
Debug.Print .responseText
End With
MiHttp.abort
Set MiHttp = Nothing
End Sub
And it runs, no coding errors, but I get this:
{"errors":[{"code":200,"message":"Forbidden."}]}
So I tried adding RequestHeaders with Authoritation:
adding this line of code before .Send:
.setRequestHeader "authorization", "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
And then I get this in the debugger:
{"errors":[{"message":"Rate limit exceeded","code":88}]}
So checked the Twitter library for developers looking info about Bearer stuff and tokens and I must admit I got overwhelmed.
About
Bearer
About
Tokens
And now I'm lost. I thought this would be kind of easy, because it's public info that everyone can get manually, from any tweet, without using any app or logging in Twitter, but it's looks like I'm wrong, and I'm kind of lost.
FINAL QUESTION: I would like to know if I can get that Bearer token in any way, then apply it into my code, to get that JSON responseText (dealing with the JSON and learning about them would be a totally different question, out of scope here).
And I would like to achieve this with VBA, no other apps or languages, because I've have no idea.
Actually I'm not even interested in the full text, just the part surrounded with red line.
Looking for some help, guide, light.
Thanks in advance and I hope this question is not too broad.
Thanks!
UPDATES: Tested #ChristosLytras's answer. I get this error:
UPDATE JULY 2020: now the working url is:
https://api.twitter.com/2/timeline/conversation/1273391252357201922.json?include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&skip_status=1&cards_platform=Web-12&include_cards=1&include_ext_alt_text=true&include_reply_count=1&tweet_mode=extended&include_entities=true&include_user_entities=true&include_ext_media_color=true&include_ext_media_availability=true&send_error_codes=true&simple_quoted_tweet=true&count=20&ext=mediaStats%2ChighlightedLabel&include_quote_count=true
You have to pass a valid fetched Guest Token in the request header along with authorization Bearer and you'll have the response. The twitter public API bearer never changes.
In order to get a new and valid Guest Token for each request, you can make a HEAD request using WinHttp.WinHttpRequest.5.1 instead of MSXML2.XMLHTTP and read the gt cookie using a regular expression like gt=(\d+);. That will fetch the cookie headers each time it's being called. You cannot use MSXML2.XMLHTTP because it uses cache and you won't get a new Guest Token each time you request the HEAD.
Working code tested using Excel 2013 with VBA 7.1:
Dim MiHttp As Object
Dim GuestTokenRE As Object
Dim MiUrl As String
Set MiHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
Set GuestTokenRE = CreateObject("VBScript.RegExp")
MiUrl = "https://api.twitter.com/2/timeline/conversation/1273391252357201922.json?include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&skip_status=1&cards_platform=Web-12&include_cards=1&include_ext_alt_text=true&include_reply_count=1&tweet_mode=extended&include_entities=true&include_user_entities=true&include_ext_media_color=true&include_ext_media_availability=true&send_error_codes=true&simple_quoted_tweet=true&count=20&ext=mediaStats%2ChighlightedLabel&include_quote_count=true"
With MiHttp
' Make a HEAD request with no cache to get the Guest Token cookie
.Open "HEAD", "https://twitter.com", False
.setRequestHeader "User-Agent", "Firefox"
.setRequestHeader "Pragma", "no-cache"
.setRequestHeader "Cache-Control", "no-cache"
.Send
DoEvents
' Use a regular expression to extract guest token from response headers
GuestTokenRE.Pattern = "Set-Cookie: gt=(\d+);"
GuestTokenRE.IgnoreCase = True
Dim matches as Object
Set matches = GuestTokenRE.Execute(.getAllResponseHeaders())
If matches.Count = 1 Then
Dim guestToken As String
guestToken = matches.Item(0).Submatches.Item(0)
' Print the Guest Token for validation
Debug.Print "Got Guest Token", guestToken
' Now we have a valid guest token, make the request
.Open "GET", MiUrl, False
' Authorization Bearer is always the same
.setRequestHeader "authorization", "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
.setRequestHeader "x-guest-token", guestToken
.Send
DoEvents
Debug.Print "Got response", .responseText
Else
Debug.Print "Could not fetch Guest Token"
End If
End With
MiHttp.abort
Set MiHttp = Nothing
Set GuestTokenRE = Nothing
Regarding 80072efe error
You'll have to get WinHttp.WinHttpRequest.5.1 to work. The 80072efe error indicates the connection terminates abnormally and you can read more about it here. I didn't have such an issue so these errors do not originate from the endpoint.
Screen capture of the code in action

Get access token for Graph API

It's my first attempt to call a Graph API (with VBA), but I still could not get one access token for this.
Although I have read the documentation, I do not know what flow I need to apply to get access token without forcing the user to log in. Is this possible on my OneDrive Personal Accounts?
Here is what I have tried
Sub Test_GetToken()
Dim xml As New MSXML2.XMLHTTP60
Dim url As String
url = "https://login.microsoftonline.com/namelles_test#outlook.com/oauth2/v2.0/token"
url = url & "?client_id=eca0b14c-1154-4768-8e45-2cb5639b7e0d"
url = url & "grant_type=client_credentials"
url = url & "&client_secret=VksZ8FeDF5XiRfqTBsgs628"
url = url & "&resource=https://graph.microsoft.com"
xml.Open "POST", url, False
xml.setRequestHeader "application", "x-www-form-urlencoded"
xml.send ("")
Debug.Print "status=" & xml.Status, "readyState=" & xml.readyState
Debug.Print xml.responseText
Set xml = Nothing
End Sub
I created an account just for testing (username: nameless_test#outlook.com, userpass: nameless1234). Therefore, the real credentials can be used.
Can someone show me the flow I need to apply and how exactly the request is built?
Thanks in advance
Looks like you put the email incorrectly in your code.
url = "https://login.microsoftonline.com/namelles_test#outlook.com/oauth2/v2.0/token"
Should be:
url = "https://login.microsoftonline.com/nameless_test#outlook.com/oauth2/v2.0/token"
Also, based on your comment, it seems that you have to put the grant_type in the body of the request instead of a query parameter in the URL.
xml.send ("grant_type=client_credentials")

Docusign with VBA - code 401

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

Resources