Twilio WhatsApp messages are in 'queued' status - twilio

Okay so I got approval from WhatsApp and Twilio (after Facebook Business verification) to use the WhatsApp API for sending out appointment reminders to my clients. I configured the message templates and they got approved too. Check the image below:
I have written a code in Python where I pick my data from a PostgreSQL server hosted on cloud (using psycopg2) and then it sends out messages to the phone numbers fetched using a query. Here is the code:
from twilio.rest import Client
import psycopg2
import time
account_sid = 'AC54xxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'f1384yyyyyyyyyyyyyyyyyyyyyyyyyyy'
connection_string = ""
conn = psycopg2.connect(user = "xxxx",
password = "yyyyyy",
host = "zzzzzzzzzzzzzzz.zzzzzzzzzzzz",
port = "ABCD",
database = "some_db")
cur = conn.cursor()
cur.execute("""query to pick data""")
rows = cur.fetchall()
client_phone_list = []
phone_list_not_received = []
session_date_list = []
session_time_list = []
client_first_name_list = []
for row in rows:
session_date_list.append(row[0])
session_time_list.append(row[1])
client_first_name_list.append(row[2])
client_phone_list.append(row[3])
cur.close()
conn.close()
client = Client(account_sid, auth_token)
message_reminder_template = """Hello {},
This is a reminder about your session today at {}. Please be on time to utilize the full length of
the session and avoid distress :)
We look forward to taking care of you!"""
for i in range(len(client_phone_list)):
first_name = client_first_name_list[i]
appointment_time = session_time_list[i]
message_body = message_reminder_template.format(first_name, appointment_time)
print(message_body)
message = client.messages.create(body = str(message_body),
from_ = 'whatsapp:+1(mytwilionumber)',
to = 'whatsapp:+91'+client_phone_list[i])
time.sleep(10)
text_status = message.status
print(text_status)
Whenever I run this code the message status returned is always 'queued'. I have checked that I am not using the 'Test Credentials' but the 'Live Credentials'.
I have also checked the error_code and error_message which returns as NULL. So there is no error but the messages are not getting sent. How can I change that?
Any help would be hugely appreciated.
Also note that the message body used in the code above is approved as a template from WhatsApp.

Twilio developer evangelist here.
At the point that you make the API request to send the message the status will be returned to code as "queued". That's this point in your code here:
message = client.messages.create(body = str(message_body),
from_ = 'whatsapp:+1(mytwilionumber)',
to = 'whatsapp:+91'+client_phone_list[i])
What you do next will not work though:
time.sleep(10)
text_status = message.status
print(text_status)
Waiting 10 seconds and then reading the status from the message object that was returned when you created the message will still return "queued".
If you want to fetch the message status after 10 seconds to see if it has been sent then you will need to make a second call to the messages API, like so:
time.sleep(10)
latest_message = client.messages(message.sid).fetch()
print(latest_message.status)
For a more efficient method of keeping track of the status of your messages, check out this tutorial on receiving webhooks for message status updates.
Let me know if that helped at all.

Related

Rpush notification fails to deliver

I am new to Rails. I am trying to send push notification using rpush gem.
I am following these steps:
n = Rpush::Gcm::Notification.new
n.app = Rpush::Gcm::App.find_by_name("android_app")
n.registration_ids = ["#{d.device_token}"]
n.data = { title: "#{self.title}"}
n.save!
The notification gets saved but is not getting delivered, and I get the following error description:
"Unable to deliver notification 10, received error (Failed to deliver to all recipients. Errors: NotRegistered.)"
Not able to understand the issue here. Please help me.
Thanks!
When you find above mentioned message in your log, means, as said #abielita and rpush wiki documentation, the identification_id GCM is using to send notification, is no more valid.
Device with (d.device_token) as registration token, is no more registered on GCM (Firebase) Service.
This message come for a specified reason: adapt your code to this condition.
Maybe is better destroy your "d" record !?
Becomes helpful Rpush.reflect in config/initializers/rpush.rb
Uncomment event notification on.gcm_invalid_registration_id and add your code inside block
e.g.
on.gcm_invalid_registration_id do |app, error, registration_id|
Device.where(registration_id: registration_id).take.destroy
end
and encloses your sending notification code inside a conditional check
unless(d.nil?)
n = Rpush::Gcm::Notification.new
n.app = Rpush::Gcm::App.find_by_name("android_app")
n.registration_ids = ["#{d.device_token}"]
n.data = { title: "#{self.title}"}
n.save!
end
I hope it help

Getting notified in another browser when a chat message is sent in Twilio

I am sending messages in using Twilio using this code:
string channelId = <channelId>;
string serviceSid = <servicesid>;
IpMessagingClient ipMessagingClient = new IpMessagingClient(<accountid>, <token>);
var msgResult = ipMessagingClient.CreateMessage(serviceSid, channelId, "sender", "message");
msg.Body = "body"
msg.DateSent = DateTime.Now;
msg.Sender = "sender"
return Json(new
{
Success = msgResult.Sid != null,
NewMessage = msg
});
Message is sent just fine and I can retrieve the messages of the channel. What I am trying to achieve now is other open browser and in the channel gets notified of new messages sent so I can update the UI to display the new messages without manual refreshing the browser.
Twilio developer evangelist here.
It looks like you are using the REST API to send messages to the Programmable Chat API.
To get using the client versions, the JS client in particular, I would take a read through the Programmable Chat documentation, go download the JS SDK and take a look at the code for the reference chat demo. All of those bits should give you a good grounding in building chat for the client side.
Let me know if that helps at all.

