我正在使用telegraf bot framework編寫一個非常簡單的電報機器人。 到目前爲止,它使用.hears
和.on
方法回覆一些簡單的命令,到目前爲止一切正常。Try/Catch不會阻止崩潰
現在我實現了另一個.hears
方法,它正在等待字符串Miez
。一旦它「聽到」這個字符串,它應該是.replyWithDocument
包含一個cat-api網址。根據cat-api的URL在每次調用時都會提供一個隨機的cat-gif。到目前爲止,我的代碼:
const Telegraf = require('telegraf')
const app = new Telegraf('<MY_TOKEN>')
// Connect/Express.js integration
const express = require('express')
const expressApp = express()
expressApp.set('port', (process.env.PORT || 5000));
app.command('start', (ctx) => {
console.log('start', ctx.from)
ctx.reply('Welcome!')
})
app.hears('Hi', (ctx) => ctx.reply('Hallo!'))
app.hears('Marco', (ctx) => ctx.reply('Polo'))
app.on('sticker', (ctx) => ctx.reply('❤'))
app.hears('Miez',(ctx) => {
try{
return ctx.replyWithDocument({
url: 'http://thecatapi.com/api/images/get?format=src&type=gif',
filename: 'cat.gif'
})
}catch(error){
return ctx.reply("Miau");
}
})
因此,大家可以看到我擠包在一個try/catch塊.replyWithDocument
。我這樣做是因爲給定的url並不總是提供一個gif。有時候你會收到Server not found
消息。我託管在Heroku機器人和這裏的日誌,相應的錯誤:
Failed to process updates. { FetchError: request to http://30.media.tumblr.com/tumblr_lu65p0QXgW1r4xjo2o1_r1_500.gif failed, reason: getaddrinfo ENOTFOUND 30.media.tumblr.com 30.media.tumblr.com:80
at ClientRequest.<anonymous> (/app/node_modules/telegraf/node_modules/node-fetch/index.js:133:11)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at Socket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at connectErrorNT (net.js:1022:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
message: 'request to http://30.media.tumblr.com/tumblr_lu65p0QXgW1r4xjo2o1_r1_500.gif failed, reason: getaddrinfo ENOTFOUND 30.media.tumblr.com 30.media.tumblr.com:80',
name: 'FetchError',
errno: 'ENOTFOUND',
type: 'system',
code: 'ENOTFOUND' }
在此之後被拋出時,機器人將停止工作在Heroku上了一段時間,然後在15分鐘或某事之後又回來了,我想它會在一段時間不活動後重新啓動。
那麼,在底線我不介意URL調用有時失敗。我不明白的是爲什麼我的try/catch-block沒有捕捉到這種行爲。如果我對日誌的解釋是正確的。
編輯:一個可能的原因來到我的頭上,也許.replyWithDocument
是一個異步調用。所以HTTP請求是成功的,並且嘗試也是如此。但是一旦響應爲Server not found
,方法調用仍然失敗。如果這可能是原因,那麼如何處理呢?
如果replyWithDocument是基於承諾,使用.catch()。如果它基於回調,則處理回調中的錯誤參數。 –