index.ts 1.33 KB
Newer Older
duanjinfei's avatar
duanjinfei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.

console.log(`Function "telegram-bot" up and running!`)

import { Bot, webhookCallback } from 'https://deno.land/x/grammy@v1.34.0/mod.ts'

const bot = new Bot(Deno.env.get('TELEGRAM_BOT_TOKEN_F') || '')

bot.command('start', (ctx) => ctx.reply('Welcome! Up and running.'))

bot.command('ping', (ctx) => ctx.reply(`Pong! ${new Date()} ${Date.now()}`))

// bot.on('message', (ctx) => ctx.reply('你好,我是tg_F'))

const handleUpdate = webhookCallback(bot, 'std/http')

Deno.serve(async (req) => {
  try {
    const url = new URL(req.url)
    if (url.searchParams.get('secret') !== Deno.env.get('FUNCTION_SECRET_F')) {
      return new Response('not allowed', { status: 405 })
    }

    // 检查请求体
    if (req.body === null) {
      return new Response('Empty request body', { status: 400 })
    }

    const response = await handleUpdate(req)
    if (!response) {
      return new Response('Invalid update', { status: 400 })
    }

    return response
  } catch (err) {
    console.error(err)
    return new Response(JSON.stringify({ error: err.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
})