3
1

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-05-29

はじめに

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

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

コード

node.js
const axios = require('axios');//npm install axios してね

//Slackにメッセージを送る
//引数1(文字列) : チャンネル名 (例: #勤怠履歴)
//引数2(文字列) : 送りたいメッセージ
const postSlack = async (ch,msg) =>{
    console.log('postSlack...')
    const req_url = 'https://slack.com/api/chat.postMessage'
    console.log('req_url:' + req_url);

    //これを使わずにオブジェクトで送るとJSONの形式ガーーーー!!みたいなErrorがでます
    let params = new URLSearchParams();

    params.append('token','アクセストークン') //正式なものをいれてください
    params.append('channel',ch)
    params.append('text',msg)

    const res = await axios.post(req_url, params)

    return res
}

呼び出し方

index.js
const test = async () => {
 const result = await postSlack('#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.

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1