Grails & SMS plugin [closed] - grails

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
Is there any recommendation for SMS plugin which can be easily integrated with Grails?
I'm building a management system which sends customers Y/N confirmation via text message.

The cost and deliverance quality of SMS services depends on which countries you will be sending SMS to, but (prior to changing to a Swedish vendor) we have used the international vendor Clickatell with ok results.
You don't need a Grails plugin for that, just use HTTPBuilder (e.g. by including the Grails REST plugin) with Grails to call the Clickatell API according to their documentation.
Here is some old sample code (may not be working if the API has changed):
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.EncoderRegistry
import static groovyx.net.http.Method.POST
import static groovyx.net.http.ContentType.URLENC
import static groovyx.net.http.ContentType.TEXT
def http = new HTTPBuilder(host)
http.contentType = TEXT
EncoderRegistry encoders = new EncoderRegistry();
encoders.setCharset('ISO-8859-1')
http.setEncoderRegistry(encoders)
http.request(POST) {
uri.path = 'http/sendmsg'
requestContentType = URLENC
body = [api_id: '1234567', user: 'john', password: 'doe', from: 'Company', to: NUMBER, text: 'Hello world', concat: '3', callback: '2', deliv_ack: '1']
response.success = { resp, reader ->
def msg = reader.text
if (msg.substring(0, 2) == 'ID') {
} else if (msg.substring(0, 3) == 'ERR') {
} else {
}
}
response.failure = { resp ->
}
}

Related

Is there a way to use firebase authentication(mainly using mobile number) with Ruby on Rails? [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 2 years ago.
Improve this question
If yes, can you point me to some resources on how to accomplish this task? Or share your expertise on this topic?
1 Get your Firebase Api key
2 Check your JWT
def firebase_verification(token)
url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=#{ENV['FIREBASE_API_KEY']}"
firebase_verification_call = HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: { 'idToken' => token }.to_json )
if firebase_verification_call.response.code == "200"
firebase_infos = firebase_verification_call.parsed_response
else
raise CustomError
end
end
3 Create the user
def firebase_login(token)
firebase_infos = firebase_verification(token)
raise CustomError if uid != firebase_infos['users'][0]['localId']
user = find_by(digits_id: firebase_infos['users'][0]['localId'])
if user.nil?
user = new
user.email = ''
user.password = Devise.friendly_token
user.digits_id = firebase_infos['users'][0]['localId']
user.digits_created_at = firebase_infos['users'][0]['createdAt']
end
user.phone_number = firebase_infos['users'][0]['phoneNumber']
user.access_token = token
user.save
user
end
for more details check this out
I believe that you can. Basically you are going to use firebase auth for authentication and your ruby app will get the authentication token and check if it is valid. I am not sure if there is an active ruby library to install for firebase (its always easier with a good lib) but you can use Firebase rest api to check for the token.

