Skip to content

Instantly share code, notes, and snippets.

@shelbyd
Last active June 9, 2022 13:30
Show Gist options
  • Save shelbyd/06d14b427b446919b8fde8137833d646 to your computer and use it in GitHub Desktop.
Save shelbyd/06d14b427b446919b8fde8137833d646 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "httparty"
BEARER_TOKEN = ENV["TWITTER_BEARER_TOKEN"]
abort "No TWITTER_BEARER_TOKEN in env" if BEARER_TOKEN.nil?
abort "Provide 2 usernames" if ARGV.size != 2
def get_user_by_username(username)
api_call("/users/by", query: { usernames: username })["data"][0]
end
def follows?(follower, followed, pagination_token: nil)
response = api_call(
"/users/#{follower}/following",
{pagination_token:, max_results: 1000}
)
if response["data"].include?(followed) return true end
next_token = response["meta"]["next_token"]
if next_token.nil? return false end
follows?(follower, followed, next_token)
end
def api_call(path, query: {})
response = HTTParty.get(
"https://api.twitter.com/2#{path}",
query:,
headers: {"Authorization": "Bearer #{BEARER_TOKEN}"},
)
if response.code.to_s.start_with?("4", "5") || response["errors"]
puts "API Error"
pp response
abort
end
response
end
follower, followed = ARGV.map { |username| get_user_by_username(username) }
if follows?(follower, followed)
puts "y"
else
puts "n"
exit 1
end
def follows_iter?(follower, followed, pagination_token: nil)
paginated_api("/users/#{follower}/following", |data| do
if data.include?(followed) return true end
end)
false
end
def paginated_api(path, &block)
token = nil
while true
response = api_call(path, {pagination_token: token, max_results: 1000})
block(response["data"])
token = response["meta"]["next_token"]
if token.nil? return end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment