Skip to content

Instantly share code, notes, and snippets.

@hyuki

hyuki/twitter-markdown.rb

Last active Mar 14, 2020
Embed
What would you like to do?
twitter-markdown.rb - convert tweet to markdown.
#!/usr/bin/env ruby
# encoding: utf-8
require 'twitter'
require 'open-uri'
require 'date'
require 'uri'
# $ grep TWITTER_MARKDOWN ~/.bash_profile
# export TWITTER_MARKDOWN_consumer_key=XXXXXXXXXXXXXXXXXXXXXXXXXXX
# export TWITTER_MARKDOWN_consumer_secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# export TWITTER_MARKDOWN_access_token=9999999-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# export TWITTER_MARKDOWN_access_token_secret=xxxxxxxxxxxxxxxxxxxx
CLIENT = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_MARKDOWN_consumer_key']
config.consumer_secret = ENV['TWITTER_MARKDOWN_consumer_secret']
config.access_token = ENV['TWITTER_MARKDOWN_access_token']
config.access_token_secret = ENV['TWITTER_MARKDOWN_access_token_secret']
end
def fetch_markdown(url)
tweet = CLIENT.status(url, { tweet_mode: "extended" })
markdown = []
name = tweet.attrs[:user][:name]
screen_name = tweet.attrs[:user][:screen_name]
markdown << ">**#{name}** [@#{screen_name}](https://twitter.com/#{screen_name})"
markdown << ">"
tweet.attrs[:full_text].split(/\n/).each do |line|
markdown << ">#{line}"
end
markdown << ">"
if tweet.media?
tweet.media.each do |media|
img = media.media_url_https.to_s
markdown << ">![#{img}](#{img})"
end
end
created_at = DateTime.parse(tweet.attrs[:created_at]).to_time.localtime.strftime("%Y-%m-%d %H:%M:%S")
markdown << ">[#{created_at}](#{url})"
markdown.join("\n")
end
if ARGV.length != 1
puts "Usage: twitter-markdown TWEET-URL"
puts "Example: twitter-markdown https://twitter.com/hyuki/status/1236171158606639104"
abort
end
url = ARGV[0]
puts fetch_markdown(url)
# vim: set filetype=ruby:
@hyuki

This comment has been minimized.

Copy link
Owner Author

@hyuki hyuki commented Mar 8, 2020

@hyuki

This comment has been minimized.

Copy link
Owner Author

@hyuki hyuki commented Mar 14, 2020

media.media_urlよりmedia.media_url_httpsの方がいい。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.