You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

twitter.rb 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. require 'twitter'
  2. require 'twitter-text'
  3. class CrossPost
  4. class Twitter
  5. def initialize(config)
  6. config = {
  7. consumer_key: config['twitter.consumer.key'],
  8. consumer_secret: config['twitter.consumer.secret'],
  9. access_token: config['twitter.access.token'],
  10. access_token_secret: config['twitter.access.secret']
  11. }
  12. @client = ::Twitter::REST::Client.new config
  13. @stream = ::Twitter::Streaming::Client.new config
  14. end
  15. def post(status)
  16. content = Sanitize.clean status.content
  17. last = nil
  18. parts = split content
  19. attachments = status.media_attachments
  20. media = attachments.collect do |f|
  21. f = open f.url
  22. begin
  23. @client.upload f
  24. ensure
  25. f.close
  26. f.unlink
  27. end
  28. end
  29. unless media.empty?
  30. first, *parts = parts
  31. last = @client.update first, media_ids: media.join(',')
  32. end
  33. parts.each { |p| last = @client.update p, in_reply_to_status: last }
  34. end
  35. private
  36. def split(text)
  37. parts = []
  38. part = ''
  39. words = text.split ' '
  40. words.each do |word|
  41. old_part = part
  42. part += ' ' unless part == ''
  43. part += word
  44. invalid = ::Twitter::Validation.tweet_invalid? part
  45. if invalid
  46. parts << old_part
  47. part = word
  48. end
  49. end
  50. parts << part unless part == ''
  51. parts
  52. end
  53. end
  54. end