Skip to content

Instantly share code, notes, and snippets.

@mashiro
Created April 18, 2018 12:31
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 mashiro/71790ebee8e9595b0bcd41bbccdd49a8 to your computer and use it in GitHub Desktop.
Save mashiro/71790ebee8e9595b0bcd41bbccdd49a8 to your computer and use it in GitHub Desktop.
require 'bundler'
Bundler.require
Slack.configure do |config|
config.token = 'xxx'
end
slack = Slack::Web::Client.new
twitter = Twitter::Streaming::Client.new do |config|
config.consumer_key = 'xxx'
config.consumer_secret = 'xxx'
config.access_token = 'xxx'
config.access_token_secret = 'xxx'
end
options = {
twitter: twitter,
slack: slack,
channel: '#twitter',
}
class TwitterToSlack
BASE_URL = 'https://twitter.com'
def initialize(options)
@twitter = options[:twitter]
@slack = options[:slack]
@channel = options[:channel]
end
def run
loop do
begin
@twitter.user do |obj|
case obj
when Twitter::Tweet
on_tweet obj
end
end
rescue => e
p e
sleep 10
end
end
end
private
def on_tweet(t)
options = {
channel: @channel,
text: text(t),
attachments: attachments(t),
as_user: false,
icon_url: t.user.profile_image_url_https.to_s,
username: t.user.screen_name,
}
puts "[#{t.created_at}] #{t.user.screen_name}: #{t.full_text}"
@slack.chat_postMessage options
end
def text(t)
make_links t.text
end
def make_links(text)
[:mention_links, :hashtag_links].inject(text) do |text, meth|
method(meth).call(text)
end
end
def mention_links(text)
text.gsub /@([a-zA-Z0-9_]+)/ do |mention|
"<#{BASE_URL}/#{$1}|#{mention}>"
end
end
def hashtag_links(text)
text.gsub /#([^#\s]+)/ do |hashtag|
"<#{BASE_URL}/hashtag/#{$1}|#{hashtag}>"
end
end
def attachments(t)
unless t.in_reply_to_status_id.nil?
[{
title: "In reply to @#{t.in_reply_to_screen_name}",
title_link: "#{BASE_URL}/#{t.in_reply_to_screen_name}/statuses/#{t.in_reply_to_status_id}",
footer: 'Twitter',
}]
end
end
end
begin
t2s = TwitterToSlack.new options
t2s.run
rescue Interrupt
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment