Luigit
repositories / will

will

owned by admin

deploy/fake/telegram.mjs

Raw
#!/usr/bin/env node
/**
 * Fake Telegram Bot API for the workstation dev body (compose.yaml).
 * Echoes sent messages back as mentions so the wake path can be exercised
 * without network or a real bot token. Not production code.
 */
import { createServer } from 'node:http'

let nextUpdate = 1
let nextMessage = 100
const updates = []

const server = createServer((req, res) => {
  let data = ''
  req.on('data', (c) => {
    data += c
  })
  req.on('end', () => {
    let body = {}
    try {
      body = data === '' ? {} : JSON.parse(data)
    } catch {
      body = {}
    }
    const json = (p) => {
      res.writeHead(200, { 'content-type': 'application/json' })
      res.end(JSON.stringify(p))
    }
    const method = (req.url ?? '').split('/').pop()?.split('?')[0] ?? ''
    switch (method) {
      case 'getMe':
        return json({ ok: true, result: { id: 42, username: 'will_bot' } })
      case 'getUpdates': {
        const offset = body.offset ?? 0
        return json({ ok: true, result: updates.filter((u) => u.update_id >= offset) })
      }
      case 'sendMessage': {
        const msg = {
          update_id: nextUpdate++,
          message: {
            message_id: nextMessage++,
            date: Math.floor(Date.now() / 1000),
            chat: { id: body.chat_id },
            from: { id: 42, username: 'will_bot', is_bot: true },
            text: body.text,
          },
        }
        // Echo back as a mention wake after a short delay.
        setTimeout(() => {
          updates.push({
            update_id: nextUpdate++,
            message: {
              ...msg.message,
              message_id: nextMessage++,
              from: { id: 7, username: 'friend' },
              text: `@will_bot ${body.text}`,
              entities: [{ type: 'mention', offset: 0, length: 9 }],
            },
          })
        }, 1000)
        return json({ ok: true, result: { message_id: msg.message.message_id } })
      }
      default:
        return json({ ok: true, result: {} })
    }
  })
})

const port = Number.parseInt(process.env.PORT ?? '38080', 10)
server.listen(port, () => console.log(`fake telegram listening on :${port}`))