Implemeting amazon Simple nodification service in RUBY - ruby

Am trying to implement amazon SNS using ruby.
I want to create a topic,delete a topic,subscribe to a topic,publish to a topic.These are included in the following code.
#!/usr/bin/env ruby
require 'rubygems'
require 'aws-sdk'
AWS.config(:access_key_id => 'BT62W53Q', :secret_access_key => '0Edwg')
#sns=AWS::SNS.new
#D requirements
alpha = #sns.topics.create('CSC470Test-Alpha')
#sns.topics.create('CSC470Test-Beta')
temp=gets
#sns.topics.each do |topic|
puts topic.name
if(topic.name=='CSC470Test-Beta')
topic.delete
end
end
puts
puts 'Beta now deleted.'
puts
#sns.topics.each do |topic|
puts topic.name
end
puts
temp=gets
puts
#C requirements
#sns.topics.each do |topic|
if(topic.name=='CSC470Test-Alpha')
subbed1=false
subbed2=false
subbed3=false
topic.subscriptions.each do |sub|
if(sub.endpoint=='sn#aine.com')
subbed1=true;
end
if(sub.endpoint=='pran#aine.com')
subbed2=true;
end
if(sub.endpoint=='http://cloud.comtor.org/csc470logger/logger')
subbed3=true;
end
end
if(!subbed1)
puts 'Subscribed sika.'
topic.subscribe('sn#aine.com')
end
if(!subbed2)
puts 'Subscribed prka'
topic.subscribe('pran#aine.com', :json => true)
end
if(!subbed3)
puts 'Subscribed comtor site.'
topic.subscribe('http://cloud.comtor.org/csc470logger/logger')
end
end
end
temp=gets
puts 'Topics with info:'
#sns.topics.each do |topic|
puts
puts 'Arn'
puts topic.arn
puts 'Owner'
puts topic.owner
puts 'Policy'
puts topic.policy
puts 'Name'
puts topic.display_name
puts 'Confirmed Subscriptions:'
puts topic.subscriptions.
select{ |s| s.arn != 'PendingConfirmation' }.
map(&:endpoint)
# if(subs.confirmation_authenticated?)
# puts 'Arn: ' + subs.arn
# puts 'Endpoint: ' + subs.endpoint
# puts 'Protocol: ' + subs.protocol
# end
end
puts
temp=gets
#sns.subscriptions.each do |subs|
puts "SubscriptionARN: #{ subs.arn} "
puts "TopicARN: #{subs.topic_arn} "
puts "Owner: #{subs.owner_id} "
puts "Delivery Policy: #{ subs.delivery_policy_json} "
end
while running this code in rails console. iam getting this error
C:/ProgramData/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/aws-sdk-1.8.5/l
ib/aws/core/client.rb:339:in `return_or_raise': The request signature we calcula
ted does not match the signature you provided. Check your AWS Secret Access Key
and signing method. Consult the service documentation for details. (AWS::SNS::Er
rors::SignatureDoesNotMatch)
from C:/ProgramData/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/aw
s-sdk-1.8.5/lib/aws/core/client.rb:440:in `client_request'
from (eval):3:in `create_topic'
from C:/ProgramData/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/aw
s-sdk-1.8.5/lib/aws/sns/topic_collection.rb:24:in `create'

Related

Declaring Ruby Methods along with a menu

