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.6KB

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