Receiving RequestError when using the twilio-ruby gem - ruby

I am try to use the twilio-ruby gem, but got a Twilio::REST::RequestError. What does this mean? Here's the code I'm using:
Controller
Class UserController < ApplicationController
def new
#user = User.new
end
def createUser
#user = User.new(user_params)
if #user.save
render text: "Thank you! You will receive sms notification"
account_sid = '*****'
auth_token = '*****'
#client = Twilio::REST::Client.new account_sid, auth_token
##client = Twilio::REST::Client.new account_sid, auth_token
#client = Twilio::REST::Client.new(TWILIO_CONFIG['sid'], TWILIO_CONFIG['token'])
# Create and send an SMS message
#client.account.messages.create
({
:from => '+127*****',
:to => #user.phone,
:body => "Hello"
})
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :phone)
end
end
Why is this generating an error?

A RequestError means that we couldn't send the SMS message. It may mean you don't have international permissions to send to the number in question, or you are trying to use a Caller ID for a phone number that you don't own, or you're trying to send to a landline, or any number of problems.
Here is an example of how to catch a RequestError and view the attached error message.
require 'twilio-ruby'
begin
client = Twilio::REST::Client.new account_sid, auth_token
client.account.sms.messages.create(
from => from_number,
to => to_number,
body => "Hello World"
)
rescue Twilio::REST::RequestError => e
puts e.message
end

Related

Display content on PM::WebScreen from BubbleWrap response

