Skip to content

Commit

Permalink
refactor: 使用TBXark/telegram-bot-api-types重构telegram相关代码
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Aug 24, 2024
1 parent 688ecda commit 7fb7071
Show file tree
Hide file tree
Showing 19 changed files with 324 additions and 343 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"eslint": "^9.8.0",
"eslint-plugin-format": "^0.1.2",
"rollup-plugin-cleanup": "^3.2.1",
"telegram-bot-api-types": "^7.9.1",
"typescript": "^5.5.4",
"vite": "^5.2.10",
"vite-plugin-checker": "^0.7.2",
Expand Down
15 changes: 6 additions & 9 deletions src/config/context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TelegramChatType, TelegramMessage } from '../types/telegram';
import type { Telegram } from '../types/telegram';
import { DATABASE, ENV, mergeEnvironment } from './env';
import type { AgentUserConfig } from './config';

Expand All @@ -14,14 +14,13 @@ export class ShareContext {
groupAdminKey: string | null;
usageKey: string;

chatType: TelegramChatType;
chatType: string;
chatId: number;
speakerId: number;

extraMessageContext: TelegramMessage | null = null;
allMemberAreAdmin: boolean = false;
extraMessageContext: Telegram.Message | null = null;

constructor(token: string, message: TelegramMessage) {
constructor(token: string, message: Telegram.Message) {
const botId = Number.parseInt(token.split(':')[0]);

const telegramIndex = ENV.TELEGRAM_AVAILABLE_TOKENS.indexOf(token);
Expand Down Expand Up @@ -87,7 +86,6 @@ export class ShareContext {
this.chatType = message.chat?.type;
this.chatId = message.chat.id;
this.speakerId = message.from?.id || message.chat.id;
this.allMemberAreAdmin = message?.chat.all_members_are_administrators || false;
}
}

Expand All @@ -96,11 +94,10 @@ export class CurrentChatContext {
message_id: number | null = null; // 当前发生的消息,用于后续编辑
reply_to_message_id: number | null;
parse_mode: string | null = ENV.DEFAULT_PARSE_MODE;
reply_markup: any = null;
allow_sending_without_reply: boolean | null = null;
disable_web_page_preview: boolean | null = null;

constructor(message: TelegramMessage) {
constructor(message: Telegram.Message) {
this.chat_id = message.chat.id;
if (message.chat.type === 'group' || message.chat.type === 'supergroup') {
this.reply_to_message_id = message.message_id;
Expand All @@ -123,7 +120,7 @@ export class WorkerContext {
this.SHARE_CONTEXT = SHARE_CONTEXT;
}

static async from(token: string, message: TelegramMessage): Promise<WorkerContext> {
static async from(token: string, message: Telegram.Message): Promise<WorkerContext> {
const SHARE_CONTEXT = new ShareContext(token, message);
const CURRENT_CHAT_CONTEXT = new CurrentChatContext(message);
const USER_CONFIG = Object.assign({}, ENV.USER_CONFIG);
Expand Down
11 changes: 6 additions & 5 deletions src/route/route.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { handleMessage } from '../telegram/handler';
import { API_GUARD, ENV } from '../config/env';
import { commandsBindScope, commandsDocument } from '../telegram/command';
import { bindTelegramWebHook, setMyCommands } from '../telegram/api/telegram';
import type { RouterRequest } from '../utils/router';
import { Router } from '../utils/router';
import type { TelegramWebhookRequest } from '../types/telegram';
import type { Telegram } from '../types/telegram';
import { TelegramBotAPI } from '../telegram/api/api';
import { errorToString, makeResponse200, renderHTML } from './utils';

const helpLink = 'https://github.com/TBXark/ChatGPT-Telegram-Workers/blob/master/doc/en/DEPLOY.md';
Expand All @@ -23,12 +23,13 @@ async function bindWebHookAction(request: RouterRequest): Promise<Response> {
const hookMode = API_GUARD ? 'safehook' : 'webhook';
const scope = commandsBindScope();
for (const token of ENV.TELEGRAM_AVAILABLE_TOKENS) {
const api = new TelegramBotAPI(token);
const url = `https://${domain}/telegram/${token.trim()}/${hookMode}`;
const id = token.split(':')[0];
result[id] = {};
result[id].webhook = await bindTelegramWebHook(token, url).then(res => res.json()).catch(e => errorToString(e));
result[id].webhook = await api.setWebhook({ url }).then(res => res.json()).catch(e => errorToString(e));
for (const [s, data] of Object.entries(scope)) {
result[id][s] = await setMyCommands(data, token).then(res => res.json()).catch(e => errorToString(e));
result[id][s] = await api.setMyCommands(data).then(res => res.json()).catch(e => errorToString(e));
}
}
let html = `<h1>ChatGPT-Telegram-Workers</h1>`;
Expand All @@ -51,7 +52,7 @@ async function bindWebHookAction(request: RouterRequest): Promise<Response> {
async function telegramWebhook(request: RouterRequest): Promise<Response> {
try {
const { token } = request.params as any;
const body = await request.json() as TelegramWebhookRequest;
const body = await request.json() as Telegram.Update;
return makeResponse200(await handleMessage(token, body));
} catch (e) {
console.error(e);
Expand Down
102 changes: 102 additions & 0 deletions src/telegram/api/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import type { Telegram } from '../../types/telegram';

export class TelegramBotAPI implements
Telegram.SendMessageRequest,
Telegram.EditMessageTextRequest,
Telegram.SendPhotoRequest,
Telegram.SendChatActionRequest,
Telegram.SetWebhookRequest,
Telegram.DeleteWebhookRequest,
Telegram.SetMyCommandsRequest,
Telegram.GetMeRequest,
Telegram.GetFileRequest,
Telegram.GetChatAdministratorsRequest,
Telegram.GetUpdatesRequest {
readonly token: string;
readonly baseURL: string = `https://api.telegram.org/`;

constructor(token: string, baseURL?: string) {
this.token = token;
if (baseURL) {
this.baseURL = baseURL;
}
}

static from(token: string, baseURL?: string): TelegramBotAPI {
return new TelegramBotAPI(token, baseURL);
}

jsonRequest<T>(method: Telegram.TelegramBotMethod, params: T): Promise<Response> {
return fetch(`${this.baseURL}bot${this.token}/${method}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(params),
});
}

formDataRequest<T>(method: Telegram.TelegramBotMethod, params: T): Promise<Response> {
const formData = new FormData();
for (const key in params) {
const value = params[key];
if (value instanceof File) {
formData.append(key, value, value.name);
} else if (value instanceof Blob) {
formData.append(key, value, 'blob');
} else if (typeof value === 'string') {
formData.append(key, value);
} else {
formData.append(key, JSON.stringify(value));
}
}
return fetch(`${this.baseURL}bot${this.token}/${method}`, {
method: 'POST',
body: formData,
});
}

sendMessage(params: Telegram.SendMessageParams): Promise<Response> {
return this.jsonRequest('sendMessage', params);
}

editMessageText(params: Telegram.EditMessageTextParams): Promise<Response> {
return this.jsonRequest('editMessageText', params);
}

sendPhoto(params: Telegram.SendPhotoParams): Promise<Response> {
return this.formDataRequest('sendPhoto', params);
}

sendChatAction(params: Telegram.SendChatActionParams): Promise<Response> {
return this.jsonRequest('sendChatAction', params);
}

setWebhook(params: Telegram.SetWebhookParams): Promise<Response> {
return this.jsonRequest('setWebhook', params);
}

deleteWebhook(): Promise<Response> {
return this.jsonRequest('deleteWebhook', {});
}

setMyCommands(params: Telegram.SetMyCommandsParams): Promise<Response> {
return this.jsonRequest('setMyCommands', params);
}

getMe(): Promise<Response> {
return this.jsonRequest('getMe', {});
}

getFile(params: Telegram.GetFileParams): Promise<Response> {
return this.jsonRequest('getFile', params);
}

getChatAdministrators(params: Telegram.GetChatAdministratorsParams): Promise<Response> {
return this.jsonRequest('getChatAdministrators', params);
}

getUpdates(params: Telegram.GetUpdatesParams): Promise<Response> {
return this.jsonRequest('getUpdates', params);
}
}
168 changes: 0 additions & 168 deletions src/telegram/api/telegram.ts

This file was deleted.

Loading

0 comments on commit 7fb7071

Please sign in to comment.