我刚刚开始学习Slack API,并且我想使用Google Apps脚本设置custom status。这是我所获得的代码(不知何故,我的个人资料变量出现了问题:
function setStatus() {
//https://api.slack.com/docs/presence-and-status
var token = MYTOKEN; //https://api.slack.com/apps
var apiEndpoint = "https://slack.com/api/";
var myUserID = MYUSERID;
var method = "users.profile.set";
var profile = {"status_text": "test"};
var payload = {"token": token, "user" : myUserID, "profile" : profile};
Logger.log(payload);
var completeUrl = apiEndpoint + method;
var jsonData = UrlFetchApp.fetch(completeUrl, {"method" : "post", "payload" : JSON.stringify(payload)});
var object = JSON.parse(jsonData.getContentText());
Logger.log(object);
}
但我收到的错误消息是{ok=false, error=invalid_form_data}
我已经通过此代码成功更改了状态(只是"方法""有效负载"变量已更改):
function setPresence() {
//https://api.slack.com/docs/presence-and-status
var token = MYTOKEN; //https://api.slack.com/apps
var apiEndpoint = "https://slack.com/api/";
var myUserID = MYUSERID;
var method = "users.setPresence";
var payload = {"token": token, "user" : myUserID, "presence" : "auto"}; //Presence can either be "auto" or "away"
Logger.log(payload);
var completeUrl = apiEndpoint + method;
var jsonData = UrlFetchApp.fetch(completeUrl, {"method" : "post", "payload" : JSON.stringify(payload)});
var object = JSON.parse(jsonData.getContentText());
Logger.log(object);
}
因此,如果有人可以帮助我指出我如何错误地传递profile
,那就太棒了!
答案 0 :(得分:3)
你的脚本几乎是正确的。我修改了一下。请检查一下。通过这个脚本,我已经确认了" status_text"可以改变。请包含users.profile:写入范围并再次检索访问令牌。
修改过的脚本:
function setStatus() {
//https://api.slack.com/docs/presence-and-status
var token = MYTOKEN; //https://api.slack.com/apps
var apiEndpoint = "https://slack.com/api/";
var myUserID = MYUSERID;
var method = "users.profile.set";
var profile = {"status_text": "test"};
var payload = {token: token, user: myUserID, profile: JSON.stringify(profile)};
Logger.log(payload);
var completeUrl = apiEndpoint + method;
var jsonData = UrlFetchApp.fetch(completeUrl, {method: "post", payload: payload});
var object = JSON.parse(jsonData.getContentText());
Logger.log(object);
}
答案 1 :(得分:0)
我也是.NET开发人员,所以对于那些想要C#解决方案的人,我已将最终解决方案转换为.NET:
string apiEndpoint = "https://slack.com/api/";
string method = "users.profile.set";
string completeUrl = apiEndpoint + method;
string token = MYTOKEN; //Put your token here
string userID = MYUSERID; //Put your user id here
JObject profile = new JObject()
{
{"status_text", "" },
{"status_emoji", "" }
};
NameValueCollection payload = new NameValueCollection()
{
{"token", token },
{"user", userID },
{"profile", profile.ToString() }
};
using (WebClient client = new WebClient())
{
var response = client.UploadValues(completeUrl, "POST", payload);
string responseText = (new UTF8Encoding()).GetString(response);
Console.WriteLine(responseText);
}
如果你不想要依赖于Newtonsoft.Json的东西那么你可以用这个代替:
JObject profile = new JObject()
{
{"status_text", "" },
{"status_emoji", "" }
};
与
string profile = "{" +
"\"status_text\":\"\"," + /* e.g. "\"status_text\":\"test\","*/
"\"status_emoji\":\"\"" +
"}";