Skip to content

Instantly share code, notes, and snippets.

@libbymiller
Created April 6, 2020 13:58
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 libbymiller/154e065ec3a8e9135aeb9169f87962e0 to your computer and use it in GitHub Desktop.
Save libbymiller/154e065ec3a8e9135aeb9169f87962e0 to your computer and use it in GitHub Desktop.
## crontab
## * * * * * cd /opt/basictwitterbot; /usr/bin/ruby basictwitterbot.rb
## this is a fragment
def check_timeline_once(last_seen_id, client, channels, me, ls_full_path, dry_run)
opts = {}
opts[:include_entities] = true
puts "checking timeline with last seen id #{last_seen_id}"
if(last_seen_id)
opts[:since_id] = last_seen_id
end
statuses = nil
begin
statuses = client.mentions(opts)
rescue Exception => e
puts "Cannot get mentions - giving up #{e}"
end
count = 0
if(statuses && statuses.length > 0)
puts "got new statuses"
pp statuses
statuses.each do |s|
if(count==0)
# they come newest first; we want the most recent one so we don't ask for duplicates
last_seen_id = s.id
# save it for next time
File.open(ls_full_path, 'w') {|f| f.write(last_seen_id) }
end
count = count+1
# process_tweet figures out if a channel is mentioned, and if so, which one
results = process_tweet(s,channels,me)
puts results
if(results)
# build_tweet_text builds the response
new_text = build_tweet_text(results)
text = s.full_text
if(new_text)
puts "attempting update with #{new_text} length #{new_text.length}"
# since this is a cron job, these sleeps may mean 2 instances running
if(!dry_run)
begin
client.update(new_text,{:in_reply_to_status_id=>s.id})
puts "tweeted"
sleep 30 # it can tweet too much and hit rate limits
rescue Twitter::Error::TooManyRequests => error
puts "hit rate limit in tweeting #{error}"
sleep 60
retry
rescue Exception=>e
puts "error #{e}"
end
end # end dry run
end
else
puts "nothing to tweet - no results"
end
end #end statuses loop
else
puts "no new tweets"
end
end
client = Twitter::REST::Client.new do |config|
config.consumer_key = twitter_config[:basictwitterbot][:consumer_key]
config.consumer_secret = twitter_config[:basictwitterbot][:consumer_secret]
config.access_token = twitter_config[:basictwitterbot][:oauth_token]
config.access_token_secret = twitter_config[:basictwitterbot][:oauth_token_secret]
end
last_seen_id = "1030765828650807297"
me = "basictwitterbot"
channels = get_channels_list
ls_full_path = File.join(File.dirname(__FILE__), "last_seen_id_#{me}")
begin
file = File.open(ls_full_path, "r")
last_seen_id = file.read
last_seen_id = last_seen_id.strip
rescue Exception=> e
puts "no last_seen file #{e}, that's ok"
end
dry_run = false
check_timeline_once(last_seen_id, client, channels, me, ls_full_path, dry_run)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment