Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 22, 2019 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/33f8bb2c087410606687e2a24a49674d to your computer and use it in GitHub Desktop.
Save komasaru/33f8bb2c087410606687e2a24a49674d to your computer and use it in GitHub Desktop.
Ruby script to tweet with image files.
#! /usr/local/bin/ruby
# アカウント名、文字列、画像ファイルを引数で与えてツイートする
# (twitter gem を使用せず oauth gem のみで行うバージョン)
#
# date name version
# 2017.01.16 mk-mode 1.00 新規作成
# 2019.02.15 mk-mode 1.01 画像添付機能追加
#
# Copyright(C) 2016-2019 mk-mode.com All Rights Reserved.
#---------------------------------------------------------------------------------
# 引数 : account_name tweet_text [image_path...]
# * ツイート文に半角スペースが存在する場合は "" で括る。改行は \n を使用する。
# * 画像はいくつでも指定可能だが、 Twitter の仕様で4個までしか添付できない。
#---------------------------------------------------------------------------------
#
require 'json'
require 'oauth'
require 'yaml'
class Tweet
YML_FILE = "/path/to/twitter.yml"
SITE_API = "https://api.twitter.com"
URL_UPD = "/1.1/statuses/update.json"
SITE_UL = "https://upload.twitter.com"
URL_MEDIA = "/1.1/media/upload.json"
def initialize
@ac = ARGV.shift
@text = ARGV.shift
@media_paths = ARGV
end
def exec
get_tw_keys
exit 0 unless @tw
format_text
exit 0 if @text == ""
tw_id = tweet
puts "[#{@ac}]"
puts @text
puts "(#{@media_paths.join(",")})" unless @media_paths == []
puts "(TWEET-ID: #{tw_id})"
rescue => e
$stderr.puts "[#{e.class}] #{e.message}"
e.backtrace.each { |tr| $stderr.puts "\t#{tr}" }
exit 1
end
private
# APIキー取得
def get_tw_keys
@tw = YAML.load_file(YML_FILE)
rescue => e
raise
end
# ツイート文整形
def format_text
@text = @text.gsub(/\\n/, "\n")
rescue => e
raise
end
# ツイート
def tweet
return unless @tw[@ac]
return unless @tw[@ac]["accs_key"] || @tw[@ac]["accs_sec"]
# OAuth 設定(for statuses/update)
cons = OAuth::Consumer.new(
@tw[@ac]["cons_key"],
@tw[@ac]["cons_sec"],
site: SITE_API
)
accs = OAuth::AccessToken.new(
cons,
@tw[@ac]["accs_key"],
@tw[@ac]["accs_sec"]
)
# OAuth 設定(for media/upload)
cons_ul = OAuth::Consumer.new(
@tw[@ac]["cons_key"],
@tw[@ac]["cons_sec"],
site: SITE_UL
)
accs_ul = OAuth::AccessToken.new(
cons_ul,
@tw[@ac]["accs_key"],
@tw[@ac]["accs_sec"]
)
# POST
if @media_paths == []
res = accs.post(URL_UPD, status: @text)
else
media_ids = []
@media_paths.each do |f|
img = File.open(f, "rb")
res = accs_ul.post(
URL_MEDIA,
media_data: Base64.encode64(img.read)
)
exit if res.code.to_i > 202
j = JSON.parse(res.body)
media_ids << j["media_id_string"]
end
res = accs.post(URL_UPD, {
status: @text, media_ids: media_ids.join(",")
})
end
j = JSON.parse(res.body)
return j["id_str"] ? j["id_str"] : "0"
rescue => e
raise
end
end
if __FILE__ == $0
exit if ARGV.size < 2
Tweet.new.exec
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment