Display output of ruby script requiring Mechanize on MacOS Desktop using GeekTools? - ruby

I have written a working ruby script using mechanize for fetching my
Stackoverflow reputation and badges
Twitter tweets and followers
and printing the output to screen.
I run this command on the terminal first :
/Users/cyclotrojan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby /Users/cyclotrojan/Desktop/Snippets/get_so_reputation_and_tw_followers.rb
The output is correctly displayed like this on the terminal:
StackOverflow :
Reputation is : 406
Total Badges : 10
Twitter :
Tweets : 1,494
Followers : 137
Now I wish to display the output of my script on my desktop using GeekTools and set refresh time to 30 minutes, so it keeps running the script over and over thus updating my stats. However when I paste the same command on a geektool shell, no output comes.
Here is the script :
File get_so_reputation_and_tw_followers.rb
require 'mechanize'
def get_stackoverflow_data
url_so = 'https://stackoverflow.com/users/898346/cyclotrojan'
begin
so_page = Mechanize.new.get(url_so)
so_reputation = so_page.link_with(:href => "/users/898346/cyclotrojan?tab=reputation").to_s
so_badges = so_page.search(".badgecount").first
print "StackOverflow :" + "\n"
print " Reputation is : " + so_reputation + "\n"
print " Total Badges : " + so_badges + "\n"
rescue
print "StackOverflow :" + "\n"
print "\tReputation is : " + "NA" + "\n"
print "\tTotal Badges : " + "NA" + "\n"
end
end
def get_twitter_data
url_tw = 'https://twitter.com/cyclotrojan'
begin
tw_page = Mechanize.new.get(url_tw)
tw_tweets = tw_page.link_with( :href => "/" + url_tw.split("/").last).to_s.split(" ").first
tw_followers = tw_page.link_with( :href => "/#!/" + url_tw.split("/").last + "/followers").to_s.split(" ").first
print "Twitter :" + "\n"
print "\tTweets : " + tw_tweets + "\n"
print "\tFollowers : " + tw_followers + "\n"
rescue
print "Twitter :" + "\n"
print "\tTweets : " + "NA" + "\n"
print "\tFollowers : " + "NA" + "\n"
end
end # end function
get_stackoverflow_data()
get_twitter_data()
However, the output simply doesnt show up on my desktop. I know that the problem is not with detecting ruby, since I tested it out using another file test.rb
File test.rb
puts "hello"
This command will work on GeekTool shell and display hello correctly :
/Users/cyclotrojan/.rvm/rubies/ruby-1.9.2-p290/bin/ruby /Users/cyclotrojan/Desktop/Snippets/test.rb;
Output on geektool shell:
hello
I have done some debugging and found that if I remove the line
require 'mechanize'
then the script runs correctly and due to exception the following output is displayed :
StackOverflow :
Reputation is : NA
Total Badges : NA
Twitter :
Tweets : NA
Followers : NA
So the issue is with including mechanize in the script. Please help me in resolving this. Thnx !
These questions didnt help :
How to run Ruby scripts in Geektool? ,
Ruby, Mac, Geektool question, file access rights?

You would be able to tell if you didn't try to rescue the error. It looks like our old friend ssl verify error so try this:
#agent = Mechanize.new
#agent.verify_mode = OpenSSL::SSL::VERIFY_NONE
tw_page = #agent.get url_tw
I should add that you might want to make sure you understand the consequences of OpenSSL::SSL::VERIFY_NONE
Also here is a tip:
tweets = tw_page.at('a[#data-element-term="tweet_stats"] strong').text rescue 'N/A'
followers = tw_page.at('a[#data-element-term="follower_stats"] strong').text rescue 'N/A'
puts "Twitter :" + "\n"
puts "\tTweets : #{tweets}"
puts "\tFollowers : #{followers}"

Related

a string output is not showing ruby

I'm tried these ruby code lines to run in sublimeText3 but I dont get any error even in view ->show console. Show result shows me that the coding is building, but I couldn't see any output there. The below code is what I'm trying.
guess.rb
words = ['foobar', 'baz', 'quux']
secret = words[rand(3)]
print "guess? "
while guess = STDIN.gets
guess.chop!
if guess == secret
puts "You win!"
break
else
puts "Sorry, you lose."
end
print "guess? "
end
puts "The word was ", secret, "."
Since the Sublime Text console does not accept any input, you need to install package like SublimeREPL. You can launch it from Tools > SublimeREPL > Ruby.

