Ruby脚本将收到的电子邮件发送为短信

时间:2016-03-17 22:01:17

标签: ruby email

我有一个简单的ruby脚本,用于将所有收到的消息作为sms消息发送。但是,出于某种原因它不会执行。

以下是示例代码;

的/ etc /别名 motor:“| /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

任何有类似脚本的人都可以帮助解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您有2个错误。

第一个错误是已经在Ruby中定义了send。请参阅此SO帖子What does send() do in Ruby?

请参阅此代码

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

$ ./send.rb 
method
Object

第二个错误是你在定义之前调用方法。请参阅此示例代码(在welcome之前调用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)

将方法名称从发送更改为其他名称,例如send_sms,并在调用方法之前放置定义

所以这应该是这样的:

#!/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

并且还可以向脚本添加日志记录,以便在运行和提取时向您提供有关内部情况的信息。所以你可以轻松调试beaviour。记录是DEBUG的简易方法。