predator_pics/get_images_by_category.rb

43 lines
1.4 KiB
Ruby
Raw Normal View History

2024-11-10 13:12:42 +00:00
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
2024-11-10 13:12:42 +00:00
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