loop through json array and retrieve one attribute, gives errors also

i am new to programming in ruby, and i am trying to get the value of json['earning_rate_hr'] but i get an error, in '[]': no implicit conversion of String into Integer (TypeError)
i know and i understand the error, however this is not my main question here is my file :
checkingchecker.rb :
#require_relative '../lib/hackex/net/typhoeus'
require_relative '../lib/hackex'
require 'rubygems'
require 'json'
file = 'accounts1.txt'
f = File.open file, 'r'
puts "MADE BY THE PEOPLE, FOR THE PEOPLE #madebylorax"
puts ""
puts "--------------------------------------------------------"
puts ""
while line = f.gets
line = line.chomp.split(';')
email, password = line
puts "logging in as " + email
HackEx.LoginDo(email, password) do |http, auth_token, user|
puts "getting info..."
user = HackEx::Request.Do(http, HackEx::Request.UserInfo(auth_token))['user']
puts "receieved user info!"
bank = HackEx::Request.Do(http, HackEx::Request.UserBank(auth_token))['user_bank']
puts "recieved bank info!"
json = HackEx::Request.Do(http, HackEx::Request.UserSpam(auth_token))['spam']
puts "recieved spam info!"
puts json['earning_rate_hr'] #error line, the error is because this is an array, and it cant be turned into integer, i was wondering if there is a way to use puts on it without trying to make it an integer
userchecking = bank["checking"]
checking = userchecking.scan(/.{1,3}/).join(',')
puts email + " has in Checking: BTC #{checking}"
puts ""
puts "--------------------------------------------------------"
puts ""
end
end
i tried to do puts json, it puts items like this one :
{"id"=>"9867351", "user_id"=>"289108", "victim_user_id"=>"1512021",
"victim_ip"=
"86.60.226.175", "spam_level"=>"50", "earning_rate_hr"=>"24300", "total_earning s"=>"13267800", "started_at"=>"2015-11-01 07:46:59",
"last_collected_at"=>"2015- 11-24 01:46:59"}
what i want to do is select the earning_rate_hr for each one of them and add them together, however i do not have a clue on how to do that, since the error is not fixed and i cant get the value of it
ps : i tried turning it into a Hash, and i also tried using .first, but .first only shows the firs one, i want to show all of them, thank you
I know you from line messenger, I haven't used ruby codes in a long time and this one keeps giving me cloudflare errors, I'm not sure if its because of server downtime/maintainance or whatever but yeah anyway heres your script, enjoy farming ;) -LineOne
PS, I changed a few strings to make it look a lil cleaner so you can see the spam income easier, and added the sleep (1) because sleeping for one second before reconnecting helps to prevent cloudflare errors
also you don't need to require json or rubygems in your hackex scripts because its required in the library so its all covered pre-user-input/script
require_relative 'libv5/lib/hackex'
while 1<2
begin
print'Filename: '
fn=gets.chomp
file = fn+'.txt'
f = File.open file, 'r'
puts "MADE BY THE PEOPLE, FOR THE PEOPLE #madebylorax" #helped by lineone
puts ""
puts "--------------------------------------------------------"
puts ""
while line = f.gets
line = line.chomp.split(';')
email, password = line
HackEx.LoginDo(email, password) do |http, auth_token, user|
puts "Retrieving Info..."
puts''
user = HackEx::Request.Do(http, HackEx::Request.UserInfo(auth_token))['user']
bank = HackEx::Request.Do(http, HackEx::Request.UserBank(auth_token))['user_bank']
json = HackEx::Request.Do(http, HackEx::Request.UserSpam(auth_token))['spam']
cash_count=0
tot_count=0
json.each do |j|
earn_rate = j['earning_rate_hr']
total= j['total_earnings']
cash_count+=earn_rate.to_i
tot_count+=total.to_i
end
print "#{email}: current earnings: #{cash_count} per hour, Total earnings #{tot_count},"
userchecking = bank["checking"]
checking = userchecking.scan(/.{1,3}/).join(',')
puts " #{checking} BTC in Checking"
puts ""
puts "--------------------------------------------------------"
puts ""
sleep 1
end
end
rescue
puts"#{$!}"
end
end
Thats fine you can also calculate the total income of your farms by adding new variables at the top example a=0 then adding the number at the end a+=tot_count
This should help:
earning_rates = json.map{|e| e["earning_rate_hr"]}
puts "Earning rates per hour: #{earning_rates.join(" ")}"
puts "Sum of earning rates: #{earning_rates.map{|e| e.to_i}.inject{|sum, x| sum + x}}"

