Skip to content

Commit

Permalink
merge: pull request #245 from TBXark/dev
Browse files Browse the repository at this point in the history
merge: 修复部分BUG
  • Loading branch information
TBXark committed May 10, 2024
2 parents 8434ab9 + d027b36 commit 0db58ae
Show file tree
Hide file tree
Showing 26 changed files with 386 additions and 451 deletions.
22 changes: 0 additions & 22 deletions .eslintrc.cjs

This file was deleted.

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,4 @@ out
/wrangler.toml
/wrangler-test.toml
.vercel
.wrangler
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ clean:

.PHONY: lint
lint:
$(ESLINT) --fix --ext .js,.jsx,.mjs main.js src adapter
$(ESLINT) --fix main.js src adapter
1 change: 0 additions & 1 deletion adapter/docker/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable require-jsdoc */
import adapter from 'cloudflare-worker-adapter';
import {SqliteCache} from 'cloudflare-worker-adapter/cache/sqlite.js';
import worker from 'cloudflare-worker-adapter';
Expand Down
4 changes: 3 additions & 1 deletion adapter/local/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable require-jsdoc */
import adapter, {bindGlobal} from 'cloudflare-worker-adapter';
import {MemoryCache} from 'cloudflare-worker-adapter/cache/memory.js';
import fs from 'fs';
Expand All @@ -13,14 +12,17 @@ const config = JSON.parse(fs.readFileSync('./config.json', 'utf-8'));
let cache = new MemoryCache();
switch (config?.database?.type) {
case 'local':
// eslint-disable-next-line no-case-declarations
const {LocalCache} = await import('cloudflare-worker-adapter/cache/local.js');
cache = new LocalCache(config.database.uri);
break;
case 'sqlite':
// eslint-disable-next-line no-case-declarations
const {SqliteCache} = await import('cloudflare-worker-adapter/cache/sqlite.js');
cache = new SqliteCache(config.database.uri);
break;
case 'redis':
// eslint-disable-next-line no-case-declarations
const {RedisCache} = await import('cloudflare-worker-adapter/cache/redis.js');
cache = new RedisCache(config.database.uri);
break;
Expand Down
1 change: 0 additions & 1 deletion adapter/render/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable require-jsdoc */
import fs from 'fs';
import adapter from 'cloudflare-worker-adapter';
import {RedisCache} from 'cloudflare-worker-adapter/cache/redis.js';
Expand Down
1 change: 0 additions & 1 deletion adapter/vercel/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable require-jsdoc */
import worker from 'chatgpt-telegram-workers';
import {RedisCache} from 'cloudflare-worker-adapter/cache/redis.js';

Expand Down
1 change: 0 additions & 1 deletion adapter/vercel/utils/env.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable require-jsdoc */
import fs from 'fs';
import dotenv from 'dotenv';

Expand Down
2 changes: 1 addition & 1 deletion adapter/vercel/utils/init.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/* eslint-disable require-jsdoc */
import fs from 'fs';
import toml from 'toml';
import dotenv from 'dotenv';

const tryWithDefault = (fn, defaultValue) => {
try {
return fn();
// eslint-disable-next-line no-unused-vars
} catch (e) {
return defaultValue;
}
Expand Down
2 changes: 1 addition & 1 deletion dist/buildinfo.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"sha": "8a48d6a", "timestamp": 1709018751}
{"sha": "cb00fc1", "timestamp": 1715320133}
50 changes: 30 additions & 20 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ var Environment = class {
// -- 版本数据 --
//
// 当前版本
BUILD_TIMESTAMP = 1709018751;
BUILD_TIMESTAMP = 1715320133;
// 当前版本 commit id
BUILD_VERSION = "8a48d6a";
BUILD_VERSION = "cb00fc1";
// -- 基础配置 --
/**
* @type {I18n | null}
Expand All @@ -17,6 +17,8 @@ var Environment = class {
UPDATE_BRANCH = "master";
// AI提供商: auto, openai, azure, workers, gemini, mistral
AI_PROVIDER = "auto";
// AI图片提供商: auto, openai, azure, workers
AI_IMAGE_PROVIDER = "auto";
// -- Telegram 相关 --
//
// Telegram API Domain
Expand Down Expand Up @@ -231,6 +233,8 @@ var Context = class {
DEFINE_KEYS: [],
// AI提供商
AI_PROVIDER: ENV.AI_PROVIDER,
// AI图片提供商
AI_IMAGE_PROVIDER: ENV.AI_IMAGE_PROVIDER,
// 聊天模型
CHAT_MODEL: ENV.CHAT_MODEL,
// OenAI API Key
Expand Down Expand Up @@ -337,14 +341,15 @@ var Context = class {
async _initUserConfig(storeKey) {
try {
const userConfig = JSON.parse(await DATABASE.get(storeKey));
const keys = userConfig?.DEFINE_KEYS || [];
let keys = userConfig?.DEFINE_KEYS || [];
this.USER_CONFIG.DEFINE_KEYS = keys;
const userDefine = "USER_DEFINE";
keys = keys.filter((key) => key !== userDefine);
mergeObject(this.USER_CONFIG, userConfig, keys);
if (userConfig[userDefine]) {
mergeObject(this.USER_DEFINE, userConfig[userDefine], this.USER_DEFINE.VALID_KEYS);
delete userConfig[userDefine];
}
mergeObject(this.USER_CONFIG, userConfig, keys);
} catch (e) {
console.error(e);
}
Expand All @@ -354,6 +359,12 @@ var Context = class {
this.USER_CONFIG.AI_PROVIDER = "auto";
}
}
{
const aiImageProvider = new Set("auto,openai,azure,workers".split(","));
if (!aiImageProvider.has(this.USER_CONFIG.AI_IMAGE_PROVIDER)) {
this.USER_CONFIG.AI_IMAGE_PROVIDER = "auto";
}
}
}
/**
* @param {Request} request
Expand Down Expand Up @@ -1137,7 +1148,7 @@ async function requestCompletionsFromOpenAI(message, history, context, onStream)
"Content-Type": "application/json",
"Authorization": `Bearer ${openAIKeyFromContext(context)}`
};
return requestCompletionsFromOpenAILikes(url, header, body, context, onStream, (result) => {
return requestCompletionsFromOpenAICompatible(url, header, body, context, onStream, (result) => {
setTimeout(() => updateBotUsage(result?.usage, context).catch(console.error), 0);
});
}
Expand All @@ -1152,9 +1163,9 @@ async function requestCompletionsFromAzureOpenAI(message, history, context, onSt
"Content-Type": "application/json",
"api-key": azureKeyFromContext(context)
};
return requestCompletionsFromOpenAILikes(url, header, body, context, onStream);
return requestCompletionsFromOpenAICompatible(url, header, body, context, onStream);
}
async function requestCompletionsFromOpenAILikes(url, header, body, context, onStream, onResult = null) {
async function requestCompletionsFromOpenAICompatible(url, header, body, context, onStream, onResult = null) {
const controller = new AbortController();
const { signal } = controller;
const timeout = 1e3 * 60 * 5;
Expand Down Expand Up @@ -1414,7 +1425,7 @@ async function requestCompletionsFromMistralAI(message, history, context, onStre
"Content-Type": "application/json",
"Authorization": `Bearer ${context.USER_CONFIG.MISTRAL_API_KEY}`
};
return requestCompletionsFromOpenAILikes(url, header, body, context, onStream);
return requestCompletionsFromOpenAICompatible(url, header, body, context, onStream);
}

// src/llm.js
Expand Down Expand Up @@ -1514,7 +1525,7 @@ function loadChatLLM(context) {
}
}
function loadImageGen(context) {
switch (context.USER_CONFIG.AI_PROVIDER) {
switch (context.USER_CONFIG.AI_IMAGE_PROVIDER) {
case "openai":
return requestImageFromOpenAI;
case "azure":
Expand Down Expand Up @@ -1709,7 +1720,7 @@ async function commandUpdateRole(message, command, subcommand, context) {
}
let showMsg = ENV.I18N.command.role.current_defined_role(size);
for (const role2 in context.USER_DEFINE.ROLE) {
if (context.USER_DEFINE.ROLE.hasOwnProperty(role2)) {
if (Object.prototype.hasOwnProperty.call(context.USER_DEFINE.ROLE, role2)) {
showMsg += `~${role2}:
<pre>`;
showMsg += JSON.stringify(context.USER_DEFINE.ROLE[role2]) + "\n";
Expand Down Expand Up @@ -1869,13 +1880,9 @@ async function commandDeleteUserConfig(message, command, subcommand, context) {
}
}
async function commandClearUserConfig(message, command, subcommand, context) {
if (ENV.LOCK_USER_CONFIG_KEYS.includes(subcommand)) {
const msg = ENV.I18N.command.setenv.update_config_error(new Error(`Key ${subcommand} is locked`));
return sendMessageToTelegramWithContext(context)(msg);
}
try {
context.USER_CONFIG.DEFINE_KEYS = [];
context.USER_CONFIG[subcommand] = null;
context.USER_CONFIG = {};
await DATABASE.put(
context.SHARE_CONTEXT.configStoreKey,
JSON.stringify({})
Expand Down Expand Up @@ -1961,6 +1968,9 @@ async function commandRegenerate(message, command, subcommand, context) {
const mf = (history, text) => {
const { real, original } = history;
let nextText = text;
if (!real || !original || real.length === 0 || original.length === 0) {
throw new Error(ENV.I18N.command.help.redo);
}
while (true) {
const data = real.pop();
original.pop();
Expand Down Expand Up @@ -2040,7 +2050,7 @@ async function bindCommandForTelegram(token) {
if (ENV.HIDE_COMMAND_BUTTONS.includes(key)) {
continue;
}
if (commandHandlers.hasOwnProperty(key) && commandHandlers[key].scopes) {
if (Object.prototype.hasOwnProperty.call(commandHandlers, key) && commandHandlers[key].scopes) {
for (const scope of commandHandlers[key].scopes) {
if (!scopeCommandMap[scope]) {
scopeCommandMap[scope] = [];
Expand Down Expand Up @@ -2237,12 +2247,12 @@ async function msgHandleRole(message, context) {
}
const role = message.text.slice(0, kv);
const msg = message.text.slice(kv + 1).trim();
if (context.USER_DEFINE.ROLE.hasOwnProperty(role)) {
if (Object.prototype.hasOwnProperty.call(context.USER_DEFINE.ROLE, role)) {
context.SHARE_CONTEXT.role = role;
message.text = msg;
const roleConfig = context.USER_DEFINE.ROLE[role];
for (const key in roleConfig) {
if (context.USER_CONFIG.hasOwnProperty(key) && typeof context.USER_CONFIG[key] === typeof roleConfig[key]) {
if (Object.prototype.hasOwnProperty.call(context.USER_CONFIG, key) && typeof context.USER_CONFIG[key] === typeof roleConfig[key]) {
if (ENV.LOCK_USER_CONFIG_KEYS.includes(key)) {
continue;
}
Expand Down Expand Up @@ -2279,7 +2289,7 @@ async function msgProcessByChatType(message, context) {
msgHandleRole
]
};
if (!handlerMap.hasOwnProperty(context.SHARE_CONTEXT.chatType)) {
if (!Object.prototype.hasOwnProperty.call(handlerMap, context.SHARE_CONTEXT.chatType)) {
return sendMessageToTelegramWithContext(context)(
ENV.I18N.message.not_supported_chat_type(context.SHARE_CONTEXT.chatType)
);
Expand Down Expand Up @@ -2349,7 +2359,7 @@ async function handleMessage(request) {
}

// src/router.js
var helpLink = "https://github.com/TBXark/ChatGPT-Telegram-Workers/blob/master/doc/DEPLOY.md";
var helpLink = "https://github.com/TBXark/ChatGPT-Telegram-Workers/blob/master/doc/en/DEPLOY.md";
var issueLink = "https://github.com/TBXark/ChatGPT-Telegram-Workers/issues";
var initLink = "./init";
var footer = `
Expand Down
2 changes: 1 addition & 1 deletion dist/timestamp
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1709018751
1715320133
8 changes: 8 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import globals from "globals";
import pluginJs from "@eslint/js";


export default [
{languageOptions: { globals: {...globals.browser, ...globals.node} }},
pluginJs.configs.recommended,
];
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
"deploy:build": "npm run build && wrangler deploy"
},
"devDependencies": {
"@eslint/js": "^9.1.1",
"esbuild": "^0.17.11",
"eslint": ">=5.16.0",
"eslint-config-google": "^0.14.0",
"eslint": "^9.1.1",
"globals": "^15.1.0",
"wrangler": "^3.0.0"
},
"exports": {
Expand Down
15 changes: 7 additions & 8 deletions src/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ async function commandUpdateRole(message, command, subcommand, context) {
}
let showMsg = ENV.I18N.command.role.current_defined_role(size);
for (const role in context.USER_DEFINE.ROLE) {
if (context.USER_DEFINE.ROLE.hasOwnProperty(role)) {
if (Object.prototype.hasOwnProperty.call(context.USER_DEFINE.ROLE, role)) {
showMsg+=`~${role}:\n<pre>`;
showMsg+=JSON.stringify(context.USER_DEFINE.ROLE[role])+'\n';
showMsg+='</pre>';
Expand Down Expand Up @@ -367,13 +367,9 @@ async function commandDeleteUserConfig(message, command, subcommand, context) {
* @return {Promise<Response>}
*/
async function commandClearUserConfig(message, command, subcommand, context) {
if (ENV.LOCK_USER_CONFIG_KEYS.includes(subcommand)) {
const msg = ENV.I18N.command.setenv.update_config_error(new Error(`Key ${subcommand} is locked`));
return sendMessageToTelegramWithContext(context)(msg);
}
try {
context.USER_CONFIG.DEFINE_KEYS = [];
context.USER_CONFIG[subcommand] = null;
context.USER_CONFIG = {};
await DATABASE.put(
context.SHARE_CONTEXT.configStoreKey,
JSON.stringify({}),
Expand Down Expand Up @@ -506,6 +502,9 @@ async function commandRegenerate(message, command, subcommand, context) {
const mf = (history, text) => {
const {real, original} = history;
let nextText = text;
if (!real || !original || real.length === 0 || original.length === 0) {
throw new Error(ENV.I18N.command.help.redo);
}
while (true) {
const data = real.pop();
original.pop();
Expand Down Expand Up @@ -611,7 +610,7 @@ export async function bindCommandForTelegram(token) {
if (ENV.HIDE_COMMAND_BUTTONS.includes(key)) {
continue;
}
if (commandHandlers.hasOwnProperty(key) && commandHandlers[key].scopes) {
if (Object.prototype.hasOwnProperty.call(commandHandlers, key) && commandHandlers[key].scopes) {
for (const scope of commandHandlers[key].scopes) {
if (!scopeCommandMap[scope]) {
scopeCommandMap[scope] = [];
Expand All @@ -622,7 +621,7 @@ export async function bindCommandForTelegram(token) {
}

const result = {};
for (const scope in scopeCommandMap) { // eslint-disable-line
for (const scope in scopeCommandMap) {
result[scope] = await fetch(
`https://api.telegram.org/bot${token}/setMyCommands`,
{
Expand Down
15 changes: 12 additions & 3 deletions src/context.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {CONST, DATABASE, ENV} from './env.js';
// eslint-disable-next-line no-unused-vars
import './type.js';


Expand Down Expand Up @@ -32,6 +32,8 @@ export class Context {

// AI提供商
AI_PROVIDER: ENV.AI_PROVIDER,
// AI图片提供商
AI_IMAGE_PROVIDER: ENV.AI_IMAGE_PROVIDER,

// 聊天模型
CHAT_MODEL: ENV.CHAT_MODEL,
Expand Down Expand Up @@ -135,14 +137,15 @@ export class Context {
async _initUserConfig(storeKey) {
try {
const userConfig = JSON.parse(await DATABASE.get(storeKey));
const keys = userConfig?.DEFINE_KEYS || [];
let keys = userConfig?.DEFINE_KEYS || [];
this.USER_CONFIG.DEFINE_KEYS = keys;
const userDefine = 'USER_DEFINE';
keys = keys.filter((key) => key !== userDefine);
mergeObject(this.USER_CONFIG, userConfig, keys);
if (userConfig[userDefine]) {
mergeObject(this.USER_DEFINE, userConfig[userDefine], this.USER_DEFINE.VALID_KEYS);
delete userConfig[userDefine];
}
mergeObject(this.USER_CONFIG, userConfig, keys);
} catch (e) {
console.error(e);
}
Expand All @@ -152,6 +155,12 @@ export class Context {
this.USER_CONFIG.AI_PROVIDER = 'auto';
}
}
{
const aiImageProvider = new Set('auto,openai,azure,workers'.split(','));
if (!aiImageProvider.has(this.USER_CONFIG.AI_IMAGE_PROVIDER)) {
this.USER_CONFIG.AI_IMAGE_PROVIDER = 'auto';
}
}
}


Expand Down
Loading

0 comments on commit 0db58ae

Please sign in to comment.