Rails 发送多条短信 [英] Rails send multiple SMS
问题描述
我有一个应用,它应该每 5 分钟向用户发送一次 SMS(值稍后会改变).
I have an app that is supposed to send an SMS to users every 5 minutes (value that will change later).
目前,我的应用正在运行,它每 5 分钟发送一次短信,但只发送给一个用户.我不知道为什么其他用户会被忽略.
At the moment, my app is working, it sends SMS every 5 minutes, but to only one user. I don't know why the other users are ignored.
我正在使用 Twilio.
I'm using Twilio.
这是我的任务:
task :sms_sender_daily => :environment do |_, args|
User.find_each do |user|
UserTexter.send_daily_sms(user).deliver_now if user.daily_sms == true && user.phone.present? (I tried with deliver_later too, same result)
end
end
这是我的 UserTexter :
Here is my UserTexter :
class UserTexter < Textris::Base
def send_daily_sms(user)
@user = user
# put your own credentials here
account_sid = 'AC25xxx'
auth_token = '059xxx'
# set up a client to talk to the Twilio REST API
@client = Twilio::REST::Client.new account_sid, auth_token
@client.account.messages.create({
:from => '+14234350632',
:to => '+' + @user.phone,
:body => 'SMS journalier',
})
end
end
我只有 3 个用户有 3 个不同的号码,但它只发送给一个.
I only have 3 users with 3 different number, but it only sends to one.
当我将 send_daily_sms 方法放入 user.rb 模型中,并对收件人"号码进行硬编码时,它会向该号码发送 3 次 SMS,因为 3 个用户将 daily_sms 设为 true.奇怪.
EDIT : When I put the send_daily_sms method in the user.rb model, and hardcode the "To" number, it sends the SMS 3 times to this number, since 3 users have daily_sms as true. Weird.
推荐答案
您在这里直接与 Twilio 客户端交互,但也使用 Textris,这有点奇怪.这是我将如何做(基于 textris 自述文件).
It's a little strange that you're interacting w/ the Twilio client directly here but also using Textris. Here is how I would do it (based on the textris readme).
# app/models/user.rb
class User < ActiveRecord::Base
scope :wanting_daily_sms,
-> { with_phone.where(daily_sms: true) }
scope :with_phone,
-> { where(arel_table[:phone].not_eq(nil)) }
end
# task
task :sms_sender_daily => :environment do |_, args|
User.wanting_daily_sms.each { |u| UserTexter.send_daily_sms(u).deliver_now }
end
# config/initializers/twilio.rb
Twilio.configure do |config|
config.account_sid = 'AC25xxx'
config.auth_token = '059xxx'
end
# Gemfile
gem 'twilio-ruby'
gem 'textris'
# UserTexter
class UserTexter < Textris::Base
default from: "Our Team <+14234350632>"
def send_daily_sms(user)
@user = user
text to: @user.phone
end
end
# app/views/user_texter/send_daily_sms.text.erb
SMS journalier
添加上面的初始化程序后,您需要确保重新启动服务器.
After adding the initializer above you'll need to be sure to restart your server.
这篇关于Rails 发送多条短信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!