Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

t.coでURL短縮した上で140文字カウントする #30

Closed
shokai opened this issue Oct 16, 2012 · 1 comment
Closed

t.coでURL短縮した上で140文字カウントする #30

shokai opened this issue Oct 16, 2012 · 1 comment
Labels

Comments

@shokai
Copy link
Owner

shokai commented Oct 16, 2012

短縮URL t.co は強制的に使用される

https://dev.twitter.com/docs/faq#6719

URL短縮はtwitter側で行われる

https://dev.twitter.com/docs/tco-url-wrapper/how-twitter-wrap-urls

twitter側が投稿からURL抜き出しに使っているgem
https://github.com/twitter/twitter-text-rb

短縮URLは投稿前にはわからないらしい・・

t.co での短縮との付き合い方

https://dev.twitter.com/docs/tco-url-wrapper/best-practices
投稿前に help/configuration をGETして短縮後の文字数を得て計算しろとのこと。

help/configuration

https://dev.twitter.com/docs/api/1/get/help/configuration

https://api.twitter.com/1/help/configuration.json で得られる

  "short_url_length": 20,
  "short_url_length_https": 21

が現在のt.co短縮後文字数。
※1日1回しか使っちゃいけないらしい

まとめ

投稿前にtwitter-gemを使い、URLとその他に分ける。
URL部分をHTTPなら20文字、HTTPSなら21文字としてカウントすればいい。
文字数は1日1回 help/configuration に確認してcacheしておく。

@shokai
Copy link
Owner Author

shokai commented Oct 17, 2012

t.coを使った後の文字数を計算する

twitter-text gemを使う。読み込むとString#char_length等も使えるようになる。

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'rubygems'
$KCODE = 'u' if RUBY_VERSION < '1.9'
require 'twitter-text'
require 'tw'
Tw::Client.new.auth

class TcoString
  def self.conf
    @@conf ||= Twitter::configuration
  end
  def self.char_length(str)
    len = str.char_length
    Twitter::Extractor.extract_urls(str).each do |url|
      len += (url =~ /^https/ ? conf.short_url_length_https : conf.short_url_length) - url.char_length
    end
    len
  end
end

msgs = []
msgs.push "test tweet http://example.com/hoge.jpg"
msgs.push "はい http://shokai.org/blog/entry/1 はい いいえ #hashtag @shokai https://hoge.jp はい"
msgs.push ARGV.join(' ') unless ARGV.empty?

msgs.each do |m|
  puts "-"*5
  puts "source: #{m}"
  puts m.split(//u).size
  puts m.char_length
  puts "urls:"
  p Twitter::Extractor.extract_urls m
  puts "use t.co:"
  puts TcoString.char_length m
end

結果

-----
source: test tweet http://example.com/hoge.jpg
38
38
urls:
["http://example.com/hoge.jpg"]
use t.co:
31
-----
source: はい http://shokai.org/blog/entry/1 はい いいえ #hashtag @shokai https://hoge.jp はい
76
76
urls:
["http://shokai.org/blog/entry/1", "https://hoge.jp"]
use t.co:
72

shokai added a commit that referenced this issue Oct 17, 2012
shokai added a commit that referenced this issue Oct 17, 2012
@shokai shokai closed this as completed Oct 17, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant