Search code examples
ruby-on-railsrubybackgroundworkertwiliosidekiq

Why won't my Twilio SMS send in Sidekiq background worker?


I am having issues sending a text with Twilio through my SideKiq background worker. The worker is supposed to send a text and then send an email (with Mandrill). The email works fine. The text never happens.

  • I haven't had issues with other jobs (including ones that also involve use of environment variables).
  • I haven't had issues sending Twilio texts outside of a background worker.
  • I'm using Foreman to start my application.
  • In console, running UserNotifier.new.perform(1) works fine - both the email and the text are sent.

Here is some of the code in question:

This is the class that I'm using to send my SMS:

(My Gemfile includes the twilio-ruby gem)

class SendSMS
   def initialize
      @twilio_client = Twilio::REST::Client.new "#{ENV['TWILIO_SID']}", "#{ENV['TWILIO_TOKEN']}"
   end

   def send(message, user)
      @twilio_client.account.sms.messages.create(
        :from => "+1#{ENV['TWILIO_PHONE_NUMBER']}",
        :to => user.phone_number,
        :body => message
      )
   end
end

My worker looks like this:

class UserNotifier
  include Sidekiq::Worker
  sidekiq_options queue: :immediate

  def perform(user_id)
    user = User.find(user_id)
    message = "Hi #{user.name}!"
    SendSMS.new.send(message, user)
    UserMailer.send(message, user).deliver
  end
end

Can anyone see an issue with my code? Please let me know if there is anything else I should post or if there is any clarification that I could make.

My server was displaying the worker logs and it didn't seem to be running into an error.

Any suggestions on how to debug background workers would be appreciated as well.


Solution

  • Try catching REST errors from Twilio and logging some debug info. You can discover errors that might prevent messages from sending, or investigate sent messages in your Twilio account logs via their sid (Twilio's internal id). Also updated your create call to use the messages resource instead of deprecated sms/messages.

    begin
        message = @twilio_client.account.messages.create(
            :from => "+1#{ENV['TWILIO_PHONE_NUMBER']}",
            :to => user.phone_number,
            :body => message
          )
        logger.debug "sent #{message.sid}"
    rescue Twilio::REST::RequestError => e
        logger.debug "error: #{e.message}"
    end