Skip to content

Instantly share code, notes, and snippets.

@rennex
Created April 14, 2022 00:13
Show Gist options
  • Save rennex/9d3ff664cb0c9f91fb1ccc15affa712f to your computer and use it in GitHub Desktop.
Save rennex/9d3ff664cb0c9f91fb1ccc15affa712f to your computer and use it in GitHub Desktop.
Twitter -> IRC
require "open-uri"
require "json"
require "htmlentities"
module URLTitle
class Twitter
class << self
def fetch_tweet(id, token)
url = "https://api.twitter.com/2/tweets/#{id}?" +
"tweet.fields=created_at&expansions=author_id"
data = URI.open(url, "Authorization" => "Bearer #{token}").read
JSON.parse(data)
end
def get_author_name(data, author_id)
ud = data["users"].find {|u| u["id"] == author_id }
return [ud["name"], ud["username"]]
end
def parse(url, m)
u = URI.parse(url)
# figure out the redirection of t.co shortlinks
if u.host == "t.co"
begin
u.open(redirect: false)
rescue OpenURI::HTTPRedirect => redirect
u = redirect.uri
puts "Handled t.co redirect to #{u}"
end
end
return unless u.host =~ /^(www\.)?twitter\.com$/i
return unless u.path =~ %r{/status/(\d+)}
id = $1
json = fetch_tweet(id, m.bot.config["twitter_bearer_token"])
# extract tweet data
td = json["data"]
return unless td
tweet = HTMLEntities.new.decode(td["text"])
time = Time.parse(td["created_at"])
date = time.strftime("%d.%m.%Y")
name, username = get_author_name(json["includes"], td["author_id"])
if m.bot.config["twitter_color"]
c_logo = "\x0312" # blue
c_user = "\x02" # bold
c_meta = "\x037" # orange
c_hash = "\x0311" # cyan
c_lf = "\x037" # orange
# Colorize hashtags.
# hashtag = letters, numbers, underscores allowed.
# Must be the beginning of the line or a word.
tweet.gsub!(/(?<=\s|^)\#[\w\d_]+/, "#{c_hash}\\&\x0f")
else
c_logo = "\x02" # bold
c_user = "\x02" # bold
c_meta = ""
c_hash = "\x02" # bold
c_lf = "\x02"
end
# fix newlines
tweet.gsub!(/\s*\n+\s*/, "#{c_lf} ·\x0f ")
return "#{c_logo}[Twitter]\x0f #{c_user}#{name}\x0f #{c_meta}<@#{username}> [#{date}]\x0f: #{tweet}"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment