#!/usr/bin/ruby =begin This file is part of Bot of Prey. Bot of Prey 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. Bot of Prey 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 . Author: Hexaitos (me@hexaitos.com, me@bateleur.org) =end require 'dotenv/load' require 'net/http' require 'json' require 'uri' require 'faraday' require 'faraday/multipart' require 'down' require 'marcel' require 'sanitize' auth_token = ENV['API_KEY'] instance_url = ENV['INSTANCE_URL'] bird_api_url = ENV['BIRD_API_URL'] conn = Faraday.new(url: bird_api_url) do |faraday| faraday.adapter Faraday.default_adapter end response = conn.get data = JSON.parse(response.body) puts "Data received from bird API: #{data}" user, url, thumb, license, desc, license_url, user_url = data.values_at('user', 'url', 'thumb', 'license', 'desc', 'license_url', 'user_url') desc_sanitised = Sanitize.clean(desc) status = "#{desc}\n\n**Attribution and license**: #{user} (#{license})\n**Source**: #{url}" puts "Status for post: #{status}" image = Down.download(thumb) image_mime = "" File.open image.path do |file| image_mine = Marcel::MimeType.for file end conn = Faraday.new( url: "#{instance_url}", headers: {'Content-Type' => 'multipart/form-data'} ) do |faraday| faraday.request :multipart faraday.adapter Faraday.default_adapter end file = Faraday::Multipart::FilePart.new( image.path, image_mime ) response = conn.post('/api/v2/media') do |req| req.headers['Authorization'] = "Bearer #{auth_token}" req.body = { file: file, description: "A photo of a bird of prey taken from Wikimedia Commons. The photo was described as follows by the original uploader or creator: #{desc_sanitised}" } end puts "Response received after media upload: #{response.status}" parsed_response = JSON.parse(response.body) media_id = parsed_response["id"] conn = Faraday.new( url: "#{instance_url}", headers: {'Content-Type' => 'multipart/form-data'} ) do |faraday| faraday.request :multipart faraday.adapter Faraday.default_adapter end response = conn.post('/api/v1/statuses') do |req| req.headers['Authorization'] = "Bearer #{auth_token}" req.body = { 'status' => status, 'visibility' => 'public', 'media_ids[]' => media_id } end puts "Reponse received from server after posting status: #{JSON.parse(response.body)}"