predator_pics/get_images_by_category.rb

45 lines
1.4 KiB
Ruby

def get_images_by_category(categories)
random_category = categories.sample
if random_category.include?("https://commons.wikimedia.org/wiki/Category:") then
random_category = random_category.gsub("https://commons.wikimedia.org/wiki/Category:", "")
elsif random_category.include?("Category:") then
random_category = random_category.gsub("Category:", "")
end
puts random_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