Skip to content

Instantly share code, notes, and snippets.

@zkwentz
Created December 5, 2016 03:03
Show Gist options
  • Save zkwentz/38a3222d7080c199c4acefb228a8b34b to your computer and use it in GitHub Desktop.
Save zkwentz/38a3222d7080c199c4acefb228a8b34b to your computer and use it in GitHub Desktop.
tweet bot
module Sentanalyzer
module Initializer
def initialize(*args)
self.sentihash = load_senti_file('./sentanalysis/sentiwords.txt')
self.sentihash.merge!(load_senti_file('./sentanalysis/sentislang.txt'))
super(*args)
end
end
def self.included(base)
attr_accessor :sentihash
base.send :prepend, Initializer
end
def load_senti_file (filename)
sentihash = {}
file = File.new(filename)
while (line = file.gets)
parsedline = line.chomp.split("\t")
sentiscore = parsedline[0]
text = parsedline[1]
sentihash[text] = sentiscore.to_f
end
file.close
return sentihash
end
def analyze_sentiment ( text )
tokens = text.split
sentiment_total = 0.0
for token in tokens do
sentiment_value = @sentihash[token]
if sentiment_value
sentiment_total += sentiment_value
end
end
threshold = 0.0
if sentiment_total < (-1 * threshold)
return 0
elsif sentiment_total > threshold
return 2
else
return 1
end
end
end
require 'twitter'
require 'yaml'
require './sentanalysis/analyzer.rb'
require 'active_support/core_ext/hash'
class TwitterBot
include Sentanalyzer
attr_accessor :client
attr_accessor :terms
attr_accessor :token
attr_accessor :secret
def initialize(options)
self.token = options[:token]
self.secret = options[:secret]
self.terms = options[:terms]
self.client = create_client
end
def favorite_tweets(options = {})
options[:live] = true if options[:live].nil?
options[:result_type] ||= "recent"
options[:take] ||= 9
@terms.each do |search_term|
favorited = 0
tweets = @client.search(search_term, result_type: options[:result_type]).take(options[:take])
tweets.each do |tweet|
if analyze_sentiment(tweet.text) > 0 and favorited < 3
binding.pry
@client.favorite tweet if options[:live]
puts tweet.text #unless options[:live]
favorited += 1
end
end
end
end
private
def create_client
Twitter::REST::Client.new do |config|
config.consumer_key = '5lVRLkjITCGcr47QKeNtNw'
config.consumer_secret = 'jk37VDGxqDQZXDijv7J7RQbtGoYiB2q8nmT0Wn1psLs'
config.access_token = @token
config.access_token_secret = @secret
end
end
end
twitter = YAML::load_file(File.join(__dir__, 'twitter.yml'))
profiles = twitter["profiles"]
profiles.each do |profile|
profile.symbolize_keys!
twitter_bot = TwitterBot.new({
token: profile[:token],
secret: profile[:secret],
terms: profile[:terms]
})
twitter_bot.favorite_tweets(live: true)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment