How can I route SMSes using Twilio, based on a schedule? - sms

I send SMS alerts to my mobile phone using Twilio; I would like to route this to a different number based on a schedule / rota? ie I am in the US, so during my day I would like to get alerts, and then during the UK's day I would like someone else?
Any ideas?
Thanks

You can just configure the sending address based on the current date and time. In Python this would look something like this:
from datetime import datetime
curr_time = datetime.utcnow()
# roughly, London working hours
if 8 < curr_time.hour <= 17:
recipient = "+44XXXXXXXXXXX"
else:
recipient = "+1XXXXXXXXXXXX"
send_sms_message(from=twilio_number, to=recipient, body=body)
Without knowing more about how you are sending the messages, or how you are generating alerts, it's difficult to provide a more nuanced answer.

Related

Is there a place to get more granular reporting data via API?

I'm trying to figure out a way to export some of the events I can see in the security dashboard and alert center. The Customer Reports API only gives me the # of mail received per day, and # or spam messages per day, but is more than 24 hrs behind.
I've tried to create an alert in the security alerts center for whenever my domain gets a relevant email, but I just get an email once a minute that says the the threshold was exceeded, and I have to click into the investigation tool to actually get the relevant data.
Is there a place I can request # of phishing emails per hour, or be alerted whenever new phishing emails are found. Or Malware, etc.
The Reports API method UserUsageReport: get allows you to retrieve received spam emails for a certain date by specifying the parameter gmail:num_spam_emails_received
However, if you want to retrieve e.g. the emails from the last hour, there is no prebuilt functionality for this.
You can write a Google Apps Script that would browse your Gmail Inbox for new Spam Emails and set the script on a time-driven trigger
Sample:
function setmeOnHourlyTimer() {
var now = new Date();
var oneHourAgoinSeconds = Math.round(now.getTime()/1000 - 1200 *60);
var query = '"after:'+ oneHourAgoinSeconds +'"';
var spamMessages = Gmail.Users.Messages.list("YOU_EMAIL", {"labelIds": ["SPAM"] , "q": query}).messages;
if (spamMessages.length > 0){
GmailApp.sendEmail("paste your email here", "You have new Spam emails", "You got " + spamMessages.length + " new spam message(s) within the last hour.")
}
}

How to get all message history from Hipchat for a room via the API?

I was using the Hipchat API (v2) a bit today and ran into an odd issue where I was not able to really pull up all of the history for a room. It seemed as though when I queried a specific date, for example, it would only retrieve a fraction of the history for that date given. I had had plans to simply iterate across all of the dates for a Room to extract the history in a format that I could use, but ended up hitting this and am now unsure if it is really possible to pull out the history fully.
I realize that this is a bit clunky. It is pulling the JSON as a string and then I have to form it into a hash so I know I'm not doing this as good as it could be done, but here is roughly what I quickly did just to test out the history method for the API:
api_token = "MY_TOKEN"
client = HipChat::Client.new(api_token, :api_version => 'v2')
history = client['ROOM_NAME'].history
history = JSON.parse(history)
history.each do |key, history|
if history.is_a? Array
history.each do |message|
if message.is_a? Hash
puts "#{message['from']['name']}: #{message['message']}"
end
end
end
end
Obviously then the extension to that was to just curse through the dates in the desired range (using: client['ROOM_NAME'].history(:date => '2010-11-19', :timezone => 'PST')), but again, I was only getting a fraction of the history for the room. Are there some additional parameters that I'm missing for this to make it work as expected?
I got this working but it was a big pain.
Start by sending a query with the current time, in UTC, but without including the time zone, as the start date:
https://internal-hipchat-server/v2/room/2/history?reverse=false&date=2015-06-25T20:42:18.658439&max-results=1000&auth_token=XXX
This is very fiddly:
If you specify just the current date, without a timezone, as documented in the API, it is interpreted as midnight last night and you only get messages from yesterday or older.
If you try specifying tomorrow’s date instead, the response is 400 Bad Request This day has not yet come to pass.
If you specify the time as 2015-06-25T20:42:18.658439+00:00, which is the format that times come in HipChat API responses, HipChat’s parser seems to fail and interpret it as midnight last night.
When you get the response back, take the oldest items.date property, strip the timezone, and resubmit the above URL with an updated date parameter:
https://internal-hipchat-server/v2/room/2/history?reverse=false&date=2015-06-17T19:56:34.533182&max-results=1000&auth_token=XXX
Be sure to include the microseconds, in case a notification posted multiple messages to the same room in the same second.
This will get you the next page of messages. Keep doing this until you get fewer than max-results messages back.
There is a start-index parameter I tried passing before I got the above working, and it will give you a few pages of results, with responses lacking a links.next property, but it won’t give you the full history. On a chatroom with 9166 messages in the history according to statistics.messages_sent, it only returned 3217 messages. So don’t use it. You can use statistics.messages_sent as a sanity check for whether you get all messages.
Oh yeah, and the last_active property in the /v2/room call cannot be trusted because it doesn’t update when notification messages are posted to the room.

