概要
Dialogflow V2 API使用時に、Intentを作成したのですが、戻り値にはIDは含まれていません。
そうすると、更新や削除のときに困ってしまい、APIとして機能しないので、IDの取得法の備忘録として書きました。
本題
以下、TypeScriptで書いてます。
accessTokenはすでに取得している前提で始めます。
index.ts
import axios from 'axios'
async function main() {
const URL = 'https://dialogflow.googleapis.com/v2'
const projectId = 'test'
const accessToken = 'hogehoge'
let http = axios.create({
baseURL: `${URL}/projects/${projectId}/agent/intents`,
// timeout: 1000,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
},
})
const { data } = await http.post('', {
displayName: 'Greeting',
webhookState: 'WEBHOOK_STATE_UNSPECIFIED',
priority: 5000000,
isFallback: false,
mlDisabled: false,
trainingPhrases: [
{
'type': 'EXAMPLE',
'parts': [
{
'text': 'Hello!',
},
],
},
],
'action': 'greeting',
'messages': [
{
'text': {
'text': [
'Hello!',
],
},
},
],
},
)
const intentId = data.name.split('/').pop()
}
main()
main
関数の最終行に注目してください。
const intentId = data.name.split('/').pop()
Dialogflow V2 APIの戻り値は以下のようになっています。
{
"name": "projects/test/agent/intents/15933e2c-63f4-45c9-87c2-f69a4a19f71a",
"displayName": "Greeting-again",
"priority": 500000,
"action": "greeting",
"messages": [
{
"text": {
"text": [
"Hello!"
]
}
}
]
}
上記のname
の中のintents
以降がintentのIDです。
そのため、/
でsplit
して、最後のものをpop
しています。
APIのリファレンスを読まないと、IDが返ってくるものと勘違いしてしまいがちですが、返ってこないんですね。
思い込みでやったら危険ということを改めて認識しました。