How to connect to Slack via slackr package in R - r

I'm trying to set up the slackr package in R to allow me to post to Slack through RStudio, but it seems the connection isn't working.
I've installed the package, set up the required App in my Slack Workspace, have a webhook and access tokens, manually granted all of Scopes needed in Slack, set up the config file and have confirmed via the cmd line that this works by sending a message to the channel through that successfully. Unfortunately nothing is working via R.
slackr_msg(paste("test"),
,channel = "#it-reports")
slackr_ims(api_token="xoxb-...")
When run the above both produce Error: Join columns must be present in data. x Problem with 'id'. which I can't find anybody else experiencing. It sounds like an issue with the user, but the app is in the channel, has permission to access all public channels, and this error appears regardless of whether I try and send it via my logged in account or just from the bot. When I just try and return something simple like listed channels with slackr_channels I get NULL. I've tried both OAuth Access Token and Bot User OAuth Access Token with all permissions needed in the scope but neither are letting me access Slack.

I'm not sure you still need an answer, but in case anyone else is looking - I've run into the same issue. I think the underlying method that your slack channel name "#my_excellent_named_channel" is converted to the channel id is deprecated.
"https://slack.com/api/channels.list" has been changed to "https://slack.com/api/conversations.list" in the methods.
I couldn't find a better way than brute forcing my channel id because I only need to publish to a notifications channel.
nextCursor=""
for (j in c(1:10)){
resp<-GET(url = "https://slack.com/api/conversations.list",
query = list(token=YOUR_BOT_TOKEN,
cursor=nextCursor
))
foo=fromJSON(content(resp, as="text"))
for (i in c(1:100)){
if(foo$channels[[i]]$name %like% 'my_excellent_named_channel'){
print(paste(nextCursor, "\n"))
print(paste(i,foo$channels[[i]]$name,"\n"))
print(paste(foo$channels[[i]]$id))
}
}
nextCursor=foo$response_metadata[[1]]
}
You'll probably need to run through a few more than the 10 top level iterations, but if you go too fast it locks you out. I then just exchanged the channel name in my config file for the channel id, and rewrote the functions to avoid the conversion.
Here's slackMsg (conversion of slackrMsg)
slackMsg=function (txt = "", channel = Sys.getenv("SLACK_CHANNEL"), username = Sys.getenv("SLACK_USERNAME"),
icon_emoji = Sys.getenv("SLACK_ICON_EMOJI"), api_token = Sys.getenv("SLACK_API_TOKEN"),
...)
{
if (api_token == "") {
stop("No token specified. Did you forget to call slackr_setup()?",
call. = FALSE)
}
if (icon_emoji != "") {
icon_emoji <- sprintf(", \"icon_emoji\": \"%s\"", icon_emoji)
}
output <- paste0(txt, collapse = "\n\n")
loc <- Sys.getlocale("LC_CTYPE")
Sys.setlocale("LC_CTYPE", "C")
on.exit(Sys.setlocale("LC_CTYPE", loc))
resp <- POST(url = "https://slack.com/api/chat.postMessage",
body = list(token = api_token, channel = channel,
username = username, icon_emoji = icon_emoji, text = output,
as_user = TRUE, link_names = 1, ...))
warn_for_status(resp)
return(invisible())
}
Don't forget to give your bot chat.write permissions in your Slack App.

Related

Using Rtweet's search_fullarchive in R

I am trying to use rtweet's search_fullarchive using my premium token registered at Twitter Developer. However, I got an error message of:
Warning: list(message = "Forbidden: Authentication succeeded but account is not authorized to access this resource.", sent = "2019-07-14T14:30:11+00:00", transactionId = "xxxxxxxxxx")
How do I get past this problem? Is there an error in the way i code?
I ensured my token is working well by testing it using httr's POST method and it worked completely fine.
I also tested my token using normal search_tweets, and also worked fine.
cons_key = "xxx"
cons_sec = "xxx"
acc_tok = "xxx"
acc_sec = "xxx"
app = "abc"
token = rtweet::create_token(app,cons_key,cons_sec,acc_tok,acc_sec)
manutd = search_fullarchive("manchester united",n=500,
fromDate = "201812010000",toDate = "201902010000",
env_name = app,token = token)
I expected a tibble dataframe as usually Rtweet's returns. However this is what i received:
"Warning: list(message = "Forbidden: Authentication succeeded but account is not authorized to access this resource.", sent = "2019-07-14T14:30:11+00:00", transactionId = "xxxxxxxxxx")"
data frame with 0 columns and 0 rows
To help anyone who might have trouble with the same thing, i'll write down a bit of explanation. Firstly, if you have registered a premium account, go to
To create the token, you need the App Name.
token = rtweet::create_token(app_name,cons_key,cons_sec,acc_tok,acc_sec)
To do query, you need the environment name.
search_fullarchive(q, n = 100, fromDate = NULL, toDate = NULL, env_name = "dev_name", safedir = NULL, parse = TRUE, token = token)
Hope it helps beginners or anyone who might have the same troubles.

User-Id for Push-Notification on Actions for Google

I try to make a push notification for my google assistant app.
I used the sendNotification Code form the google developer site: https://developers.google.com/actions/assistant/updates/notifications
I am coding Java.
Everything is working, expect getting the correct user id.
When I hardcode my user it works, but how do I get the user id in the code?
I tried following code:
Argument arg_userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
String userId = request.getUser().getUserId();
--> I get "java.lang.reflect.InvocationTargetException"
String userId = arg_userId.getRawText();
--> same Exception
There are two problems with the approach you're taking to get the notification ID:
The ID attached to the user object is deprecated and probably unavailable.
This wasn't the ID you wanted anyway.
In the response where the user finalizes the notification, that response includes an ID which you should get and store. Since you're using Java, the code might look something like this:
ResponseBuilder responseBuilder = getResponseBuilder(request);
Argument permission = request.getArgument(ConstantsKt.ARG_PERMISSION);
if (permission != null) {
Argument userId = request.getArgument(ConstantsKt.ARG_UPDATES_USER_ID);
// code to save intent and userID in your db
responseBuilder.add("Ok, I'll start alerting you.").endConversation();
} else {
responseBuilder.add("Ok, I won't alert you.");
}
return responseBuilder.build();

