質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
LINE Messaging API

LINE Messaging APIは、メッセージの送信・返信ができるAPIです。Web APIを経由しアプリケーションサーバとLINEのAPIでやり取りが可能。複数のメッセージタイプや分かりやすいAPIリファレンスを持ち、グループチャットにも対応しています。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Q&A

解決済

1回答

4688閲覧

LINE Messaging API のpushメッセージで "statusCode: 400" のエラーが出る

hokosugi

総合スコア63

LINE Messaging API

LINE Messaging APIは、メッセージの送信・返信ができるAPIです。Web APIを経由しアプリケーションサーバとLINEのAPIでやり取りが可能。複数のメッセージタイプや分かりやすいAPIリファレンスを持ち、グループチャットにも対応しています。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

0グッド

0クリップ

投稿2021/05/23 02:00

LINE developersのドキュメントの通りに node.js でpushメッセージを作成・実行しましたが、 statusCode: 400 のエラーです。

ACCESS_TOKENは LINE developersのコンソールにある「チャンネルアクセストークン(長期)」を貼り付けてあります。
pushMessageの第一引数にはwebhookでpostしたデータにあるdestination(lineUserId)を貼り付けました。

サンプル文でエラーなので、ACCESS_TOKENlineUserId が間違えていると普通だと思うのですが、合っていそうなので何故なのかわからなくなってしまいました。
一応、shellでも試しましたが同じ statusCode400 のエラーが出ました。(最後にエラー分を貼りました)

変更後のコピペしたコード

const line = require('@line/bot-sdk'); require('dotenv').config(); const client = new line.Client({ channelAccessToken: process.env.ACCESS_TOKEN }); const message = { type: 'text', text: 'Hello World!' }; client.pushMessage('lineUserId', message) .then(() => { console.log('seccess'); }) .catch((err) => { console.log(err); });

エラー文

HTTPError: Request failed with status code 400 at HTTPClient.wrapError (/Users/myname/sample/generate/node_modules/@line/bot-sdk/dist/http.js:89:20) at /Users/myname/sample/generate/node_modules/@line/bot-sdk/dist/http.js:19:88 at processTicksAndRejections (node:internal/process/task_queues:96:5) at async HTTPClient.post (/Users/myname/sample/generate/node_modules/@line/bot-sdk/dist/http.js:33:21) { statusCode: 400, statusMessage: 'Bad Request', originalError: Error: Request failed with status code 400 at createError (/Users/myname/sample/generate/node_modules/axios/lib/core/createError.js:16:15) at settle (/Users/myname/sample/generate/node_modules/axios/lib/core/settle.js:17:12) at IncomingMessage.handleStreamEnd (/Users/myname/sample/generate/node_modules/axios/lib/adapters/http.js:260:11) at IncomingMessage.emit (node:events:377:35) at endReadableNT (node:internal/streams/readable:1312:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) { config: { url: 'https://api.line.me/v2/bot/message/push', method: 'post', data: '{"messages":[{"type":"text","text":"Hello World!"}],"to":"lineUserId","notificationDisabled":false}', headers: [Object], transformRequest: [Array], transformResponse: [Array], timeout: 0, adapter: [Function: httpAdapter], xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: [Function: validateStatus] }, request: ClientRequest { _events: [Object: null prototype], _eventsCount: 7, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: true, chunkedEncoding: false, shouldKeepAlive: false, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, _closed: false, socket: [TLSSocket], _header: 'POST /v2/bot/message/push HTTP/1.1\r\n' + 'Accept: application/json, text/plain, */*\r\n' + 'Content-Type: application/json;charset=utf-8\r\n' + 'Authorization: Bearer process.env.ACCESS_TOKEN\r\n' + 'User-Agent: @line/bot-sdk/7.3.0\r\n' + 'Content-Length: 122\r\n' + 'Host: api.line.me\r\n' + 'Connection: close\r\n' + '\r\n', _keepAliveTimeout: 0, _onPendingData: [Function: nop], agent: [Agent], socketPath: undefined, method: 'POST', maxHeaderSize: undefined, insecureHTTPParser: undefined, path: '/v2/bot/message/push', _ended: true, res: [IncomingMessage], aborted: false, timeoutCb: null, upgradeOrConnect: false, parser: null, maxHeadersCount: null, reusedSocket: false, host: 'api.line.me', protocol: 'https:', _redirectable: [Writable], [Symbol(kCapture)]: false, [Symbol(kNeedDrain)]: false, [Symbol(corked)]: 0, [Symbol(kOutHeaders)]: [Object: null prototype] }, response: { status: 400, statusText: 'Bad Request', headers: [Object], config: [Object], request: [ClientRequest], data: [Object] }, isAxiosError: true, toJSON: [Function: toJSON] } }

shell エラー分(途中まで)

Note: Unnecessary use of -X or --request, POST is already inferred. * Trying 203.104.153.64... * TCP_NODELAY set * Connected to api.line.me (203.104.153.64) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/ssl/cert.pem CApath: none * TLSv1.2 (OUT), TLS handshake, Client hello (1): * TLSv1.2 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS change cipher, Change cipher spec (1): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384 * ALPN, server accepted to use h2 * Server certificate: * subject: C=JP; ST=Tokyo-to; L=Shinjuku-ku; O=LINE Corporation; CN=*.line.me * start date: Jun 17 06:01:58 2020 GMT * expire date: Sep 5 12:00:00 2022 GMT * subjectAltName: host "api.line.me" matched cert's "*.line.me" * issuer: C=BE; O=GlobalSign nv-sa; CN=GlobalSign RSA OV SSL CA 2018 * SSL certificate verify ok. * Using HTTP2, server supports multi-use * Connection state changed (HTTP/2 confirmed) * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 * Using Stream ID: 1 (easy handle 0x7f9f7d80f400) > POST /v2/bot/message/push HTTP/2 > Host: api.line.me > User-Agent: curl/7.64.1 > Accept: */* > Content-Type: application/json /* 中略 */ > Content-Length: 104 > * We are completely uploaded and fine * Connection state changed (MAX_CONCURRENT_STREAMS == 128)! < HTTP/2 400 < server: openresty

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

ソースをコピペしてアクセストークンと宛先(ユーザーID)だけ書き換えて試しましたがちゃんとメッセージ送信できました。ご自分でも書かれているように、アクセストークンかユーザーIDの間違いだと思われます。
アクセストークンを環境変数から取得するのではなく直接ソース上に書くとか、ユーザーIDはチャネル管理画面に表示されている自分のユーザーIDを使ってみるとかしてみてはどうでしょうか。

投稿2021/05/23 04:19

draq

総合スコア2573

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hokosugi

2021/05/23 07:19

ご回答ありがとうございます!見直した所、pushMessageメソッドの第一引数に指定している値はlineUserIdではなく、webhookで指定したボットサーバーの値のようです。`destination`なのでオカシイなとは思っていたものの早めに気づくべきでした。lineUserIdを指定したら出来ました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問