Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion ds-bot/src/host/im/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export function install(rt) {
numbersMulti: 'reply with the numbers, separated by spaces',
allow: 'Allow once',
reject: 'Reject',
typeOwn: 'Type my own answer',
typePrompt: 'Type your answer and send it.',
},
zh: {
requested: '已向 DS Bot 发出连接请求,请在电脑上的 DS Bot 设置 → IM 里允许。',
Expand All @@ -74,6 +76,8 @@ export function install(rt) {
numbersMulti: '回复编号,多选用空格隔开',
allow: '允许一次',
reject: '拒绝',
typeOwn: '自己输入答案',
typePrompt: '输入你的答案后发送。',
},
'zh-TW': {
requested: '已向 DS Bot 發出連線請求,請在電腦上的 DS Bot 設定 → IM 裡允許。',
Expand All @@ -94,6 +98,8 @@ export function install(rt) {
numbersMulti: '回覆編號,多選用空格隔開',
allow: '允許一次',
reject: '拒絕',
typeOwn: '自己輸入答案',
typePrompt: '輸入你的答案後傳送。',
},
ja: {
requested: 'DS Bot に接続リクエストを送信しました。PC の DS Bot 設定 → IM で許可してください。',
Expand All @@ -114,6 +120,8 @@ export function install(rt) {
numbersMulti: '番号をスペース区切りで返信',
allow: '1回許可',
reject: '拒否',
typeOwn: '自分で回答を入力',
typePrompt: '回答を入力して送信してください。',
},
ko: {
requested: 'DS Bot에 연결 요청을 보냈습니다. 컴퓨터의 DS Bot 설정 → IM에서 허용해 주세요.',
Expand All @@ -134,6 +142,8 @@ export function install(rt) {
numbersMulti: '공백으로 구분하여 번호로 답장',
allow: '한 번 허용',
reject: '거부',
typeOwn: '직접 답변 입력',
typePrompt: '답변을 입력해 보내 주세요.',
},
es: {
requested: 'Se envió una solicitud de conexión a DS Bot; permítela en Ajustes → IM en el ordenador.',
Expand All @@ -154,6 +164,8 @@ export function install(rt) {
numbersMulti: 'responde con los números separados por espacios',
allow: 'Permitir una vez',
reject: 'Rechazar',
typeOwn: 'Escribir mi respuesta',
typePrompt: 'Escribe tu respuesta y envíala.',
},
fr: {
requested: 'Une demande de connexion a été envoyée à DS Bot ; autorisez-la dans Paramètres → IM sur l’ordinateur.',
Expand All @@ -174,6 +186,8 @@ export function install(rt) {
numbersMulti: 'répondez avec les numéros séparés par des espaces',
allow: 'Autoriser une fois',
reject: 'Refuser',
typeOwn: 'Écrire ma réponse',
typePrompt: 'Écrivez votre réponse et envoyez-la.',
},
de: {
requested: 'Eine Verbindungsanfrage wurde an DS Bot gesendet; erlaube sie am Computer unter Einstellungen → IM.',
Expand All @@ -194,6 +208,8 @@ export function install(rt) {
numbersMulti: 'mit durch Leerzeichen getrennten Nummern antworten',
allow: 'Einmal erlauben',
reject: 'Ablehnen',
typeOwn: 'Eigene Antwort schreiben',
typePrompt: 'Schreibe deine Antwort und sende sie.',
},
}
return (table[lang] ?? table.en)[key] ?? key
Expand Down Expand Up @@ -489,6 +505,45 @@ export function install(rt) {
}
const sendCardReply = async (conn, chat, body) => sendText(conn, { key: chat.key, kind: chat.kind, title: chat.title }, body)

// A card whose typed-answer button was tapped, per chat: the next text there is
// its answer. One per chat, so a second tap replaces the first. Not persisted:
// after a restart the text is an ordinary message, which still closes the card.
const armed = new Map()
const armKey = (conn, chatKey) => `${conn.id}\n${chatKey}`
const typedButton = cardKey => ({ data: `t:${cardKey}`, label: text('typeOwn') })
const typeable = (conn, cardKey) => conn.platform === 'telegram' && (cardKey.startsWith('q:') || cardKey.startsWith('v:'))
const cardOpen = (conn, chatKey, cardKey) => openCard(conn, chatKey, cardKey) !== undefined
&& (cardKey.startsWith('q:') ? questionById(cardKey.slice(2)) !== undefined : viewById(cardKey.slice(2)) !== undefined)
const armTyped = async (conn, chat, cardKey) => {
if (!cardOpen(conn, chat.key, cardKey)) {
await sendCardReply(conn, chat, text('stale'))
return
}
armed.set(armKey(conn, chat.key), cardKey)
enqueue(conn, chat.key, { chat: { key: chat.key, kind: chat.kind, title: chat.title }, text: text('typePrompt'), forceReply: true })
}
// The typed answer for the card this chat armed. False when that card is no
// longer open, so the text goes on as an ordinary message.
const answerTyped = async (conn, chat, cardKey, body) => {
if (!cardOpen(conn, chat.key, cardKey)) return false
try {
if (cardKey.startsWith('q:')) {
const found = questionById(cardKey.slice(2))
await rt.answerQuestion(found.sessionId, found.question.id, { selected: [], custom: body })
} else {
// A view has no free-text answer; the user's own message closes it as replied.
const found = viewById(cardKey.slice(2))
await rt.sendUser({ sessionId: found.sessionId, content: [{ type: 'text', text: body }], requestId: `im:${conn.platform}:${randomUUID()}` })
}
} catch (error) {
if (error?.code === 'bot/stale') return false
throw error
}
await settleCard(conn.id, cardKey, body)
await settledEdits(conn)
return true
}

// The chat's newest still-open card, questions and approvals together: a bare
// number answers whatever arrived last, not always a question.
const newestOpenCard = (conn, chatKey) => {
Expand Down Expand Up @@ -534,6 +589,11 @@ export function install(rt) {
await sendText(conn, msg.chat, text(stopped ? 'stopped' : 'idle'))
return
}
const armedCard = armed.get(armKey(conn, msg.chat.key))
if (armedCard !== undefined && body !== '') {
armed.delete(armKey(conn, msg.chat.key))
if (await answerTyped(conn, msg.chat, armedCard, body)) return
Comment on lines +592 to +595

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bind the armed answer to the user who pressed the button

In a Telegram group with multiple paired users, one user can press “Type my own answer” and another user's next message mentioning or replying to the bot will consume that arm. Because the key contains only the connection and chat, unrelated text is submitted as the first user's card answer, closing the question before their actual answer arrives. Store the initiating sender ID and require it to match before consuming the armed card; other users' messages should retain their ordinary routing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve attachments when consuming a typed reply

If the user answers an armed card with a captioned photo or document, Telegram supplies both nonempty text and images/files. This early return passes only the caption to answerTyped, bypassing the attachment processing below. For a view, the resulting sendUser call likewise contains only text, so an answer such as “use the attached specification” reaches the Bot without its specification and the card is settled anyway. Preserve or separately deliver the attachments when handling the typed answer rather than silently discarding them.

Useful? React with 👍 / 👎.

}
if (NUMBERS.test(body)) {
const picked = body.trim().split(/\s+/).map(Number)
const held = newestOpenCard(conn, msg.chat.key)
Expand Down Expand Up @@ -582,6 +642,10 @@ export function install(rt) {
if (!paired(conn, action.sender.id)) return
const data = String(action.data ?? '')
const chat = { key: action.chat.key, kind: action.chat.kind, title: action.chat.title }
if (data.startsWith('t:') && data.length > 4) {
await armTyped(conn, chat, data.slice(2))
return
}
// Button data is `<kind>:<id>:<choice>`; the id is everything between the
// first and the last colon, so an id with a colon in it still parses.
const cut = data.lastIndexOf(':')
Expand Down Expand Up @@ -632,7 +696,9 @@ export function install(rt) {
approval: (id) => [{ data: `a:${id}:allow`, label: text('allow') }, { data: `a:${id}:reject`, label: text('reject') }],
}

const sendCard = async (conn, cardKey, targets, body, buttons) => {
const sendCard = async (conn, cardKey, targets, body, given) => {
// Every typeable card gets the typed-answer button here, so no caller can leave it out.
const buttons = typeable(conn, cardKey) ? [...(given ?? []), typedButton(cardKey)] : given
for (const { chatKey, chat } of targets) {
sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, body, buttons, (sent) => {
void markCard(conn.id, cardKey, chatKey, sent?.messageId, body)
Expand Down
8 changes: 5 additions & 3 deletions ds-bot/src/host/im/platforms/telegram.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,13 +193,15 @@ export default {
}
void poll()

const send = async (chat, { text, buttons }) => {
const send = async (chat, { text, buttons, forceReply }) => {
const chunks = chunkTelegram(text, TEXT_LIMIT)
let messageId
for (const [index, chunk] of chunks.entries()) {
const markup = index === chunks.length - 1 && buttons?.length > 0
const last = index === chunks.length - 1
// An inline keyboard and a reply prompt cannot share one message.
const markup = last && buttons?.length > 0
? { reply_markup: { inline_keyboard: buttons.map(button => [{ text: button.label, callback_data: button.data }]) } }
: {}
: last && forceReply === true ? { reply_markup: { force_reply: true } } : {}
const sendOne = async (body) => {
try {
return await call('sendMessage', { chat_id: chat.key, text: body, parse_mode: 'HTML', ...markup })
Expand Down
14 changes: 14 additions & 0 deletions ds-bot/test/im-telegram.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,20 @@ test('send renders HTML, chunks long text, buttons go on the last chunk', async
} finally { api.close() }
})

test('a reply prompt goes with force_reply and no inline keyboard', async () => {
const api = await fakeApi()
try {
const handle = telegram.connect({ token: 'TOKEN' }, env(api.api), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
await handle.send({ key: '5' }, { text: 'Type your answer and send it.', forceReply: true })
const sends = api.calls.filter(call => call.method === 'sendMessage')
assert.equal(sends.length, 1)
assert.deepEqual(sends[0].params.reply_markup, { force_reply: true })
await handle.send({ key: '5' }, { text: 'plain' })
assert.equal(api.calls.filter(call => call.method === 'sendMessage')[1].params.reply_markup, undefined, 'ordinary sends carry no reply prompt')
handle.stop()
} finally { api.close() }
})

test('a chunk Telegram cannot parse goes again as plain text', async () => {
const api = await fakeApi()
try {
Expand Down
119 changes: 118 additions & 1 deletion ds-bot/test/im.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ test('a single-choice view card gets buttons, and a press answers the view', asy
await showView(s)
const card = s.fake.sent.find(entry => entry.buttons !== undefined)
assert.ok(card, 'the view card has buttons')
assert.deepEqual(card.buttons, [{ data: 'v:v1:0', label: 'Ship' }, { data: 'v:v1:1', label: 'Hold' }])
assert.deepEqual(card.buttons, [{ data: 'v:v1:0', label: 'Ship' }, { data: 'v:v1:1', label: 'Hold' }, { data: 't:v:v1', label: 'Type my own answer' }])
assert.match(card.text, /Chief asks: Ship it\?\nThe build is green\.\n1\. Ship\n2\. Hold - wait a day\n\(reply with the number\)/)
await s.fake.handlers.onAction({ chat: { key: 'dm-u1', kind: 'direct', title: 'U1' }, sender: { id: 'u1', name: 'U1' }, data: 'v:v1:1', messageId: 1 })
assert.equal(s.rt.state.views.a, undefined, 'the press answers the view')
Expand Down Expand Up @@ -572,6 +572,123 @@ test('a view answered on the computer settles its IM card', async (t) => {
assert.match(s.fake.edited[0].text, /answered/)
})

const QUESTION = { id: 'q1', question: 'Ship it?', options: [{ label: 'deploy to production' }, { label: 'One customer first' }, { label: 'Hold' }] }
const askQuestion = async (s) => {
s.rt.state.questions.a = structuredClone(QUESTION)
await s.rt.save()
await s.flush()
}
const press = (s, data) => s.fake.handlers.onAction({ chat: { key: 'dm-u1', kind: 'direct', title: 'U1' }, sender: { id: 'u1', name: 'U1' }, data, messageId: 1 })
const answerOf = message => JSON.parse(message.content[0].text).answers[0]
const followups = (s) => {
const got = []
s.agentOf('a').followup = (message) => { got.push(message) }
return got
}

test('a Telegram question card carries a fourth button that types an answer', async (t) => {
const s = await start()
t.after(s.stop)
await pairedChat(s)
await askQuestion(s)
const card = s.fake.sent.find(entry => entry.buttons !== undefined)
assert.deepEqual(card.buttons.map(button => button.data), ['q:q1:0', 'q:q1:1', 'q:q1:2', 't:q:q1'])
assert.equal(card.buttons[3].label, 'Type my own answer')
})

test('the typed-answer button arms a reply prompt and the next text answers that card', async (t) => {
const s = await start()
t.after(s.stop)
await pairedChat(s)
await askQuestion(s)
const got = followups(s)
await press(s, 't:q:q1')
await s.flush()
const prompt = s.fake.sent.at(-1)
assert.equal(prompt.forceReply, true, 'the prompt asks Telegram for a reply box')
assert.equal(prompt.buttons, undefined, 'a reply prompt carries no inline keyboard')
assert.ok(s.rt.state.questions.a !== undefined, 'arming answers nothing yet')
s.prompts.length = 0
await dm(s, 'u1', 'Ship to Acme only, then wait a day')
assert.equal(s.rt.state.questions.a, undefined, 'the typed text answers the card')
assert.equal(got.length, 1, 'the same Bot gets the answer')
assert.deepEqual(answerOf(got[0]), { id: 'q1', selected: [], custom: 'Ship to Acme only, then wait a day' })
assert.equal(s.prompts.length, 0, 'the text is not also sent as an ordinary message')
await s.flush()
assert.equal(s.fake.edited.length, 1, 'the card is edited shut')
s.prompts.length = 0
await dm(s, 'u1', 'and one more thing')
assert.equal(s.prompts.length, 1, 'the arm is spent: the next text is an ordinary message')
})

test('ordinary chat text with no armed card is untouched', async (t) => {
const s = await start()
t.after(s.stop)
await pairedChat(s)
await askQuestion(s)
const got = followups(s)
s.prompts.length = 0
await dm(s, 'u1', 'what does this card mean?')
assert.equal(got.length, 0, 'nothing answers the card')
assert.ok(s.rt.state.questions.a !== undefined, 'the card stays open')
assert.equal(s.prompts.length, 1, 'the text reaches the Bot as an ordinary message')
assert.deepEqual(s.prompts[0].content, [{ type: 'text', text: 'what does this card mean?' }])
})

test('a typed answer never binds to a card that closed after it was armed', async (t) => {
const s = await start()
t.after(s.stop)
await pairedChat(s)
await askQuestion(s)
const got = followups(s)
await press(s, 't:q:q1')
delete s.rt.state.questions.a
await s.rt.save()
await s.flush()
s.prompts.length = 0
await dm(s, 'u1', 'late text')
assert.equal(got.length, 0, 'the closed card is not answered')
assert.equal(s.prompts.length, 1, 'the text goes on as an ordinary message')
})

test('a plain number still answers the card on Telegram', async (t) => {
const s = await start()
t.after(s.stop)
await pairedChat(s)
await askQuestion(s)
const got = followups(s)
await dm(s, 'u1', '2')
assert.equal(s.rt.state.questions.a, undefined)
assert.deepEqual(answerOf(got[0]), { id: 'q1', selected: ['One customer first'] })
})

test('a second arm replaces the first, and a typed view answer reaches the Bot', async (t) => {
const s = await start()
t.after(s.stop)
await pairedChat(s)
await showView(s)
await press(s, 't:v:v1')
await press(s, 't:v:v1')
await s.flush()
assert.equal(s.fake.sent.filter(entry => entry.forceReply === true).length, 2)
s.prompts.length = 0
await dm(s, 'u1', 'neither, ask me tomorrow')
assert.equal(s.prompts.length, 1, 'the typed text goes to the Bot once')
assert.deepEqual(s.prompts[0].content, [{ type: 'text', text: 'neither, ask me tomorrow' }])
await s.flush()
assert.equal(s.fake.edited.length, 1, 'the view card is edited shut')
})

test('arming a card that is already answered gets the stale text', async (t) => {
const s = await start()
t.after(s.stop)
await pairedChat(s)
await press(s, 't:q:gone')
await s.flush()
assert.ok(s.fake.sent.some(entry => /already answered/.test(entry.text ?? '')))
assert.ok(!s.fake.sent.some(entry => entry.forceReply === true), 'no reply prompt for a closed card')
})

test('a read-only host runs no adapter; becoming writable starts it', async (t) => {
const s = await start()
t.after(s.stop)
Expand Down
Loading