ServiceNow integration with slack [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 8 months ago.
Improve this question
I need to integrate servicenow with slack which helps to send high and critical P1 alerts to a slack channel.
I am looking for possibilities that can be done to get the serviceNow integrated with slack.
Please suggest.
You should create a Business Rule in ServiceNow on insert/update.
Condition:
Priority = 1 or Priority ChangesTo 1
Advanced/Script:
var request = new sn_ws.RESTMessageV2('SLACK_EndpointURL', 'POST');
request.setRequestHeader("Accept","application/json");
request.setRequestHeader('Content-Type','application/json');
//OR METHOD # request.setEndpoint('SLACK_EndpointURL');
// Your message
var reqBody = '{\"text\":\"This is a line of text.\nAnd this is another one.\"}';
request.setRequestBody(reqBody);
var response = request.execute();
var responseBody = response.getBody();
//See response in System Logs # gs.log(responseBody);
There are multiple ways to integrate ServiceNow and Slack. But a simple and straight-forward approach for your case would be to create an Incoming WebHook in Slack which provides a URL and all you need to do from your ServiceNow instance is to post JSON to that URL.
You can find more details about creating and customizing Slack webhooks here: https://api.slack.com/incoming-webhooks
You could use a BR to trigger with the desired conditions. This function posts our messages to Slack. The endpoint is the inbound webhook address created in Slack:
function postMessage(inPayload, inEndpoint, inTimeout) {
var sResponseBody = '', nResponseCode = 0, sResponseMessage = '', sResponseEndpoint = '', sResponseHeaders = [];
var rest = new sn_ws.RESTMessageV2();
rest.setEndpoint(inEndpoint);
rest.setHttpTimeout(inTimeout);
rest.waitForResponse(inTimeout);
rest.setRequestHeader('Content-Type', 'application/json');
rest.setRequestHeader('Accept', 'application/json');
rest.setHttpMethod('post');
rest.setRequestBody(inPayload);
for ( var i = 0; i < 3; i++ ) {
try {
var response = rest.execute();
sResponseBody = response.getBody();
nResponseCode = response.getStatusCode();
sResponseEndpoint = response.getEndpoint();
sResponseHeaders = response.getRequestHeaders();
break;
} catch( err ) {
sResponseMessage = err.getMessage();
gs.sleep(5000);
}
}
return {"ResponseCode":nResponseCode,"ResponseBody":sResponseBody,"ResponseMessage":sResponseBody,"ResponseEndpoint":sResponseEndpoint, "ResponseHeaders":sResponseHeaders};
}
This will tell you how to create an inbound webhook:
https://api.slack.com/incoming-webhooks
Here's an example payload we use. The ${tags} are simple macros we use to get value from the source ticket. You can simply dotwalk in the BR.
{
"username":"${SlackUsername}",
"attachments":[{
"title":"Short description",
"title_link":"${URL}",
"text":"${ShortDescription}",
"fallback":"${ShortDescription}",
"color":"${Color}",
"footer":"${SlackUsername}",
"fields":[
{"title":"State","value":"${State}","short":true},
{"title":"Priority","value":"${Priority}","short":true},
{"title":"Assignment group","value":"${AssignmentGroup}","short":true},
{"title":"Assigned to","value":"${AssignedTo}","short":true},
{"title":"Technical Service","value":"${TechnicalService}","short":true},
{"title":"Configuration item","value":"${ConfigurationItem}","short":true},
{"title":"Details","value":"${Description}","short":false}
],
"ts":"${TimeStampEpoch}"
}
]
}
For info:
We use a custom table with conditions set to trigger a post to Slack. Users can simply create their own filters as required. The endpoint used is an inbound webhook provided by the user.
An async business rule runs on task to review conditions and action as required.
The current work on this is to use a Slack app so we can post to any channel by channel id. This means we don't risk the issue of someone creating an inbound webhook then leaving the company.

Ruby - hashes, symbols and strings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have gem that returns next hash object
{:response=>"There was an error authenticating the sender account.", :status_code=>401}
and in my rake task i'm trying to access it's properties:
response = my_gem.execute
puts response
puts response.has_key?(:respose)
puts response[:respose]
But i can't understand why it prints
{:response=>"There was an error authenticating the sender account.", :status_code=>401}
false
Why can't i access :response property with response[:respose] ?
P.S. response[response.keys.first] works but it's very weird solution
There is a typo in the below :
puts response.has_key?(:respose)
has_key?(:respose) should be has_key?(:response).
response = {:response=>"There was an error authenticating the sender account.", :status_code=>401}
response.has_key?(:response)
# => true

How to get Yahoo's woeid by location? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
// Get woeid by lati/long
HttpGet hg = new HttpGet(
"http://where.yahooapis.com/geocode?location=" + latlon + "&flags=J&gflags=R)");
HttpClient hc = new DefaultHttpClient();
HttpResponse weatherHR = hc.execute(hg);
if (weatherHR.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
if (DEBUG)
Utils.log("", "Location != HttpStatus.SC_OK");
return null;
}
I used this API and it work ok before, but It return a error since today, the HttpStatus.SC_OK is not OK. Has this API been closed? Thanks.
Yahoo has moved to paid service called BOSS but they do offer a non-commercial service:
Non-Commercial usage of Yahoo Geo API's
Yahoo! continues to fully support developer applications built on top of Placefinder and PlaceSpotter in non-commercial settings. Both services are available to you via YQL and rate limited to 2000 queries per table. Learn more about using the Placefinder and Placespotter YQL tables.
Using Placefinder you can reverse lookup a latitude and longitude:
http://developer.yahoo.com/yql/console/?q=select%20*%20from%20geo.placefinder%20where%20text%3D%2237.416275%2C-122.025092%22%20and%20gflags%3D%22R%22
which can be converted into a json request:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D%2237.416275%2C-122.025092%22%20and%20gflags%3D%22R%22&format=json
Yes, it's closed, give a look here:
http://soup.metwit.com/post/47181933854/an-alternative-to-yahoo-weather-api
A city can also be used as location as follows:
select *
from weather.forecast
where woeid in (
select woeid
from geo.places(1)
where text="frankfurt"
) and u="c"
Where "frankfurt" can be replaced with any location of choice.
To get the Yahoo Weather WOEID by latitude and longitude, you can use this
https://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.places%20where%20text%3D%22(20,34)%22%20limit%201&diagnostics=false&format=json
And you will receive a response like the following:
{
"query":{
"count":1,
"created":"2017-03-17T20:34:50Z",
"lang":"es-AR",
"results":{
"place":{
"woeid":"1435509"
}
}
}
}
If still someone need answear. You have basic URL:
https://query.yahooapis.com/v1/public/yql?q=
Now you have to make correct YQL statement (replace city with your city name) e.x.
select * from geo.places where text="city"
Now you have to encode to URI. You can use javascript method: encodeURIComponent().
Then you have to merge basicURL and encoded YQL statement and
&format=json
So example of the whole link for San Francisco will be:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22san%20francisco%2C%20ca%22&format=json
Now from response you have to get WOEID number. You can get it by:
query>results>place>[0]>woeid
So in Javascript it will be something like:
const woeidNumber = responseObject['query']['results']['place'][0]['woeid'];

Find where a t.co link goes to [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Given a "t.co" link, how can I find out what the link resolves to? For example, if I have "t.co/foo", I want a function or process that returns "domain.com/bar".
I would stay away from external APIs over which you have no control. That will simply introduce a dependency into your application that is a potential point of failure, and could cost you money to use.
CURL can do this quite nicely. Here's how I did it in PHP:
function unshorten_url($url) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => TRUE, // the magic sauce
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYHOST => FALSE, // suppress certain SSL errors
CURLOPT_SSL_VERIFYPEER => FALSE,
));
curl_exec($ch);
return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
}
I'm sure this could be adapted to other languages or even scripted with the curl command on UNIXy systems.
http://jonathonhill.net/2012-05-18/unshorten-urls-with-php-and-curl/
If you want to do it from the command line, curl's verbose option comes to the rescue:
curl -v <url>
gives you the HTTP reply. For t.co it seems to give you an HTTP/301 reply (permanently moved). Then, there's a Location field, which points to the URL behind the shortened one.
curl -s -o /dev/null --head -w "%{url_effective}\n" -L "https://t.co/6e7LFNBv"
--head or -I only downloads HTTP headers
-w or --write-out prints the specified string after the output
-L or --location follows location headers
Here is a Python solution.
import urllib2
class HeadRequest(urllib2.Request):
def get_method(self): return "HEAD"
def get_real(url):
res = urllib2.urlopen(HeadRequest(url))
return res.geturl()
Tested with an actual twitter t.co link:
url = "http://t.co/yla4TZys"
expanded = get_real(url)
expanded = http://twitter.com/shanselman/status/276958062156320768/photo/1
Wrap it up with a try-except and you are good to go.
Another Python solution, this time relying on the requests module instead of urllib2 (and all the rest of those libraries):
#!/usr/bin/env python
import requests
shorturl = raw_input("Enter the shortened URL in its entirety: ")
r = requests.get(shorturl)
print("""
The shortened URL forwards to:
%s
""" % r.url)
Here is an R solution, ported from other answers in this thread, and from example() code of the RCurl Package:
unshorten_url <- function(uri){
require(RCurl)
if(RCurl::url.exists(uri)){
# listCurlOptions()
opts <- list(
followlocation = TRUE, # resolve redirects
ssl.verifyhost = FALSE, # suppress certain SSL errors
ssl.verifypeer = FALSE,
nobody = TRUE, # perform HEAD request
verbose = FALSE
);
curlhandle = getCurlHandle(.opts = opts)
getURL(uri, curl = curlhandle)
info <- getCurlInfo(curlhandle)
rm(curlhandle) # release the curlhandle!
info$effective.url
} else {
# just return the url as-is
uri
}
}
Twitter expands the URL. Assume you have a single tweet using twitter API
encoded as json file.
import json
urlInfo=[]
tweet=json.loads(tweet)
keyList=tweet.keys() # list of all posssible keys
tweet['entities'] # gives us values linked to entities
You can observe that there is a value called 'urls'
tweet['entities']['urls'] # gives values mapped to key urls
urlInfo=tweet['entities']['expanded_url'] # move it to a list
# iterating over the list.. gives shortened URL
# and expanded URL
for item in urlInfo:
if "url" and "expanded_url" in urlInfo.keys():
print(item["url"] + " "+item["expanded_url"])

Resources