I've been fooling around with Ruby lately, so i decided to write an sftp client.
require 'net/sftp'
require 'ostruct'
require 'optparse'
class Sftp
def parse(arguments)
ARGV << "-h" if ARGV.empty?
#options = OpenStruct.new
args = OptionParser.new do |args|
args.banner = "Usage: #{__FILE__} [options]"
args.on("--host HOST", String,
) do |host|
#options.host = host
end
args.on("--username USERNAME", String,
) do |username|
#options.username = username
end
args.on("--password PASSWORD", String,
) do |password|
#options.password = password
end
args.on("--port=PORT", Integer,
) do |port|
#options.port = port
end
args.on("--mkdir=MAKE DIRECTORY", String,
) do |mkdir|
#options.mkdir = mkdir
end
args.on("--rmdir=REMOVE DIRECTORY", String,
) do |rmdir|
#options.rmdir = rmdir
end
args.on("-h", "--help", "Show help and exit") do
puts args
exit
end
end
begin
args.parse!(arguments)
rescue OptionParser::MissingArgument => error
puts "[!] ".red + error.message.bold
exit
rescue OptionParser::InvalidOption => error
puts "[!] ".red + error.message.bold
exit
end
def connect
Net::SFTP.start(#options.host, #options.username, :password => #options.password, :port => #options.port) do |sftp|
sftp.mkdir(#options.mkdir)
puts "Creating Directory: #{#options.mkdir}"
sftp.rmdir(#options.rmdir)
puts "Deleting Directory: #{#options.rmdir}"
end
end
end
def run(arguments)
parse(arguments)
connect
end
end
sftp = Sftp.new
sftp.run(ARGV)
I want these two commands to be separated. For example when i pass
the argument mkdir I just want only this to run and if I want to run rmdir again I just wanna run only this command.
It has to do with methods, but I can't find a proper solution. And I'm really rusty.
Any recommendation?
A very simple approach could be to check if the required value is set before running the command, and skip the command if the value is not set.
def connect
Net::SFTP.start(#options.host, #options.username, password: #options.password, port: #options.port) do |sftp|
if #options.mkdir
sftp.mkdir(#options.mkdir)
puts "Creating Directory: #{#options.mkdir}"
end
if #options.rmdir
sftp.rmdir(#options.rmdir)
puts "Deleting Directory: #{#options.rmdir}"
end
end
end

ruby net::ssh does not print stdout data on channel.on_data

I wanted to run a remote command with ruby's net::ssh and was hoping to print the output stdout but i don't see anything printed at the below code at channel.on_data
see test code:
Net::SSH.start('testhost', "root", :timeout => 10) do |ssh|
ssh.open_channel do |channel|
channel.exec('ls') do |_, success|
unless success
puts "NOT SUCCEESS:! "
end
channel.on_data do |_, data|
puts "DATAAAAAA:! " # ======> Why am i not getting to here?? <=======
end
channel.on_extended_data do |_, _, data|
puts "EXTENDED!!!"
end
channel.on_request("exit-status") do |_, data|
puts "EXIT!!!! "
end
channel.on_close do |ch|
puts "channel is closing!"
end
end
end
end
and the output is:
channel is closing!
why don't i get into the block on_data? I want to grab the stdout.
note that i know the client code is able to ssh to the remote server because when I asked the command to be ls > ls.log I saw that ls.log on target host.
Note that opening a channel is asynchronous, so you have to wait for the channel to do anything meaningful, otherwise you are closing the connection too soon.
Try this:
Net::SSH.start('test', "root", :timeout => 10) do |ssh|
ch = ssh.open_channel do |channel|
channel.exec('ls') do |_, success|
unless success
puts "Error"
end
channel.on_data do |_, data|
puts data
end
channel.on_extended_data do |_, _, data|
puts data
end
channel.on_request("exit-status") do |_, data|
puts "Exit"
end
channel.on_close do |ch|
puts "Closing!"
end
end
end
ch.wait
end

Ruby code not executed after method call

Code is not executed (puts "hey") in the harvest method after the call to searchEmails(page). I'm probably missing something simple with Ruby because I'm just getting back into it.
def searchEmails(page_to_search)
begin
html = #agent.get(url).search('html').to_s
mail = html.scan(/['.'\w|-]*#+[a-z]+[.]+\w{2,}/).map.to_a
base = page_to_search.uri.to_s.split("//", 2).last.split("/", 2).first
mail.each{|e| #file.puts e+";"+base unless e.include? "example.com" or e.include? "email.com" or e.include? "domain.com" or e.include? "company.com" or e.length < 9 or e[0] == "#"}
end
end
def harvest(url)
begin
page = #agent.get(url)
searchEmails(page)
puts "hey"
rescue Exception
end
end
url="www.example.com"
harvest(url)
#agent.get(url) will fail with a bad url or network outage.
The problem in your code could be written as follows:
def do_something
begin
raise
puts "I will never get here!"
rescue
end
end
Since you can't get rid of the raise, you need to do something inside the rescue (most likely log it):
begin
#agent.get(url)
# ...
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,
Net::ProtocolError => e
log(e.message, e.callback)
end

Ruby: Chatterbot can't load bot data

I'm picking up ruby language and get stuck at playing with the chatterbot i have developed. Similar issue has been asked here Click here , I did what they suggested to change the rescue in order to see the full message.But it doesn't seem right, I was running basic_client.rb at rubybot directory and fred.bot is also generated at that directory . Please see the error message below: Your help very be very much appreciated.
Snailwalkers-MacBook-Pro:~ snailwalker$ cd rubybot
Snailwalkers-MacBook-Pro:rubybot snailwalker$ ruby basic_client.rb
/Users/snailwalker/rubybot/bot.rb:12:in `rescue in initialize': Can't load bot data because: No such file or directory - bot_data (RuntimeError)
from /Users/snailwalker/rubybot/bot.rb:9:in `initialize'
from basic_client.rb:3:in `new'
from basic_client.rb:3:in `<main>'
basic_client.rb
require_relative 'bot.rb'
bot = Bot.new(:name => 'Fred', :data_file => 'fred.bot')
puts bot.greeting
while input = gets and input.chomp != 'end'
puts '>> ' + bot.response_to(input)
end
puts bot.farewell
bot.rb:
require 'yaml'
require './wordplay'
class Bot
attr_reader :name
def initialize(options)
#name = options[:name] || "Unnamed Bot"
begin
#data = YAML.load(File.read('bot_data'))
rescue => e
raise "Can't load bot data because: #{e}"
end
end
def greeting
random_response :greeting
end
def farewell
random_response :farewell
end
def response_to(input)
prepared_input = preprocess(input).downcase
sentence = best_sentence(prepared_input)
reversed_sentence = WordPlay.switch_pronouns(sentence)
responses = possible_responses(sentence)
responses[rand(responses.length)]
end
private
def possible_responses(sentence)
responses = []
#data[:responses].keys.each do |pattern|
next unless pattern.is_a?(String)
if sentence.match('\b' + pattern.gsub(/\*/, '') + '\b')
if pattern.include?('*')
responses << #data[:responses][pattern].collect do |phrase|
matching_section = sentence.sub(/^.*#{pattern}\s+/, '')
phrase.sub('*', WordPlay.switch_pronouns(matching_section))
end
else
responses << #data[:responses][pattern]
end
end
end
responses << #data[:responses][:default] if responses.empty?
responses.flatten
end
def preprocess(input)
perform_substitutions input
end
def perform_substitutions(input)
#data[:presubs].each {|s| input.gsub!(s[0], s[1])}
input
end
# select best_sentence by looking at longest sentence
def best_sentence(input)
hot_words = #data[:responses].keys.select do |k|
k.class == String && k =~ /^\w+$/
end
WordPlay.best_sentence(input.sentences, hot_words)
end
def random_response(key)
random_index = rand(#data[:responses][key].length)
#data[:responses][key][random_index].gsub(/\[name\]/, #name)
end
end
I'm assuming that you are trying to load the :data_file passed into Bot.new, but right now you are statically loading a bot_data file everytime. You never mentioned about bot_data in the question. So if I'm right it should be like this :
#data = YAML.load(File.read(options[:data_file]))
Instead of :
#data = YAML.load(File.read('bot_data'))

can i read the deleted statuses on twitter with ruby?

I would like to read the deleted statuses on twitter since i can already have the user_id and status_id of the deleted tatus using "on_delete" method.
here is my code:
require 'rubygems'
require 'tweetstream'
TweetStream::Client.new(USER,PASS).follow(3331681,15846407,30592818,21249843,1367531,428333, 196218494,82158673, :delete => Proc.new{ |status_id, user_id| puts "#{status_id}, #{user_id}"}) do |status|
#is it a retweet
rt=!defined?(status.method_missing("retweeted_status",status.id).class).nil?
puts "retweet?:"
puts rt.inspect
if status.in_reply_to_screen_name.nil?
if rt
puts "Retweeted by :#{status.user.screen_name}"
else
puts "Screen name :#{status.user.screen_name}"
end
else
puts "From :#{status.user.screen_name} to #{status.in_reply_to_screen_name}"
end
puts "Text:#{status.text}"
puts "#{status.created_at}"
puts '*' * 7
puts "user id:#{status.user.id}"
puts "to :#{status.in_reply_to_user_id}"
puts '--' * 25
end
No, you can't. This is a constraint of the Twitter API rather than any Ruby library. It used to be possible but has since been fixed, breaking tweet recovery services such as tweleted.com in the process.

Resources