Ruby script sends received email as sms

I have a simple ruby ​​script designed to send all received messages as sms messages. However, for some reason, it fails for some reason.

Here's some sample code;

/ etc / motor aliases : "| /home/motorcare/sms_script.rb"

sms_script.rb

#!/usr/bin/env ruby
require "json"
require "httparty"
require 'net/http'
require 'uri'
require "cgi"
require "mail"
# Reading files
mail = Mail.read(ARGV[0])
destination = mail.subject
message = mail.body.decoded
#first_line = lines[0].strip
if destination =~ /^(256)/
   send(destination, message)
else
   destination = "256#{destination.gsub(/^0+/,"")}"
   send(destination, message)
end

# Sending message
def send(destination, message)
  url = "http://xxxxxxxxxx.com/messages?token=c19ae2574be1875f0fa09df13b0dde0b&to=#{phone_number}&from=xxxxxx&message=#{CGI.escape(message)}"
  5.times do |i|
    response = HTTParty.get(url)
    body = JSON.parse(response.body)
    if body["status"] == "Success"
      break
    end
  end
end

      

Anyone with a similar script to help with this?

0


a source to share


1 answer


You have 2 errors.

The first mistake is something that is send

already defined in Ruby. See this SO post What does send () do in Ruby?

see this code

$ cat send.rb 
#!/usr/bin/env ruby
puts defined? send
puts send :class

$ ./send.rb 
method
Object

      

The second mistake is that you are calling the method before you define it. See this code example (call welcome

before def welcome

)



$ cat welcome.rb 
#!/usr/bin/env ruby
welcome('hello from welcome')
def welcome(msg)
        puts msg
end

$ ./welcome.rb 
./welcome.rb:3:in `<main>': undefined method `welcome' for main:Object (NoMethodError)

      

Change the name of the method on dispatch to something else, e.g. send_sms, and put the definition before the method call

So it should look like this:

#!/usr/bin/env ruby
require "json"
require "httparty"
require 'net/http'
require 'uri'
require "cgi"
require "mail"


# Sending message
def send_sms(destination, message)
  url = "http://xxxxxxxxxx.com/messages?token=c19ae2574be1875f0fa09df13b0dde0b&to=#{phone_number}&from=xxxxxx&message=#{CGI.escape(message)}"
  5.times do |i|
    response = HTTParty.get(url)
    body = JSON.parse(response.body)
    if body["status"] == "Success"
      break
    end
  end
end

# Reading files
mail = Mail.read(ARGV[0])
destination = mail.subject
message = mail.body.decoded
#first_line = lines[0].strip
if destination =~ /^(256)/
   send_sms(destination, message)
else
   destination = "256#{destination.gsub(/^0+/,"")}"
   send_sms(destination, message)
end

      

And also adding a log to the script will give you information about what is going on internally when it is started and unloaded. This way you can debug beaviour easily. Registration is an easy approach to DEBUG.

+1


a source







All Articles