Keep getting Ruby Twitter::Error::Forbidden - ruby

I'm pulling tweets from a text file and tweeting them in timed intervals. As the first tweet is posted, everything is fine. When its time for the next tweet to post I get an error that reads:
I got my four keys, but I can always renew them or get new ones...Here is the code I'm using:
require 'Twitter'
client = Twitter::REST::Client.new do |config|
config.consumer_key = "..."
config.consumer_secret = "..."
config.access_token = "..."
config.access_token_secret = "..."
end
def repeat_every(interval)
loop do
start_time = Time.now
yield
elapsed = Time.now - start_time
sleep([interval - elapsed, 0].max)
end
end
blog_post = []
tweet_img = []
def post
client = Twitter::REST::Client.new do |config|
config.consumer_key = "..."
config.consumer_secret = "..."
config.access_token = "..."
config.access_token_secret = "..."
end
File.open("tweets.txt") do |line|
line.each do |item|
tweets = item
puts tweets
client.update("#{tweets}").to_s
sleep((rand*1800 +900).to_i)
end
end
end
repeat_every(81000){
post
}

require 'Twitter'
def repeat_every(interval)
loop do
start_time = Time.now
yield
elapsed = Time.now - start_time
sleep([interval - elapsed, 0].max)
end
end
def post
client = Twitter::REST::Client.new do |config|
config.consumer_key = "xxxx"
config.consumer_secret = "xxxx"
config.access_token = "xxxx"
config.access_token_secret = "xxxx"
end
File.open("tweets.txt") do |line|
line.each_line do |item|
tweets = item
puts tweets
client.update("#{tweets}")
sleep((rand*10 + 10).to_i)
end
end
end
repeat_every(81000){
post
}

insert this code on the second line
OpenSSL :: SSL :: VERIFY_PEER = OpenSSL :: SSL :: VERIFY_NONE

Related

Send direct messages with twitter gem

