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

SlackBOT Node.js axios await asyncを使ったPOSTリクエスト

$
0
0

はじめに

最近のJavaScriptでGET,POSTリクエストするにはaxiosを使うのがイケてるらしいが、非同期の処理になるためコールバック地獄が起こる。それを解決するためにasyncawaitを使ったPOSTリクエストのサンプルコード(個人的なメモ)

SlackBOTに指定のチャンネルにテキストを投稿させるためのコードです。
カスタムインテグレーションではなく、「App」の方です
基本的なPOSTリクエストなので応用は効くと思います

コード

node.js
constaxios=require('axios');//npm install axios してね//Slackにメッセージを送る//引数1(文字列) : チャンネル名 (例: #勤怠履歴)//引数2(文字列) : 送りたいメッセージconstpostSlack=async(ch,msg)=>{console.log('postSlack...')constreq_url='https://slack.com/api/chat.postMessage'console.log('req_url:'+req_url);//これを使わずにオブジェクトで送るとJSONの形式ガーーーー!!みたいなErrorがでますletparams=newURLSearchParams();params.append('token','アクセストークン')//正式なものをいれてくださいparams.append('channel',ch)params.append('text',msg)constres=awaitaxios.post(req_url,params)returnres}

呼び出し方

index.js
consttest=async()=>{constresult=awaitpostSlack('#general','こんにちはせかい')console.log('result: '+JSON.stringify(result.data))}

結果

スクリーンショット 2020-05-29 午後6.38.38.png

うまく動かない場合は
SlackAppの管理画面から「OAuth & Permissions」→から以下の権限を与えてください(不要な権限があるとは思いますが、個人的な設定です

channels:manage
channels:read
chat:write
chat:write.customize
chat:write.public

遭遇したエラー

new URLSearchParams()を使わないときに遭遇したエラー

(node:73150) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'TLSSocket'
    --- property '_httpMessage' closes the circle
    at JSON.stringify (<anonymous>)
    at test (/Users/merarli/WebstormProjects/hogehoge/index.js:1143:32)
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:73150) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:73150) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


Viewing all articles
Browse latest Browse all 8697

Trending Articles