28 lines
879 B
Ruby
28 lines
879 B
Ruby
|
def get_random_image(photos)
|
||
|
random_photo = photos.sample
|
||
|
|
||
|
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
|
||
|
|
||
|
params = {
|
||
|
action: 'query',
|
||
|
prop: 'imageinfo',
|
||
|
titles: "#{random_photo}", # Specify the category title
|
||
|
iiprop: 'url|user|extmetadata',
|
||
|
format: 'json' # Request response in JSON format
|
||
|
}
|
||
|
|
||
|
response = conn.get do |req|
|
||
|
req.params = params
|
||
|
end
|
||
|
|
||
|
data = JSON.parse(response.body)
|
||
|
info = data['query']['pages'].values.first
|
||
|
user = info['imageinfo'].first['user']
|
||
|
url = info['imageinfo'].first['url']
|
||
|
license = info['imageinfo'].first['extmetadata']['LicenseShortName']['value']
|
||
|
desc = info['imageinfo'].first['extmetadata']['ImageDescription']['value']
|
||
|
|
||
|
return {:user => user, :url => url, :license => license, :desc => desc}
|
||
|
end
|