class WorkoutScreen < PM::WebScreen
title "Workouts"
def content
#response
end
def on_load
set_nav_bar_button :left, title: "Menu", action: :nav_left_button
end
def load_started
#response = ''
BubbleWrap::HTTP.get("my_url", {async: false, :headers => { "User-Agent" => "value"}}) do |response|
#response = response.body.to_str
end
end
def nav_left_button
app_delegate.menu.show(:left)
end
end
I need to send HTTP request with specific header, but content always nil . I have checked response by sniffer - everything is Ok.
If I do this way
class WorkoutScreen < PM::WebScreen
title "Workouts"
def content
#response = ''
BubbleWrap::HTTP.get("my_url", {async: false, :headers => { "User-Agent" => "value"}}) do |response|
#response = response.body.to_str
end
#response
end
I see
eb_screen_module.rb:50:in `set_content:': Is a directory - read() failed (Errno::EISDIR)
exception
NSUserDefaults.standardUserDefaults.registerDefaults({UserAgent: "value"})
Found solution myself

send mail with attachment ruby

I want send mail with an attachment file. I need have then format body text in html, when configure the format, the file attachment sent bad in the mail.
My code using actionMailer:
#require 'mail'
class MyMail < ActionMailer::Base
default :from => 'cristian.gonzalez#powersystem.com.ar'
def send_mail(user,pdffile_name,pdffile_name_second,pdffile_name_thir,htmlfile_name)
#sendgrid_unique_args :key1 => user.id
email_with_name = "#{user.send_user} <#{user.mail_address}>"
#Adjuntar el archivo 1
unless pdffile_name.nil?
filename = user.first_attachment.partition("/")[2]
attachments[filename] = File.open(pdffile_name, 'rb', &:read)
end
mail :to => 'cdgonzalez82#gmail.com',
:subject = user.mail_subject,
:content_type = 'text/html; charset=UTF-8',
:email.body = user.mail_body
end
end
Any help please???

How can I use Digest and Basic authentications with HTTParty in the same class?

I have the following class performing some requests:
the first request uses a digest auth
the second request uses a basic auth
When I run the second request I have the following error:
only one authentication method, :basic_auth or :digest_auth may be used at a time
How can I invalidate the digest_auth prior to running the second request?
class Test
include HTTParty
debug_output $stdout
digest_auth 'login', 'pass'
def first_request(href)
self.class.base_uri "SERVER:PORT"
response = self.class.get(href, {:query => {}})
response
end
def second_request(href)
auth = {:username => "USERNAME", :password => "PASSWORD"}
options = { :body => xml_string, :basic_auth => auth }
response = self.class.post('', options)
response
end
end
When you use basic_auth or digest_auth, HTTParty stores the information internally in the #default_options hash. Here is the source for basic_auth:
# File 'lib/httparty.rb', line 102
def basic_auth(u, p)
default_options[:basic_auth] = {:username => u, :password => p}
end
You can get access to that hash using the default_options method:
# File 'lib/httparty.rb', line 452
def default_options #:nodoc:
#default_options
end
I'd try:
default_options.delete(:basic_auth)
or:
default_options.delete(:digest_auth)
prior to using the other authentication method.
This is untested code but looks 'bout right:
class Test
include HTTParty
debug_output $stdout
def first_request(href)
klass = self.class
klass.base_uri "SERVER:PORT"
klass.default_options.delete(:basic_auth)
klass.digest_auth 'login', 'pass'
klass.get(href, {:query => {}})
end
def second_request(href)
klass = self.class
klass.default_options.delete(:digest_auth)
klass.post(
'',
{
:body => xml_string,
:basic_auth => {
:username => "USERNAME",
:password => "PASSWORD"
}
}
)
end
end

Error on a Sinatra's middleware

In my Sinatra app, I've created the following middleware to ensure the incoming request contains the parameter "token" in the query string
class CheckMandatoryParams
def initialize(app)
#app = app
end
def call(env)
# Get token from query string
h = Hash[*env["QUERY_STRING"].split('&').map {|s| s.split('=')}.flatten]
token = h["token"]
# Do not authorize request unless both parameters are not null
if token.nil? then
Log.instance.error("CheckMandatoryParams - token not provided")
[401, {"Content-Type" => "text/plain", "Content-Length" => body.length.to_s}, ["Unauthorized"]]
else
Log.instance.debug("CheckMandatoryParams - token provided")
#app.call(env)
end
end
end
In the case the params exists, the next app is calls and everything goes fine.
In the case the params is not in the query string, the response is not sent, I receive a huge html file indicating an error at the line ' [401, {"Content-Type" => "text/plain", "Content-Length" => body.length.to_s}, ["Unauthorized"]]' but I cannot figure out what is wrong.
Any idea?
UPDATE
This is working better like that :)
body = "Unauthorized"
[401, {"Content-Type" => "text/plain", "Content-Length" => body.length.to_s}, [body]]
I did not manage to retrieve the param with the following code though:
request = Rack::Request.new(env)
token = request.params["token"]
It looks like the "body" variable may be undefined. One possible way to rewrite your code would be as follows:
class CheckMandatoryParams
def initialize(app)
#app = app
end
def call(env)
request = Rack::Request.new(env)
token = request.params["token"]
if token.nil?
[401, {"Content-Type" => "text/plain", "Content-Length" => request.body.length.to_s}, ["Unauthorized"]]
else
#app.call(env)
end
end
end

HTTParty authentication problem

I am trying to log in with HTTParty.
I followed the instruction and still can't get it to work.
require 'rubygems'
require 'httparty'
class LAShowRoom
include HTTParty
base_uri 'www.lashowroom.com'
#debug_output
def initialize email, password
#email = email
response = self.class.get('/login.php')
response = self.class.post(
'/login.php',
:body => { :login_id => email, :login_key => password, :submit_login => 'Log In' },
:headers => {'Cookie' => response.headers['Set-Cookie']}
)
#response = response
#cookie = response.request.options[:headers]['Cookie']
end
def login_response
#response
end
def welcome_page
self.class.get("/announce.php", :headers => {'Cookie' => #cookie})
end
def logged_in?
welcome_page.include? "Kevin"
end
end
la_show_room = LAShowRoom.new('my_email', 'my_password')
puts "Logged in: #{la_show_room.logged_in?}"
As far as I know, HTTParty handles https automatically.
Am I missing something?
Thanks.
Sam
Yes, HTTParty handles HTTPS automatically, but you still need to declare HTTPS. Try
base_uri 'https://…'
How else is HTTParty supposed to know? ;-)

Resources