Skip to content

Commit

Permalink
refactor: use grammy instead myself type
Browse files Browse the repository at this point in the history
  • Loading branch information
niracler committed May 15, 2024
1 parent 420327e commit ac8e2c2
Show file tree
Hide file tree
Showing 11 changed files with 57 additions and 75 deletions.
20 changes: 20 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"dependencies": {
"crossbell": "^1.11.9",
"crypto-js": "^4.2.0",
"grammy": "^1.23.0",
"oauth-1.0a": "^2.2.6",
"openai": "^4.33.0",
"telegramify-markdown": "git+ssh://[email protected]/niracler/telegramify-markdown.git#master"
Expand Down
5 changes: 3 additions & 2 deletions src/channel/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Env as CoreEnv, TelegramUpdate } from "@/core/type"
import { Env as CoreEnv } from "@/core/type"
import { Update } from "grammy/types"

export type Env = {} & CoreEnv

Expand All @@ -9,7 +10,7 @@ export type Env = {} & CoreEnv
* @param env - The environment object.
* @returns A promise that resolves to a string indicating the result of the sync operation.
*/
export async function processChannel(update: TelegramUpdate, env: Env): Promise<string> {
export async function processChannel(update: Update, env: Env): Promise<string> {

const message = update.message?.text || update.message?.caption || ''
const command = message.split(' ')[0]
Expand Down
11 changes: 5 additions & 6 deletions src/core/db.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Env, TelegramUpdate } from "./type"
import { Env } from "./type"
import { Update } from 'grammy/types'

/**
* Inserts the Telegram update data into the database.
Expand All @@ -7,8 +8,9 @@ import { Env, TelegramUpdate } from "./type"
* @param env - The environment object.
* @returns A promise that resolves when the data is successfully inserted into the database.
*/
export async function syncToDatabase(update: TelegramUpdate, env: Env) {
export async function syncToDatabase(update: Update, env: Env) {
console.log('syncToDatabase', JSON.stringify(update, null, 2))
if (!update.message) return

await env.DB.prepare(`
INSERT INTO telegram_messages (
Expand Down Expand Up @@ -68,10 +70,7 @@ export async function syncToDatabase(update: TelegramUpdate, env: Env) {
update.message.reply_to_message?.sender_chat?.title || null,
update.message.reply_to_message?.sender_chat?.type || null,
update.message.reply_to_message?.date || null,
update.message.forward_from_chat?.id || null,
update.message.forward_from_chat?.title || null,
update.message.forward_from_chat?.type || null,
update.message.forward_from_message_id || null,
null, null, null, null,
update.message.media_group_id || null,
update.message.photo?.length ? update.message.photo[update.message.photo.length - 1].file_id : null,
update.message.caption || null,
Expand Down
16 changes: 9 additions & 7 deletions src/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@

import telegramifyMarkdown from "telegramify-markdown"
import { Env, TelegramUpdate } from "./type"
import { Env } from "./type"
import { Update } from 'grammy/types'
import { syncToDatabase } from "./db"


// Process the Telegram update received
export async function handleTelegramUpdate(update: TelegramUpdate, env: Env, handler: () => Promise<string | undefined>) {
export async function handleTelegramUpdate(update: Update, env: Env, handler: () => Promise<string | undefined>) {
if (!update.message) return
let replyText: string | undefined

try {
Expand All @@ -31,7 +33,7 @@ export async function handleTelegramUpdate(update: TelegramUpdate, env: Env, han
}

// Process the '/getgroupid' command
export async function processGetGroupIdCommand(update: TelegramUpdate, env: Env): Promise<string> {
export async function processGetGroupIdCommand(update: Update, env: Env): Promise<string> {
const fromUsername = update.message?.from?.username || ''
const formFirstName = update.message?.from?.first_name || ''
let replyName = fromUsername ? `@${fromUsername}` : formFirstName
Expand All @@ -46,7 +48,7 @@ export async function processGetGroupIdCommand(update: TelegramUpdate, env: Env)
}

// Process the '/getuserid' command
export async function processGetUserIdCommand(update: TelegramUpdate, env: Env): Promise<string> {
export async function processGetUserIdCommand(update: Update, env: Env): Promise<string> {
const fromUsername = update.message?.from?.username || ''
const formFirstName = update.message?.from?.first_name || ''
let replyName = fromUsername ? `@${fromUsername}` : formFirstName
Expand All @@ -58,20 +60,20 @@ export async function processGetUserIdCommand(update: TelegramUpdate, env: Env):
const username = update.message?.sender_chat?.username || ''
const title = update.message?.sender_chat?.title || ''
replyName = username ? `@${username}` : title
id = update.message?.sender_chat?.id.toString() || ''
id = update.message?.sender_chat?.id || 0
}

return `呀~ ${replyName} ,您的 ID 是 \`${id}\` 哦!ヽ(^Д^)ノ`
}

// Process the '/ping' command
export async function processPingCommand(update: TelegramUpdate, env: Env): Promise<string> {
export async function processPingCommand(update: Update, env: Env): Promise<string> {
// Show more information about this chat
return JSON.stringify(update.message?.chat, null, 2)
}

// Process the '/debug' command
async function processDebugCommand(update: TelegramUpdate, env: Env): Promise<string> {
async function processDebugCommand(update: Update, env: Env): Promise<string> {
// Show more information about this update
return JSON.stringify(update, null, 2)
}
Expand Down
47 changes: 0 additions & 47 deletions src/core/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,50 +4,3 @@ export type Env = {
ALLOW_USER_IDS: string[]
DB: D1Database
}

export interface TelegramUpdate {
update_id: number // Update ID from Telegram
message: TelegramMessage // Message object, optional
inline_query: any
// 添加更多的更新相关字段| Add more update related fields
}

interface TelegramChat {
id: number // Chat ID
title?: string // Chat title, optional
username?: string // Username, optional
type: string // Type of chat, one of "private", "group", "supergroup" or "channel"
// 添加更多的聊天相关字段 | Add more chat related fields
}

interface TelegramPhoto {
file_id: string // 可用于获取文件内容 | Can be used to get file content
file_unique_id: string // 文件的唯一标识符 | Unique identifier for this file
width: number // 图片宽度 | Image width
height: number // 图片高度 | Image height
file_size?: number // 文件大小(可选) | File size (optional)
}

export interface TelegramMessage {
message_id: number // Message ID
chat: TelegramChat // Chat object
text?: string // Received message text, optional
reply_to_message?: TelegramMessage // 添加这个字段来获取回复的消息 | Add this field to get the replied message
from: {
username: string // 发送者的用户名 | Sender's username
id: string // 发送者的ID | Sender's ID
first_name: string // 发送者的名字 | Sender's first name
},
sender_chat?: TelegramChat // Sender's chat object, optional
caption?: string
photo?: TelegramPhoto[] // TelegramPhoto需要根据API定义 | TelegramPhoto needs to be defined according to the API
forward_from_chat?: TelegramChat // Forwarded from chat object, optional
forward_from_message_id?: number // Forwarded from message ID, optional
media_group_id?: string // Media group ID
quote?: {
text: string
is_manual?: boolean
}
date: number // Unix timestamp
// 添加更多的消息相关字段 | Add more message related fields
}
6 changes: 4 additions & 2 deletions src/core/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Env, TelegramMessage } from "./type"
import { Env } from "./type"
import { Message } from "grammy/types"


/**
* Retrieves the URL list of Telegram photos from a given message.
Expand All @@ -8,7 +10,7 @@ import { Env, TelegramMessage } from "./type"
* @param env - The environment object containing necessary configurations.
* @returns A promise that resolves to an array of photo URLs.
*/
export async function getTelegramPhotoUrlList(message: TelegramMessage, env: Env): Promise<string[]> {
export async function getTelegramPhotoUrlList(message: Message, env: Env): Promise<string[]> {
let photoIdList = []
if (!message.media_group_id) {
if (message.photo?.length) {
Expand Down
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { processSyncXLogCommand } from './xlog'
import twitter from './twitter'
import { processChannel } from './channel'

import { TelegramUpdate } from './core/type'
import { Env as LLMEnv } from './llm'
import { Env as XLogEnv } from './xlog'
import { Env as TwitterEnv } from './twitter'
import { Update } from 'grammy/types'

export type Env = LLMEnv & XLogEnv & TwitterEnv

async function handler(update: TelegramUpdate, env: Env): Promise<string | undefined> {
async function handler(update: Update, env: Env): Promise<string | undefined> {
const content = update.message?.text || update.message?.caption || ''

if (content.startsWith('/getchatid')) {
Expand Down Expand Up @@ -41,7 +41,7 @@ export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if (request.method === 'POST') {
try {
const update = await request.json() as TelegramUpdate
const update = await request.json() as Update
await handleTelegramUpdate(update, env, async () => {
return await handler(update, env)
})
Expand Down
10 changes: 6 additions & 4 deletions src/llm/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import OpenAI from "openai"
import { ChatCompletionContentPart, ChatCompletionMessageParam } from 'openai/resources'
import { TelegramMessage, TelegramUpdate, Env as CoreEnv } from "@/core/type"
import { Env as CoreEnv } from "@/core/type"
import { getTelegramPhotoUrlList } from "@/core/utils"
import { Update, Message } from "grammy/types"

export type Env = {
OPENAI_API_KEY: string
Expand All @@ -14,9 +15,10 @@ export type Env = {
* @param env - The environment object containing the OpenAI API key.
* @returns A promise that resolves to a string representing the generated response.
*/
export async function processLLM(update: TelegramUpdate, env: Env): Promise<string> {
export async function processLLM(update: Update, env: Env): Promise<string> {
if (!update.message) return ''
const content = update.message?.text || update.message?.caption || ''
const replyName = update.message?.reply_to_message?.from.username || ''
const replyName = update.message?.reply_to_message?.from?.username || ''
console.log(`content: ${content}, replyName: ${JSON.stringify(update.message)}`)

if (!content.includes(`@${env.TELEGRAM_BOT_USERNAME}`) && replyName !== env.TELEGRAM_BOT_USERNAME) {
Expand Down Expand Up @@ -73,7 +75,7 @@ export async function processLLM(update: TelegramUpdate, env: Env): Promise<stri
* @param env The environment configuration.
* @returns A promise that resolves to an array of ChatCompletionContentPart objects or a string.
*/
async function messageToContentPart(message: TelegramMessage | undefined, env: Env): Promise<ChatCompletionContentPart[] | string> {
async function messageToContentPart(message: Message | undefined, env: Env): Promise<ChatCompletionContentPart[] | string> {
if (!message) return ""

if (!message.photo?.length) {
Expand Down
5 changes: 3 additions & 2 deletions src/twitter/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import OAuth from 'oauth-1.0a'
import { HmacSHA1, enc } from 'crypto-js'
import { Buffer } from 'node:buffer'
import { Env as CoreEnv, TelegramUpdate } from "@/core/type"
import { Env as CoreEnv } from "@/core/type"
import { getTelegramPhotoUrlList } from '@/core/utils'
import { Update } from 'grammy/types'

export type Env = {
TWITTER_API_KEY: string
Expand All @@ -28,7 +29,7 @@ interface TwitterResponse {
* @param env - The environment variables.
* @returns A promise that resolves to a string indicating the result of the sync operation.
*/
async function processSyncTwitterCommand(update: TelegramUpdate, env: Env): Promise<string> {
async function processSyncTwitterCommand(update: Update, env: Env): Promise<string> {
const allowedUserList = env.ALLOW_USER_IDS
let fromUserId = update.message?.from?.id.toString() || ''
let fromUsername = update.message?.from?.username || ''
Expand Down
5 changes: 3 additions & 2 deletions src/xlog/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ipfsUploadFile } from "crossbell/ipfs"
import { Env as CoreEnv, TelegramUpdate } from "@/core/type"
import { Env as CoreEnv } from "@/core/type"
import { getTelegramPhotoUrlList } from "@/core/utils"
import { Update } from "grammy/types"

export type Env = {
XLOG_TOKEN: string
Expand All @@ -14,7 +15,7 @@ export type Env = {
* @param env - The environment object.
* @returns A promise that resolves to a string indicating the result of the sync operation.
*/
export async function processSyncXLogCommand(update: TelegramUpdate, env: Env): Promise<string> {
export async function processSyncXLogCommand(update: Update, env: Env): Promise<string> {

const allowedUserList = env.ALLOW_USER_IDS
let fromUserId = update.message?.from?.id.toString() || ''
Expand Down

0 comments on commit ac8e2c2

Please sign in to comment.