How to fetch Shopify store orders using Shopify's API

I'm struggling to import the orders for a Shopify development store using the httr package in R. Here's what I've tried.
I've created a development store and made some fake orders.
Within my development store, I added a private app and generated my API key and Password
Following this article, I tried implementing the following request
Code
apikey <- "foo"
pass <- "bar"
shop <- GET(
url = "my-test-store.myshopify.com/orders.json",
authenticate(user = apikey, password = pass)
)
But this gives a 401 status code. However, this works but returns xml instead of json
shop <- GET(
url = "my-test-store.myshopify.com/orders",
authenticate(user = apikey, password = pass)
)
How can I retrieve the results as JSON instead of XML?
Note that I can also fetch the orders using the R package shopifyr but would rather not use that package as it is no longer maintained.
You're close. Try this:
library(httr)
apikey <- "foo"
pass <- "bar"
orders <- GET(
url = "https://yourshop.myshopify.com/admin/orders.json",
authenticate(user = apikey, password = pass)
)
content(orders)
Update 2019-05-13
I created an R package called shopr for querying data via the Shopify API. Fetching orders looks like this
library(shopr)
shopr_get_orders(
shopURL = "https://my-test-store.myshopify.com",
APIKey = "abc123",
APIPassword = "def456"
)
Old Answer
Figured it out.
orders <- GET(
url = "https://my-test-store.myshopify.com/admin/orders",
add_headers(Accept = "application/json"),
authenticate(user = apikey, password = pass)
)
orders
The trick was to explicitly put "https://..." in the url otherwise httr was prepending "http://" to the url, causing my 401 problem.

Convert string to map in lua

I am quite new to lua. I trying to convert a string of the form
{"result": "success", "data":{"shouldLoad":"true"}"}
into lua map. So that I can access it like json. e.g. someMap[data][shouldLoad] => true
I dont have any json bindings in lua. I also tried loadstring to convert string of the form {"result" = "success", "data"={"shouldLoad"="true"}"}, which is not working.
Following, is the code snippet, where I am calling getLocation hook, which in turn returns json stringified map. Now I want to access some keys from this response body and take some decisions accordingly.
access_by_lua "
local res = ngx.location.capture('/getLocation')
//res.body = {"result"= "success", "data" = {"shouldLoad" = "true"}}
local resData = loadstring('return '..res.body)()
local shoulLoad = resData['data']['shouldLoad']
"
When I try to load shouldLoad value, nginx error log reports error saying trying to index nil value.
How do I access key value with either of the string formats. Please help.
The best answer is to consider a pre-existing JSON module, as suggested by Alexey Ten. Here's the list of JSON modules from Alexey.
I also wrote a short pure-Lua json module that you are free to use however you like. It's public domain, so you can use it, modify it, sell it, and don't need to provide any credit for it. To use that module you would write code like this:
local json = require 'json' -- At the top of your script.
local jsonStr = '{"result": "success", "data":{"shouldLoad":"true"}"}'
local myTable = json.parse(jsonStr)
-- Now you can access your table in the usual ways:
if myTable.result == 'success' then
print('shouldLoad =', myTable.data.shouldLoad)
end

Retrieve Oauth 2.0 refresh token with R httr google demo

A refresh token is not available when I follow Hadley's R google Oauth2.0 demo to access Fusion tables.
Demo: https://github.com/hadley/httr/blob/master/demo/oauth2-google.r
Example of modified "offline" attempt:
google_token <- oauth2.0_token(oauth_endpoints("google"), myapp,
scope = "https://www.googleapis.com/auth/fusiontables",
type= "offline",
use_oob = FALSE,
cache = TRUE)
Any direction on how to retrieve a refresh token is much appreciated.
UPDATE:
Using the follow code a character string is returned with google_token$credentials. Is this the authorization code referenced here:https://developers.google.com/accounts/docs/OAuth2WebServer#offline
google_token <- oauth2.0_token(oauth_endpoints("google"), myapp,
scope = "https://www.googleapis.com/auth/fusiontables",
type= "access_type='offline'",
use_oob = FALSE,
cache = TRUE)
Thank you.
I'm a bit late to the party here but hopefully this helps someone. I found this question last week because I was struggling with the same issue. Like you, I read the API documentation and tried the "offline" in the "type" field of the "oauth2.0_token()" function but it messed up the response. I downloaded the httr package source files from the github repository and had a look around. After some digging I found a way around it.
if you modify the "authorize-url" variable in oauth-init from this:
authorize_url <- modify_url(endpoint$authorize, query = compact(list(
client_id = app$key,
scope = scope_arg,
redirect_uri = redirect_uri,
response_type = "code",
state = state)))
to this:
authorize_url <- modify_url(endpoint$authorize, query = compact(list(
client_id = app$key,
scope = scope_arg,
redirect_uri = redirect_uri,
response_type = "code",
state = state,
access_type="offline")))
and then source the oauth-token and all the dependent functions (including oauth-init) you'll get a refresh token. For some reason, when oauth_token calls init_oauth2.0 it doesn't pass the "type" argument.
It's a nasty workaround and I've probably committed several sins but it does work. and you do get a refresh token.

Resources