HBASE schema design for instant message

We have been implementing an instant message service and want to use HBEASE to store message history (and using redis to caching ongoing conversation). The incoming message for a user looks like
Userid (to whom)
time
message body (combined with from, message body ....)
Regarding Schema design:
Option A: one message per row
Row key: md5(userid) + timesample
column/valye: null / message
Option B: one user per row
Row key: md5(userid)
column/valye: time / message
could you help me to figure out pro and cont? thanks
chatting type include: peer-2-peer, group chating
As far as I know Facebook has done a great job on message system use hbase; Maybe these links will help you:http://www.slideshare.net/brizzzdotcom/facebook-messages-hbase
http://sites.computer.org/debull/A12june/facebook.pdf

Does Outlook correctly handle time zones for .ics (ICalendar) files?

I have a program that sends calendar appointments out to users. However these users are in many different time zones. When I create the .ics file, I set the time zone to the local time zone, because they are scheduled here. They then get sent out to the users, who are scattered across many time zones.
Will outlook handle this correctly? As in: if I schedule a person for an 8am meeting and I am in Philadelphia, it should come up as 8am meeting for them in any other time zone.
I know that Outlook works with time zones to an extent, but I couldn't find any good documentation on it.
EDIT:
I really should have asked something more along the lines of how do you format it to handle this correctly, here is the format I am currently using. But I have little experience with this so I might be doing it wrong:
String[] iCalArr = { "BEGIN:VCALENDAR",
"PRODID:-//foobar//morefoobar//EN",
"VERSION:2.0",
"CALSCALE:GREGORIAN",
"METHOD:REQUEST",
"BEGIN:VTIMEZONE",
"TZID:America/New_York",
"X-LIC-LOCATION:America/New_York",
"BEGIN:DAYLIGHT",
"TZOFFSETFROM:-0500",
"TZOFFSETTO:-0400",
"TZNAME:EDT",
"DTSTART:19700308T020000",
"RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU",
"END:DAYLIGHT",
"BEGIN:STANDARD",
"TZOFFSETFROM:-0400",
"TZOFFSETTO:-0500",
"TZNAME:EST",
"DTSTART:19701101T020000",
"RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU",
"END:STANDARD",
"END:VTIMEZONE",
"BEGIN:VEVENT",
"DTSTART;TZID=America/New_York:" + strBeginDate,
"DTEND;TZID=America/New_York:" + strEndDate,
"DTSTAMP:" + strNow,
"UID:DT 2012 Training - " + System.Guid.NewGuid().ToString(),
"RECURRENCE-ID;TZID=America/New_York:20110207T103000",
"CREATED:" + strNow,
"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:foobar",
"LAST-MODIFIED:" + strNow,
"LOCATION:" + location,
"SEQUENCE:1",
"STATUS:TENTATIVE",
"SUMMARY:foobar",
"TRANSP:OPAQUE",
"END:VEVENT", "END:VCALENDAR" };
Outlook should handle that just fine, assuming your particular application writes out proper timezone information. Or perhpaps works in UTC and marks everything with the Z zone.
I'm confused by your remark that "testing is not an option". I can imagine the unidentified "program" being unable to write out test data, but your question indicates you worry about Outlook. Surely you can handedit some ICS files with different timezones and feed them to Outlook? This should clearly indicate that Outlook knows how to deal with them.
yes Outlook handles time zones, this article from the KB actually indicates a limitation which is that Outlook needs to be updated everytime a timezone (DST, ...) is changed:
http://support.microsoft.com/kb/931667

