Skip to content

Instantly share code, notes, and snippets.

@AWtnb
Last active June 26, 2019 04:10
Show Gist options
  • Save AWtnb/c0107c5e1b0d282fd60b02b476868087 to your computer and use it in GitHub Desktop.
Save AWtnb/c0107c5e1b0d282fd60b02b476868087 to your computer and use it in GitHub Desktop.
lottery on slack
/*
slash command
ランダムに複数の要素を選ぶ抽選
*/
// 配列中の複数要素をランダムに取得する関数
// https://miya2000.hatenadiary.org/entry/20080607/p0
function randomChoose (array, num) {
var a = array;
var t = [];
var r = [];
var l = a.length;
var n = num < l ? num : l;
while (n-- > 0) {
var i = Math.random() * l | 0; // https://www.f-sp.com/entry/2016/11/18/190732
r[n] = t[i] || a[i];
--l;
t[i] = t[l] || a[l];
}
return r;
}
// 応答関数
function doPost (e) {
var postText = e.parameter.text.trim();
var user = e.parameter.user_name;
// スペースで分割して配列化
var p = postText.split(/\s/g);
// 返答メッセージ
var message = "文法が間違っています!\n `/lottery (半角数字) from (空白区切りの選択肢)` で指定してください!";
var type = "ephemeral";
if (p[0].match(/\d/) && p[1] == "from" && p.slice(2).length > 1) {
var choice = p.slice(2);
var pickUp = p[0];
var select = randomChoose(choice, pickUp);
message = user + " さんが挙げた *" + choice.length + "* 個の選択肢から以下の *" + pickUp + "* 個をランダムに選択しました!\n`" + select.join("` `") + "`";
type = "in_channel";
}
var response = {
"response_type": type,
"text": message
};
return ContentService.createTextOutput(JSON.stringify(response)).setMimeType(ContentService.MimeType.JSON);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment