37 lines
1.1 KiB
Ruby
37 lines
1.1 KiB
Ruby
|
def get_images_by_category(categories)
|
||
|
random_category = categories.sample.gsub("https://commons.wikimedia.org/wiki/Category:", "")
|
||
|
photos = []
|
||
|
|
||
|
conn = Faraday.new(url: 'https://commons.wikimedia.org/w/api.php') do |faraday|
|
||
|
faraday.adapter Faraday.default_adapter # Use the default adapter (Net::HTTP)
|
||
|
end
|
||
|
|
||
|
# Define the parameters for the request
|
||
|
params = {
|
||
|
action: 'query',
|
||
|
list: 'categorymembers',
|
||
|
cmtitle: "Category:#{random_category}", # Specify the category title
|
||
|
cmlimit: 100,
|
||
|
format: 'json' # Request response in JSON format
|
||
|
}
|
||
|
|
||
|
# Send the GET request
|
||
|
response = conn.get do |req|
|
||
|
req.params = params
|
||
|
end
|
||
|
|
||
|
# Parse the response as JSON
|
||
|
data = JSON.parse(response.body)
|
||
|
|
||
|
# Handle and print the response
|
||
|
if data['query'] && data['query']['categorymembers']
|
||
|
category_members = data['query']['categorymembers']
|
||
|
category_members.each do |member|
|
||
|
photos << member['title']
|
||
|
end
|
||
|
else
|
||
|
puts "No data found or error in API request"
|
||
|
end
|
||
|
|
||
|
return photos
|
||
|
end
|