Twilio IP Messaging - get the last message index on REST API

Using the twilio-ruby package to connect to the REST API for Twilio's IP Messaging service and attempting to compute an unread message count.
The REST API is paginating the messages so that something like
channel.messages.list.last.index
Will return 49 once there are more than 50 messages in the channel.
Is there a way to get just the last message on the channel (as seems to be possible in the android/ios SDK) to avoid paginating through all message history?
In regards to computing an unread message count, take a look at the Message Consumption Horizon and subtract the lastConsumedMessageIndex from the total number of messages in the list - 1.
For the messages list (in Python):
https://www.twilio.com/docs/api/ip-messaging/rest/messages#list-all-messages
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest.ip_messaging import TwilioIpMessagingClient
# Your Account Sid and Auth Token from twilio.com/user/account
account = "ACCOUNT_SID"
token = "AUTH_TOKEN"
client = TwilioIpMessagingClient(account, token)
service = client.services.get(sid="SERVICE_SID")
channel = service.channels.get(sid="CHANNEL_ID")
messages = channel.messages.list()
See also, Sending a Consumption Report (the example in JavaScript):
//determine the newest message index
var newestMessageIndex = activeChannel.messages.length ?
activeChannel.messages[activeChannel.messages.length-1].index : 0;
//check if we we need to set the consumption horizon
if (activeChannel.lastConsumedMessageIndex !== newestMessageIndex) {
activeChannel.updateLastConsumedMessageIndex(newestMessageIndex);
}

rpush notification, saves notification but not sending. Ionic receive message Notification received

Are there any documentations regarding the data field of the Push Notification message i mean n.data { }. what does it mean?
I seem to be having the same issue as well
This is my code
n = Rpush::Apns::Notification.new
n.app = Rpush::Apns::App.find_by_name("Loanstreet Partners")
n.device_token = #user_auth_token.device_token # 64-character hex string
n.alert = "New Case Submission: " + la.case_code
n.data = { foo: :bar }
n.badge = 1
n.save!
Rpush.push
Rpush.apns_feedback
In my rpush_notifications table, i see the notification created but in my rpush_feedback it is empty. not sure why it doesn't get sent. Anyone has a clue?
I don't get any error or anything as well. So I'm sort of confused.
I do however get a Notification received from Ionic log but i dont see any notification.

Twilio check if phone number has been blacklisted

I am currently integrating into the twilio rest api and need to perform a check on a users phone number to determine if that user has blacklisted themselves or not. I have little experience with this api and scouring through the documentation and google has turned up nothing.
In our application we are going to have a notification center and if the user has blacklisted themselves I do not want to give them the ability to turn on their SMS notifications. Potentially a user could have SMS notifications on but twilio would block any messages. I know there is the ability to get a status code back from twilio when an SMS is queued that shows the user is blacklisted (https://www.twilio.com/docs/api/rest/message). However, I will not be sending messages on the notifications screen and need a direct way (if at all possible) to check twilio to determine if a number is blacklisted. Any help is much appreciated. Let me know if anymore information will be of help.
Megan from Twilio.
I'd be curious to see if you ever tried your own workaround. But I wanted to note for others in a similar situation how you could grab the blacklist error and then do whatever you may want with it.
In Ruby it would look something like this:
require 'rubygems'
require 'twilio-ruby'
account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'
#client = Twilio::REST::Client.new account_sid, auth_token
begin
#message = #client.messages.create(
from: 'TWILIO_NUMBER',
to: 'USER_NUMBER',
body: 'Howdy!'
)
rescue Twilio::REST::RestError => e
if e.code == 21610
# User is blacklisted
# Store info however you choose
puts e.message
end
end
We check for blacklisting specifically using the code '21610'. For more information about errors you can visit the reference page.
Hope this helps!
Twilio recommends developers to store the opt-out/in statuses in their side. I have stored it in DB. There are 2 ways to collect the unsubscribed users list.
1) Use SMS webhooks. You can find how to configure your Twilio number to receive webhook events here
#PostMapping(value = "/twilio", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_ATOM_XML_VALUE)
public String twilioConsumer(TwilioEventDTO twilioEventDTO) {
// twilioEventDTO.getBody() => returns the body of the SMS user replied.
twilioService.consume(twilioEventDTO);
return new MessagingResponse.Builder().build().toXml();
}
2) Since I implemented webhooks later, I had to collect already unsubscribed users. When you send sms to the number that has been opted-out, Twilio API throws an exception with the status number of 21610. You can catch it and store the number in DB.
try {
Message result = Message.creator(
new PhoneNumber(toPhoneNumber),
new PhoneNumber(fromPhoneNumber),
messageBody)
.create();
response = result.getStatus().name();
} catch (ApiException e) {
if (e.getCode().equals(21610))
updateSubscription(toPhoneNumber, false);
logger.warn("Error on sending SMS: {}", e.getMessage());
}
P.S.: examples written in Java - Spring Boot framework.

Resources