How to Receive Replies for Twilio SMS - sms

I've successfully configured Twilio on console as well as in my Salesoforce web application to send SMS to a given(authorized) mobile number. However I'm unable to find the proper way to find
How my clients can reply to the SMSs they receive
How I can retrieve their replies via API to my web application
I felt something called TwiML is related to this but not much clear the process. Can some body guide if you have done some similar implementation?

You can find the answer for how your human clients/customers/users can reply here:
https://www.twilio.com/docs/sms/quickstart/python#install-flask-and-set-up-your-development-environment
Rather than "client", I will use the word "user" to mean client / customer / user / human.
Let me explain what these instructions tell you by example:
The instructions will tell you how to make a bot that can send a human user a text such as "Hi, How Are You?". Then the user can respond with e.g. "I need an espresso.".
Then the bot will detect that that user has sent a response and can reply with a canned answer such as "Oh, okay.".
The instructions are pretty involved, impossible to summarize here, and fairly well written (I just followed them successfully).
However, those instructions are not clear on how to make the bot actually process what the user says, for example respond conditionally based on whether the user says 'yes' or 'no'.
If you want to actually process the contents of the user's message (exemplified as detecting whether they replied 'yes', 'no', or something else, then you can take the run.py they have at the end of their tutorial and modify is like so:
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import sys
app = Flask(__name__)
#app.route("/sms", methods=['GET', 'POST'])
def sms_ahoy_reply():
"""Respond to incoming messages with a friendly SMS."""
# Start our response
resp = MessagingResponse()
message_body = request.form['Body']
message_body = message_body.strip()
if message_body == "yes":
resp.message("You said yes.")
elif message_body == "no":
resp.message("You said no.")
else:
resp.message("You said neither yes nor no.")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)

Related

How do I make my discord.py bot count the amount of messages sent by a certain person?

I am trying to make a Discord bot that is similar to mee6 in the sense that it counts the messages sent by a user in my Discord server at certain intervals. I have scoured the web and can't find what I'm looking for even though there are similar questions. For example, I was able to find some code that counts the number of messages sent in one specific channel. I was also able to find something that I am basically looking for, which is total messages sent in a guild, but it was written in Java. I hope this narrows my question, and thank you in advance.
You can store the author and the message count in a Dictionary like this:
messageCount = {}
#client.event
async def on_message(ctx):
author = str(ctx.author)
if author in messageCount:
messageCount[author] += 1
else:
messageCount[author] = 1
await client.process_commands(ctx)
So, the dictionary would look something like this:
messageCount = {
'user#1532': 52,
'user#0864': 742,
'user#0067': 662,
...
}
Note: Once the bot goes offline, all the data will be erased, so i'll be a lot safer to store this data in an external file or a database. I'm hoping this answer will give you a gist on how to get started.

Return initial data on subscribe event in django graphene subscriptions

