Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

Slackのメッセージショートカットからgithub issueを作成するアプリ

$
0
0

Slack Message APIを使ってmessage-shortcut からissue作成

今回は自分が前回作成したSlack message APIを用いたGithub issue作成ショートカットのコード内容について書いていきます。

基本的部分はslackのmessage APIのSlack チュートリアルから引用しています。
全コードはこちらのGlitchから確認ください。https://glitch.com/edit/#!/slack-create-issue-pub
Glitchからremixをすることで、簡単に実装することが可能です。
実装の手順はこちらのページに書いています 
Slack message APIを用いたGithub issue作成ショートカット
開発環境: node.js: v10.15.3, javascript
使用ツール: Glitch

今回のメインのファイルはindex.js,confirmation.js,gitissue.js,verifySignature.js,.envの以上5つのファイルで、他のファイルは環境構築用です。
verifySignature.jsについては一切 Slack チュートリアルと変わらないので、割愛します。
index.jsファイルには、slack APIからactionを受け取り、そのactionのtypeによって行動を選択して実行しています。
今回のshortcut用のformを作成して、shortcut ボタンが押されたら、それが表示されるように設定します。

index.js
constexpress=require('express');constbodyParser=require('body-parser');constaxios=require('axios');constqs=require('qs');constapp=express();constapiUrl='https://slack.com/api';constrawBodyBuffer=(req,res,buf,encoding)=>{if(buf&&buf.length){req.rawBody=buf.toString(encoding||'utf8');}};app.use(bodyParser.urlencoded({verify:rawBodyBuffer,extended:true}));app.use(bodyParser.json({verify:rawBodyBuffer}));/*
/* Endpoint to receive an action and a dialog submission from Slack.
/* To use actions and dialogs, enable the Interactive Components in your dev portal.
/* Scope: `command` to enable actions
 *//* ここでshortcut用のmodalを送信しています。*/app.post('/actions',(req,res)=>{constpayload=JSON.parse(req.body.payload);const{type,user,view}=payload;console.log(JSON.parse(req.body.payload));// Message action triggeredif(type==='message_action'){// Open a modal with the selected message pre-populatedopenModal(payload).then((result)=>{if(result.data.error){console.log(result.data);res.sendStatus(500);}else{res.sendStatus(200);}}).catch((err)=>{res.sendStatus(500);});}elseif(type==='view_submission'){//ここにformを提出後の処理を書き足します。 }});/* 表示されるフォームをここで定義します */constopenModal=async(payload)=>{constviewData={token:process.env.SLACK_ACCESS_TOKEN,trigger_id:payload.trigger_id,view:JSON.stringify({type:'modal',title:{type:'plain_text',text:'Create a github issue'},callback_id:'create-issue',//登録したアプリのcall back IDを入力submit:{type:'plain_text',text:'Create'},//blockにinputする内容を決定 今回はGithub issue作成に必要なtitleとbodyblocks:[{block_id:'title',type:'input',element:{action_id:'title_id',type:'plain_text_input',multiline:true,initial_value:""},label:{type:'plain_text',text:'Issue Title'}},{block_id:'body',type:'input',element:{action_id:'body_id',type:'plain_text_input',multiline:true,/*Slack APIがMessage shortcutを通して、送られてきたmessageデータを
              payloadから取り出しinitial_valueに設定します。 */initial_value:payload.message.text},label:{type:'plain_text',text:'Issue Body'}}]})awaitaxios.post(`${apiUrl}/views.open`,qs.stringify(viewData));//console.log(result.data);};constserver=app.listen(process.env.PORT||5000,()=>{console.log('Express server listening on port %d in %s mode',server.address().port,app.settings.env);});

次にformをsubmitした後の処理をそれぞれ定義します。
この処理は大きく2つになります。

  • 確認用のmessageをbotから送信(confirmation.js)
  • formのtitle,bodyの情報でgithub APIからissueを作成する(gitissue.js)

それぞれの処理は各ファイルで定義して、index.jsにimportする形にしています。
確認用のmessageをbotから送信(confirmation.js)

confirmation.js
// slackへのform送信はaxiosとqsを用いて行います。constaxios=require('axios');constqs=require('qs');constapiUrl='https://slack.com/api';/*送信用formatを用意し、(userId,view)を引数に設定しています。 
 slackではsubmit後にviewにtextデータを追加して送信してくれるので、それをそのまま引数に設定しています。*/constsendConfirmation=(userId,view)=>{letvalues=view.state.values;letblocks=[{type:'section',text:{type:'mrkdwn',text:'issue was created successfully!\n\n'}},{type:'section',text:{type:'mrkdwn',text:`*title*\n${values.title.title_id.value}`}},{type:'section',text:{type:'mrkdwn',text:`*Message*\n${values.body.body_id.value}`}},];letmessage={token:process.env.SLACK_ACCESS_TOKEN,channel:userId,blocks:JSON.stringify(blocks)};axios.post(`${apiUrl}/chat.postMessage`,qs.stringify(message)).then((result=>{console.log(result.data);})).catch((err)=>{console.log(err);});}module.exports={sendConfirmation};

次にformのtitle,bodyの情報でgithub APIからissueを作成します。(gitissue.js)

gitissue.js
//今回はissue作成でRESTfull APIでのissue作成を簡略化してくれる octokitを使用しますconst{Octokit}=require("@octokit/rest");constGITHUB_ACCESS_TOKEN=process.env.GITHUB_ACCESS_TOKEN;// octokitインストールにPersonal_Access_Tokenを代入することでOAuth2認証を行えます。constoctokit=newOctokit({auth:GITHUB_ACCESS_TOKEN});constsendOctokit=(view)=>{letvalues=view.state.values;//viewデータで送られてきた情報を取得しますletinitialdatas={title:values.title.title_id.value,body:values.body.body_id.value,};//octokintでのissue作成octokit.issues.create({owner:'git-owner',//ここにowner名 git-ownerrepo:'git-repo',//ここにrepo名 git-repotitle:initialdatas.title,body:initialdatas.body,}).then(({data})=>{console.log(data);}).catch(error=>{console.log(error);});}module.exports={sendOctokit};

以上でsubmit後の処理のコードは完成です
後はこれらをindex.jsにimportして、formを提出後の処理を記入する場所に追加します。

index.js
constconfirmation=require('./confirmation');//confirmation.js利用のためconstgitissue=require('./gitissue');// gitissue.js利用のためif(type==='message_action'){//......}elseif(type==='view_submission'){//form提出後の処理を書くres.send('');// Make sure to respond immediately to the Slack server to avoid an errorgitissue.sendOctokit(view);// gitissue.jsからimport// DM the user a confirmation messageconfirmation.sendConfirmation(user.id,view);// confirmation.jsからimport}

以上でアプリのcode部分は完成です。


Viewing all articles
Browse latest Browse all 8691

Trending Articles