Appending a parameter's value in parameters.yml when deploying symfony application

First of all I've never used ruby and capifony so this question might be very easy for some of you but not for me. I tried to find examples related to my question but couldn't find any or I'm too new to ruby to miss!
When deploying my Symfony app, the value of a particular key in my parameters file should be dynamically appended so, rather than using exact generic value coming from distribution file below:
parameters_prod.yml.dist
parameters:
my_prefix: my_value_prefix_
Straight after deployment, parameters.yml should read like below:
parameters.yml
parameters:
my_prefix: my_value_prefix_8235647895
8235647895 part above is going to be timestamp.
How can I do this?
My current deploy.rb
namespace :mytest do
desc "Upload the parameters.yml"
task :upload_parameters do
origin_file = parameters_dir + "/" + parameters_file if parameters_dir && parameters_file
origin_file_append = parameters_dir + "/" + parameters_file_append if parameters_dir && parameters_file_append
if origin_file && File.exists?(origin_file)
relative_path = "app/config/parameters.yml"
files = [origin_file]
files << origin_file_append if origin_file_append && File.exists?(origin_file_append)
tmp_origin_file = origin_file + '.tmp'
File.open(tmp_origin_file, 'w') do |fo|
files.each do |file|
File.foreach(file) do |li|
fo.puts li
end
end
end
if shared_files && shared_files.include?(relative_path)
destination_file = shared_path + "/" + relative_path
else
destination_file = latest_release + "/" + relative_path
end
try_sudo "mkdir -p #{File.dirname(destination_file)}"
top.upload(tmp_origin_file, destination_file)
File.delete(tmp_origin_file)
end
end
end

Ruby mulitple conditional statment write to same file twice?

I am trying to create a find and replace script in ruby. But I cannot figure out how to write to the same file twice when there are two conditions matched (2 different regex patterns are found and need to be replaced in the same file) I can get it to provide 2 copies of the file concatonated with only changes made from one condition in each.
Here is my code (Specifically pattern3 and pattern4):
print "What extension do you want to modify? "
ext = gets.chomp
if ext == "py"
print("Enter password: " )
pass = gets.chomp
elsif ext == "bat"
print "Enter drive letter: "
drive = gets.chomp
print "Enter IP address and Port: "
ipport = gets.chomp
end
pattern1 = /'Admin', '.+'/
pattern2 = /password='.+'/
pattern3 = /[a-zA-Z]:\\(?i:dir1\\dir2)/
pattern4 = /http:\/\/.+:\d\d\d\d\//
Dir.glob("**/*."+ext).each do |file|
data = File.read(file)
File.open(file, "w") do |f|
if data.match(pattern1)
match = data.match(pattern1)
replace = data.gsub(pattern1, '\''+pass+'\'')
f.write(replace)
puts "File " + file + " modified " + match.to_s
elsif data.match(pattern2)
match = data.match(pattern2)
replace = data.gsub(pattern2, 'password=\''+pass+'\'')
f.write(replace)
puts "File " + file + " modified " + match.to_s
end
if data.match(pattern3)
match = data.match(pattern3)
replace = data.gsub(pattern3, drive+':\dir1\dir2')
f.write(replace)
puts "File " + file + " modified " + match.to_s
if data.match(pattern4)
match = data.match(pattern4)
replace = data.gsub(pattern4, 'http://' + ipport + '/')
f.write(replace)
puts "File " + file + " modified " + match.to_s
end
end
end
end
f.truncate(0) makes things better but truncates the first line since it concatonates from the end of the 1st modified portion of the file.
Try writing file only once after all substitutions:
print "What extension do you want to modify? "
ext = gets.chomp
if ext == "py"
print("Enter password: " )
pass = gets.chomp
elsif ext == "bat"
print "Enter drive letter: "
drive = gets.chomp
print "Enter IP address and Port: "
ipport = gets.chomp
end
pattern1 = /'Admin', '.+'/
pattern2 = /password='.+'/
pattern3 = /[a-zA-Z]:\\(?i:dir1\\dir2)/
pattern4 = /http:\/\/.+:\d\d\d\d\//
Dir.glob("**/*.#{ext}").each do |file|
data = File.read(file)
data.gsub!(pattern1, "'#{pass}'")
data.gsub!(pattern2, "password='#{pass}'")
data.gsub!(pattern3, "#{drive}:\\dir1\\dir2")
data.gsub!(pattern4, "http://#{ipport}/")
File.open(file, 'w') {|f| f.write(data)}
end

