predator_pics/get_images_by_category.rb

56 lines
1.8 KiB
Ruby
Raw Permalink Normal View History

2024-11-13 13:27:23 +00:00
=begin
Copyright (C) 2024 Hexaitos
This file is part of "Predator Pics"
Predator Pics is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Predator Pics is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Foobar. If not, see <https://www.gnu.org/licenses/>.
Contact: me@bateleur.org, me@hexaitos.com.
=end
2024-11-10 13:12:42 +00:00
def get_images_by_category(categories)
random_category = categories.sample
2024-11-13 13:27:23 +00:00
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
2024-11-10 13:12:42 +00:00
photos = []
conn = Faraday.new(url: 'https://commons.wikimedia.org/w/api.php') do |faraday|
2024-11-13 13:27:23 +00:00
faraday.adapter Faraday.default_adapter
2024-11-10 13:12:42 +00:00
end
params = {
action: 'query',
list: 'categorymembers',
2024-11-13 13:27:23 +00:00
cmtitle: "Category:#{random_category}",
2024-11-11 23:06:10 +00:00
cmlimit: 500,
cmtype: 'file',
2024-11-13 13:27:23 +00:00
format: 'json'
2024-11-10 13:12:42 +00:00
}
response = conn.get do |req|
req.params = params
end
data = JSON.parse(response.body)
2024-11-13 13:27:23 +00:00
begin
2024-11-10 13:12:42 +00:00
category_members = data['query']['categorymembers']
category_members.each do |member|
2024-11-13 13:27:23 +00:00
photos << member['title']
2024-11-10 13:12:42 +00:00
end
2024-11-13 13:27:23 +00:00
rescue
2024-11-10 13:12:42 +00:00
puts "No data found or error in API request"
end
return photos
end