I'm trying to response to user on subscribe. By example, in a chatroom when an user connect to subscription, the subscription responses him with data (like a welcome message), but only to same user who just connect (no broadcast).
How can I do that? :(
Update: We resolve to use channels. DjangoChannelsGraphqlWs does not allow direct back messages.
Take a look at this DjangoChannelsGraphQL example. Link points to the part which is there to avoid "user self-notifications" (avoid user being notified about his own actions). You can use the same trick to send notification only to the user who made the action, e.g. who just subscribed.
Modified publish handler could look like the following:
def publish(self, info, chatroom=None):
new_msg_chatroom = self["chatroom"]
new_msg_text = self["text"]
new_msg_sender = self["sender"]
new_msg_is_greetings = self["is_greetings"]
# Send greetings message only to the user who caused it.
if new_msg_is_greetings:
if (
not info.context.user.is_authenticated
or new_msg_sender != info.context.user.username
):
return OnNewChatMessage.SKIP
return OnNewChatMessage(
chatroom=chatroom, text=new_msg_text, sender=new_msg_sender
)
I did not test the code above, so there could be issues, but I think it illustrates the idea quite well.

How Can I Use xmpp4r To Detect The Online/Offline Status Of A Given Jabber ID?

What is the proper xmpp4r way to know if a given contact is online before sending them a message?
Can you post sample xmpp4r code for doing this?
Here is my use case:
If contact online, send :normal message
Else, email contact
Here are things I have working code for:
Send messages of various types
Get a roster/contact list
Register a call back to detect changes in presence
However, I can't find a place that directly addresses a work flow like this:
Loop through each JID in your roster
If jid.is_online? == true, send IM
Else, send email
I've read that you should send a JID a message of type :headline and if that fails, you know the user is offline. In my tests, if the user is ONLINE, they'll receive a message of type headline. This is suboptimal, as users should only receive messages to read, not noise to determine online status.
I've read that on sign on, all of your contacts will bounce a presence status back at you, and that status is the sole indication that they are online - assuming that there isn't a disconnect or presence change you've yet to receive. So you should register a presence call back, record the initial users who ping you back, and then add or remove from the list based on your running roster presence callback.
If this is truly the way to do it:
Can I get some example code of how to collect all the "I'm here" presence confirmations on sign on via xmpp4r?
Why, oh why, was xmpp designed this way and why is this better than offering an "is_online_and_available" method?
So the answer here is adding a message call back and checking inside the block for the type:
m = Message.new(to, body)
cl.send(m)
cl.add_message_callback do |m|
if m.type == :error
puts "type: #{m.type}"
else
puts "not an error"
end
end
This requires threading as you have to be listening for the response.

PubSubHubbub and Ruby on Rails: subscription verification

I am trying to implement Superfeedr subscriptions using PubSubHubbub and Ruby on Rails. The problem is, the subscriptions are never confirmed, even though my callback prints out the hub.challenge string, which it successfully receives.
def push
feed = Feed.find(params[:id])
if feed.present?
if params['hub.mode'].present? and params['hub.verify_token'] == feed.secret
feed.update_attribute(:is_active, (params['hub.mode'] == 'subscribe'))
render text: params['hub.challenge']
return
elsif params['hub.secret'] == feed.secret
parse(feed, request.raw_post)
end
end
render nothing: true
end
It sets feed.is_active = true, but Superfeedr Analytics shows no sign of subscription.
I am using 1 dyno Heroku hosting and async verification method.
The first thing you should check is the HTTP status code and the response BODY of your subscription request. I expect the code to be 422 to indicate that subscription was failed, but the body will help us know exactly what is going on.
Also, do you see the verification request in the logs?
A common issue with heroku is that if you use hub.verify=sync, you will need 2 dynos, because you have to concurrent requests in this case...

Using the xmpp4r Ruby gem, how can I synchronously discover if a contact is online?

I'm new to XMPP and the xmpp4r library, so please forgive my noob question if this is obviously documented somewhere.
What's the most straightforward way, in a synchronous manner, to find out if a given JID is online? (so that I can call something like is_online?(jid) in an if statement)
My details:
I'm writing a Sinatra app that will attempt to send a message to a user when a particular url gets requested on the web server, but it should only try to send the message to the user if that user is currently online. Figuring out if a given JID is online is my problem.
Now, I know that if I connect and wait a few seconds for all the initial presence probe responses to come back to the Roster helper, then I can inspect any of those presences from my Roster and call #online? on them to get the correct value. But, I don't know when all of the presence updates have been sent, so there's a race condition there and sometimes calling #online? on a presence from my roster will return false if I just haven't received that presence probe response yet.
So, my current thinking is that the most straightforward way to find out if someone is online is to construct a new Presence message of type :probe and send that out to the JID that I'm interested in. Here's how I'm doing it right now:
#jabber is the result of Client::new
#email is the jid I'm interested in polling
def is_online?(jabber, email)
online = false
p = Presence.new
p.set_to(email)
p.set_from(jabber.jid)
p.set_type(:probe)
pres = jabber.send(p) do |returned_presence|
online = returned_presence.nil?
end
return online
end
Now, this works in cases where the user is actually online, but when the user is offline, it looks like the presence probe message that comes back is being caught by some other presence_callback handler that doesn't know what to do with it, and my is_online? function never finishes returning a value.
Can anyone help me by providing a simple example is_online? function that I can call, or point me in the right direction for how I can detect when the roster is done getting all the initial presence updates before I try checking a presence for #online?
As it turns out, there's not a synchronous way to ask for a JID presence. You've just got to ask for what you want, then wait for your response handler to fire when the response arrives.

Resources