I'm working on a twitter bot with the twitter gem. This bot is liking and following peoples. But now i want to send private messages with this gem and i cant.
This is what Im testing :
def login_twitter_stream
client_streaming =
Twitter::Streaming::Client.new do |config|
config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_ACCESS_TOKEN_SECRET"]
end
return client_streaming
end
def login_twitter
client_REST =
Twitter::REST::Client.new do |config|
config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_ACCESS_TOKEN_SECRET"]
end
return client_REST
end
def direct_messages
client = login_twitter
client
.search("#helloworld", result_type: "recent")
.take(5)
.each do
client.create_direct_message(
"#{tweet.user}",
"hello this is a test!",
options = {}
)
end
end
direct_messages
And this is the error I have with a simple
client.create_direct_message("#username","hello this is a test!",options={})
event.message_create.target.recipient_id: '#username' is not a valid Long (Twitter::Error::BadRequest)
ans this one:
undefined local variable or method `tweet' for main:Object (NameError)
I hope u have the solution ! Have a great day.
get the id of the twitter you want to send a message with. You can use this link to get an Id.
Then you can execute the command:
client.create_direct_message('<replace with the twitter Id you obtained>',"hello this is a test!",options={})
the tweet.user in your example means, there is a tweets-table(a model class) and the twitter Id is saved in the user-column.

ruby tweet line from text file

My code won't tweet from the file every interval, it only prints in the terminal, but not on twitter. I'm also trying to loop it so that once done with the file.length its repeats. Thanks for your help.
require 'Twitter'
client = Twitter::REST::Client.new do |config|
config.consumer_key = "..."
config.consumer_secret = "..."
config.access_token = "..."
config.access_token_secret = "..."
end
blog_post = []
tweet_img = []
def post
File.open("tweets.txt") do rand |line|
line.each do |item|
tweets = item.chomp.split("\n")
#while client.update("#{}")
puts tweets
sleep(30)
#end
#puts blog_post.to_s, "\n\n"
end
end
end
puts client.update("#{post}").text
require 'Twitter'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
client = Twitter::REST::Client.new do |config|
config.consumer_key = "xxxx"
config.consumer_secret = "xxxx"
config.access_token = "xxxx"
config.access_token_secret = "xxxx"
end
file = File.open("tweets.txt")
ary = []
i = 0
file.each_line do |line|
ary[i] = line.chomp
i += 1
end
file.close
j = 0
i.times do
client.update("#{ary[j]}")
j += 1
sleep 10
end
Your call to Twitter:
client.update("#{post}").text
is outside of your loop, so it is only called once. If you want it for each line, it should be:
def post
File.open("tweets.txt") do rand |line|
line.each do |item|
tweets = item.chomp.split("\n")
puts tweets
client.update("#{tweets}").text
sleep(30)
end
end
end

How to create instance of Twitter::Tweet to create retweeted_by_user

I want to call retweeted_by_user(user, options = {}). How do I create instance of object Twitter::Tweet (in Twitter::REST::Timelines module) to call this method. It is instance method, correct?
I did this for Twitter::REST::CLIENT
client = client = Twitter::REST::Client.new do |config|
config.consumer_key = "..."
config.consumer_secret = "..."
config.access_token = "..."
config.access_token_secret = "..."
end
but it does not work for Twitter::Tweet
client = client = Twitter::Tweet.new do |config|
config.consumer_key = "..."
config.consumer_secret = "..."
config.access_token = "..."
config.access_token_secret = "..."
end
Here are the docs for Twitter gem. I need a little more explanation
http://rdoc.info/gems/twitter/Twitter/REST/Timelines#retweeted_by_user-instance_method
spec are the best documentation and explanation:
client:
https://github.com/sferik/twitter/blob/c9cfca9bf156ac0569d6c2cd7117327daf10a643/spec/twitter/rest/timelines_spec.rb#L6
method usage:
https://github.com/sferik/twitter/blob/c9cfca9bf156ac0569d6c2cd7117327daf10a643/spec/twitter/rest/timelines_spec.rb#L58

Implement caching in Sinatra app to handle twitter rate limits

I have written a small Sinatra script to fetch 2 tweets of a user and display 10 retweeters in the descending order of their no. of followers:
Puzzle/puzzle.rb
require 'twitter'
require 'json'
require 'sinatra'
#require 'haml'
client = Twitter::REST::Client.new do |config|
config.consumer_key = ""
config.consumer_secret = ""
config.access_token = ""
config.access_token_secret = ""
end
set :server, 'webrick'
set :haml, :format => :html5
get '/' do
content_type :json
arr = []
retweeters = client.retweeters_of(429627812459593728)
retweeters.each do |retweeter|
ob = {}
ob[:name] = retweeter.name
ob[:followers_count] = retweeter.followers_count
arr.push(ob)
end
# remove the duplicates and sort on the users with the most followers,
sorted_influencers = arr.sort_by { |hsh| hsh[:followers_count] }
sorted_influencers.reverse!
sorted_influencers[0..9].to_s
end
I am trying to handle rate limits.
How to cache the json output to avoid rate limit exceeding?
Assuming you keep your very simple scenario, you could use a small custom class to store the information and provide thread-safe methods (it is not clear from your question where your problem exactly resides, but this one problem will arise anyway):
require 'json'
require 'sinatra'
require 'date'
require 'thread'
require 'twitter'
set :server, 'webrick'
set :haml, :format => :html5
class MyCache
def initialize()
#mutex = Mutex.new
#last_update = DateTime.new # by default, -4732 BC
#client = Twitter::REST::Client.new do |config|
config.consumer_key = ""
config.consumer_secret = ""
config.access_token = ""
config.access_token_secret = ""
end
end
def get_cache
#mutex.synchronize do
if DateTime.now - #last_update > 10.0 / (3600 * 24)
#last_update = DateTime.now
arr = []
retweeters = #client.retweeters_of(429627812459593728)
retweeters.each do |retweeter|
ob = {}
ob[:name] = retweeter.name
ob[:followers_count] = retweeter.followers_count
arr.push(ob)
end
# remove the duplicates and sort on the users with the most followers,
sorted_influencers = arr.sort_by { |hsh| hsh[:followers_count] }
sorted_influencers.reverse!
#cache = sorted_influencers[0..9].to_s
end
#cache
end
end
end
my_cache = MyCache.new
get '/' do
content_type :json
my_cache.get_cache
end
This version now includes everything needed. I use the #client to store the instance of the twitter client (I suppose it's reusable), also note how the whole code is inside the if statement, and at last we update #cache. If you are unfamiliar with Ruby, the value of a block is determined by its last expression, so when I write #cache alone it is as if I had written return #cache.

Sinatra app doesnt redirect to haml files

This is the Sinatra code that I wrote. All gems exist, the ruby files compiles perfectly but when i go to localhost:4567/ the sinatra app doesnt run. It takes me to the 'Sinatra doesnt know this ditty' page. What mistake am i making here? Is it a syntax issue? I've posted the main ruby file's code here others are just haml files thats all.
require 'bundler'
Bundler.setup(:default)
require 'sinatra'
require 'haml'
require 'twitter'
require 'oauth'
class MyTweetWeek < Sinatra::Base
set :haml, :format => :html5, :attr_wrapper => '"'
enable :sessions, :static, :raise_errors
set :public_dir, File.join(File.dirname(__FILE__), 'public')
get '/' do
haml :index
end
get '/login' do
request_token = consumer.get_request_token(:oauth_callback => ENV['OAUTH_CALLBACK'])
session[:request_token] = request_token.token
session[:request_token_secret] = request_token.secret
redirect request_token.authorize_url
end
get '/oauth_callback' do
request_token = OAuth::RequestToken.new(
consumer,
session[:request_token],
session[:request_token_secret]
)
session[:request_token] = session[:request_token_secret] = nil
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
session[:access_token] = access_token.token
session[:access_secret] = access_token.secret
redirect '/resume'
end
get '/resume' do
redirect '/' unless authenticated?
today = Date.today #get today's date
monday = today - today.cwday + 1 #calculate Monday
search = Twitter::Search.new
#screen_name = client.verify_credentials.screen_name
#number_of_tweets = 0
#number_of_mentions = 0
results = search.from(#screen_name)
.since_date(monday)
.no_retweets
.per_page(100)
.fetch
#number_of_tweets += results.size
while search.next_page?
results = search.fetch_next_page
#number_of_tweets += results.size
end
search.clear
results = search.q("##{#screen_name.gsub('#', '')}")
.since_date(monday)
.no_retweets
.per_page(100)
.fetch
#number_of_mentions += results.size
while search.next_page?
results = search.fetch_next_page
#number_of_mentions += results.size
end
haml :resume
end
error Twitter::Error::Unauthorized do
redirect '/'
end
not_found do
haml :not_found
end
private
def consumer
#consumer ||= OAuth::Consumer.new(
ENV['CONSUMER_KEY'],
ENV['CONSUMER_SECRET'],
:site => "https://api.twitter.com"
)
end
def client
Twitter.configure do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.oauth_token = session[:access_token]
config.oauth_token_secret = session[:access_secret]
end
#client ||= Twitter::Client.new
end
def authenticated?
!session[:access_token].nil? && !session[:access_secret].nil?
end
end
As you have a modular app do you need to require "sinatra/base" rather than "sinatra"? See here
See Serving a Modular App and add the line run! if app_file == $0 at the end of the class. Also see DavB's answer.

Resources