Web based API that can tell me if a number is a landline or cell phone? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
My application sends SMS messages to people, but the numbers entered in as their cell phone are sometimes land lines (this is user error or the user not really knowing if the contact number they have is a cell phone or landline.)
I found a few websites that can tell me if a number is a landline or cell phone, but they do not offer programatic API's. Is anyone aware of a way a web application can figure out if a number can receive SMS messages?
I guess a test SMS message is one way, but my current SMS gateway fails hard when it gets a landline number and doesn't tell me the landline number it tried to send the SMS to. I'll follow this up with my carrier, but I would love an easy way to let the user entering phone numbers in if they are a landline or cell number.
Update:
There are ways to figure this out. Take a look at http://www.phonevalidator.com, they can query a phone number and figure out if it is a landline or cell phone.
You can have JavaScript open a popup with the url:
"http://www.phonevalidator.com/results.aspx?p=" + phoneNumber
It's not a free service, but a company called Targus (not the bag company) has an API for querying phone information. They can tell if it's landline or cell, even address validation. The charge based on how many queries you do (a few cents a query).
http://www.targusinfo.com/
Followup: I contacted TARGUSinfo on Feb. 24, 2011 and was told by their sales rep that they only work with record sets in the hundreds-of-thousands to millions and generally their customers are plugged into their API for real-time access. Differentiating between cell numbers and land line numbers for smaller record sets is "not something they can assist with."
I am afraid the only real way to find it out is contact SMS gateway service providers. A list of them can be found here for example:
http://en.wikipedia.org/wiki/SMS_gateways
Anyway, instead of that I suggest doing the following:
When user inserts cell phone number into his or her profile, send testing SMS to this number with confirmation code. If number is not verified by user, don't bother sending SMS messages to it later on.
Actually there are land line operators that allow receiving SMS. Either by text2voice gateway or phone terminal with extended capability. Moreover, in Europe cell phone operators have started offering "virtual land lines", which are in fact GSM cell phones assigned to one particular base station. But they do follow land line numbering scheme.
Resuming — not allowing sending SMS to land line number is wrong.
The following script returns
646-826-3879 LANDLINE
for the Stack Overflow hot line.
#!/usr/bin/perl -w
use strict;
use warnings;
use LWP::Simple;
use LWP::Simple::Cookies ( autosave => 1, file => "$ENV{'HOME'}/lwp_cookies.dat" );
my $usage = "Usage: $0 <phone_number>\n\nwhere phone_number is on format XXX-XXX-XXXX or XXXXXXXXX";
die $usage unless scalar #ARGV == 1;
my $number = shift #ARGV;
die $usage unless $number =~ /(\d\d\d)-?(\d\d\d)/;
my $NPA = $1;
my $NXX = $2;
#GET /search.asp?frmNPA=646&frmNXX=826&frmCity=&frmState=&frmZip=&frmCounty=&frmCompany=&search.x=0&search.y=0 HTTP/1.0
my $doc = get 'http://www.area-codes.com/search.asp?frmNPA=' . $NPA . '&frmNXX=' . $NXX . '&frmCity=&frmState=&frmZip=&frmCounty=&frmCompany=&search.x=0&search.y=0';
# html format:
#...
# <td><strong>NXX Use Type:</strong></td>
# <td>LANDLINE</td>
#...
my $next = 0;
my $result = "";
grep {
if (/NXX Use Type:/) {
$next = 1;
} else {
if ($next) {
$next = 0;
$result = $_;
}
}
} split(/\n/, $doc);
$result =~ /<[^>]*>(.*)<[^>]*>/;
print "$number\t$1\n";
I'm not sure if you want to do that really... If you want to tell if a number is reserved by a callphone or landline provider, you should be able to find the ranges in some documents from your country's telco supervising entity (not sure who does that in US - it might be http://www.nanpa.com/). Those documents are usually public.
But the problem is that mobile number != able to receive sms. With number porting and all the "unified communication" ideas nowadays you can easily have local numbers redirecting to mobiles, non-geographical numbers handling smses and local "special" numbers rewriting your incoming smses as facebook messages ;) For example my local "landline" number is redirected to a mobile in another country and couple of other locations.
You shouldn't be charged for a message sent to a nonexisting / otherwise strange number, so it might be a good way to check if someone can receive them. If you have a good control over the SMS gateway, you can send a message with delivery report active and expiry == immediate message (forgot the official name). Just send a test / welcome message - if it's not accepted, you can mark the number as unavailable. Otherwise, you can just ask for a "number that accepts SMSes" instead of a "cellphone number".
Trying to combine some answers here...
Daniel mentioned that
You can have JavaScript open a popup with the url:
"http://www.phonevalidator.com/results.aspx?p=" + phoneNumber
Does this still work? I can't seem to reproduce it. If we can get that to work, then maybe we can use a script like the following...
#!/usr/bin/perl -w
use strict;
use warnings;
use LWP::Simple;
my $usage = "Usage: $0 <phone_number>\n\nwhere phone_number is on format XXX-XXX-XXXX or XXXXXXXXX";
die $usage unless scalar #ARGV == 1;
my $number = shift #ARGV;
die $usage unless $number =~ /(\d\d\d)-?(\d\d\d)/;
my $NPA = $1;
my $NXX = $2;
#GET /search.asp?frmNPA=646&frmNXX=826&frmCity=&frmState=&frmZip=&frmCounty=&frmCompany=&search.x=0&search.y=0 HTTP/1.0
my $doc = get 'http://www.phonevalidator.com/results.aspx?p=' . $NPA . $NXX;
# html format:
#...
# <td class="style16">
# Phone Line Type:
# </td>
# <td class="style13">
# <span id="PhoneTypeLabel">LANDLINE</span>
# </td>
#
#...
my $result = "";
grep {
if (/PhoneTypeLabel/) {
$result = $_;
}
} split(/\n/, $doc);
$result =~ /<[^>]*>(.*)<[^>]*>/;
print "$number\t$1\n";
Another option would be to have the user select their cellphone provider from a list. Just a thought.
Why not make a list of the usual format for the landlines and mobile numbers? For example, where I'm located landlines always follow this format:
9xxxx xxxx
and mobiles are always:
04xx xxx xxx
You can easily make a list of the general format of landline/mobile numbers in the area you are serving. Then, when wanting to find out if a US number is landline or mobile, just compare it and see whether it matches the landline format or the mobile number format.
Another thing that is done often to validate phone numbers, is to send a temporary pin via SMS to the user's mobile, and ask them to enter that pin in order to validate their number.
I can imagine doing this, if I had access to the core mobile network. That's an SS7 API, though, not a Web API. I would bet that any service which offers a Web API acts as a proxy to the SS7 network, instead of relying on databases. The only other alternative would be to query the number porability database. Eventually, to terminate a call, all network operators need to determine which other operator they need to connect to.
we have a service which provides fixed line / cellular detection for USA and Canada, and also detects if the number is Live or Dead, which wireless carrier the number is ported to etc. There's a full web API.
If you sign up for an account at www.hlrcheck.com I'll get it validated and add some free credits for you to test. We're in beta at the moment, but full release candidate is imminent.
All solutions mentioned here are static number pattern lookups but the only reliable way to figure out whether a given cell phone number is valid (and ready to receive SMS) is to perform an HLR Lookup. HLR stands for Home Location Register, which is a mobile network operator database with real time subscriber information. There are several API services for HLR lookups, e.g. www.hlr-lookups.com.

Resources