Ruby, Mac, Geektool question, file access rights?

I have a Ruby script that I built in TextMate and can successfully run in TextMate.
I can also successfully run this script straight from the terminal.
The script has this chunk of code in it:
# Get the XML file
puts 'Opening the file'
open("messages.xml", "r") do |f|
puts 'File is opened'
theXML = Hpricot::XML(f)
puts 'Trying to get the message_entity'
message_entity = GetMessage(theXML)
# Build the system command
puts 'Getting the author and the message'
theAuthor = message_entity.search(:author).text
theMessage = message_entity.search(:messagetext).text
# Get the correct image for this author
theAuthorImage = ''
case theAuthor
when 'James' : theAuthorImage = 'images/me32.png'
when 'Zuzu' : theAuthorImage = 'images/Zuzu32.png'
end
puts "/usr/local/bin/growlnotify '" + theAuthor + " says' -m '" + theMessage + "' -n 'Laurens Notes' --image '" + theAuthorImage + "'"
#system("/usr/local/bin/growlnotify '" + theAuthor + " says' -m '" + theMessage + "' -n 'Laurens Notes' --image '" + theAuthorImage + "'")
end
puts 'The End'
When the script is run by GeekTool, it never gets past puts 'File is opened'. It doesn't even hit puts 'The End'. It gives no error at all.
The script is under a folder under the /System folder on my Mac, but I have changed the file permissions to allow "everyone" to have "read & write" access.
EDIT
I just copied the files to a folder directly under my user home folder, and it still has the issue in GeekTool but not in TextMate or straight through the Terminal.
END EDIT
2nd Edit
I think GeekTool may have an issue with paths to files maybe.
For example, I changed the program to just read the XML file straight from the Internet for now and it does that just fine, but there are some images that the program is using for the icons in growlnotify. When run through TextMate, these icons display perfectly. When run using GeekTool...nope. No custom icon at all.
It's as if GeekTool just can't handle the file paths correctly.
When I do puts __FILE__.to_s it gives me the correct filepath to my .rb file though.
** end 2nd edit**
What should I do?
Geektool runs all the commands from / so relative path names will not work when trying to run growlnotify.
puts Dir.pwd #outputs "/"
You will need to pass the absolute paths of the images to growlnotify.
The current path can be retrieved with
File.dirname(__FILE__)
So you would use
theAuthorImage = File.dirname(__FILE__)
case theAuthor
when 'James' : theAuthorImage += '/images/me32.png'
when 'Zuzu' : theAuthorImage += '/images/Zuzu32.png'
end
cmd = "/usr/local/bin/growlnotify '#{theAuthor} says' -m '#{theMessage}' -n 'Laurens Notes' --image '#{theAuthorImage}'"
puts cmd
system cmd
Try wrapping it all in a block like below, which will log to /tmp/geektool.txt. Then you can see if there are any exceptions happening that you aren't aware of (like file permission).
begin
#file.open... etc
rescue Exception => e
file.open('/tmp/geektool.txt', 'w'){|f| f.puts "#{e}\n\n#{e.backtrace}"}
end
Also, don't forget there's the ruby-growl gem.
Have you checked if GeekTool spews any output to console.log or system.log?
Also, if it never gets past 'File is opened', it might be an issue with gems and requiring Hpricot?

Resources