Today I am researching using APIs and I have successfully given this bot the ability to use wikipedia to answer questions it does not know the answer to. I wrote this with the help of ChatGPT we had a back and forth and eventually we were able to figure out ohw to access summaries and entire articles on wikipedia in text form. If you would like to try out this interesting code it will work as is.
local HttpService = game:GetService("HttpService")
local function SearchWikipedia2(searchq)
local url = "https://en.wikipedia.org/w/rest.php/v1/search/page?q="
-- Define the query parameters
-- Make the request and get the response
local success, response = pcall(function()
return HttpService:RequestAsync({
Url = url..searchq
-- Method = "GET",
--Query = params -- Pass the query parameters as a table
})
end)
-- Check if the request was successful
if success then
-- Check if the response status code was 200 (OK)
if response.StatusCode == 200 then
-- Parse the response body as JSON
local data = HttpService:JSONDecode(response.Body)
-- Get the first item from the result list
local item = data.pages[1]
-- Extract the title and text from the item
local title = item.title
local excerpt = item.excerpt
local pattern = "<span class=\"searchmatch\">(.-)</span>"
-- Replace the HTML tags with empty strings
local text = excerpt:gsub(pattern, "%1")
-- Print the title and text to the output
print(title)
print(text)
-- Extract the key from the item
local key = item.key
-- Construct the article URL from the key and the base URL
local base_url = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&titles="
local article_url = base_url .. key.."&format=json"
-- Print the article URL to the output
print(article_url)
-- Make another request to get the article content
local success, response = pcall(function()
return HttpService:RequestAsync({
Url = article_url,
Method = "GET"
})
end)
-- Check if the request was successful
if success then
-- Check if the response status code was 200 (OK)
if response.StatusCode == 200 then
-- Parse the response body as JSON
-- Access the extract property of the JSON object
local data = HttpService:JSONDecode(response.Body)
-- Access the pages table of the JSON object
local pages = data.query.pages
-- Use the pairs function to iterate over the pages table
for key, value in pairs(pages) do
-- Get the page key and the extract from each subtable
local page_key = key
local extract = value.extract
-- Print the page key and the extract to the output
--print(page_key)
print(extract)
end
print(data)
-- Print the extract to the output
--print(extract)
else
-- Print the response status code and status message to the output
print("Error: " .. response.StatusCode .. " " .. response.StatusMessage)
end
else
-- Print the error message to the output
print("Error: " .. response)
end
end
end
end
SearchWikipedia2("What is an archer?")