├── README.md ├── api └── telegram.js ├── docs ├── README.de.md ├── README.es.md ├── README.fr.md ├── README.ja.md ├── README.ru.md ├── README.zh-cn.md └── README.zh-hant.md ├── locales ├── de.json ├── en.json ├── es.json ├── fr.json ├── ja.json ├── ru.json ├── zh-cn.json └── zh-hant.json ├── package.json ├── public └── index.html ├── src ├── api.js ├── azureOpenAI.js ├── bot.js ├── claude.js ├── config.js ├── geminiApi.js ├── generateImage.js ├── groqapi.js ├── localization.js ├── redis.js └── uploadHandler.js └── vercel.json /README.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot: Multifunctional AI Assistant 🤖💬 2 | 3 | [English](./README.md) | [简体中文](./docs/README.zh-cn.md) | [繁體中文](./docs/README.zh-hant.md) | [日本語](./docs/README.ja.md) | [Español](./docs/README.es.md) | [Français](./docs/README.fr.md) | [Русский](./docs/README.ru.md) | [Deutsch](./docs/README.de.md) 4 | 5 | GPT-Telegram-Bot is a powerful Telegram bot that integrates various AI models, providing intelligent conversations, image generation and analysis capabilities. 6 | 7 | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## Main Features 🌟 10 | 11 | 1. **Multi-model Support** 🎭: Any model compatible with OpenAI API, Google Gemini, Anthropic Claude, Groq, and Azure OpenAI 12 | 2. **Intelligent Conversations** 💬: Natural language interactions with context memory support 13 | 3. **Image Generation** 🎨: Create images based on text descriptions 14 | 4. **Image Analysis** 🔍: Interpret and describe uploaded images 15 | 5. **Multilingual Support** 🌐: Localization support for multiple languages 16 | 6. **Stream Response** ⚡: Real-time generation and display of AI replies 17 | 7. **User Whitelist** 🔐: Can be set to allow access only to specific users 18 | 19 | ## Supported AI Models 🧠 20 | 21 | - OpenAI Series: Powerful language models 🚀 22 | - Google Gemini: Google's next-generation AI model 🧑‍🔬 23 | - Anthropic Claude: Another powerful language model choice 🎭 24 | - Groq: High-speed inference AI model ⚡ 25 | - Azure OpenAI: Microsoft-hosted OpenAI service 👔 26 | 27 | ## Project Structure 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # API related configuration 32 | │ ├── telegram.js # Handles Telegram bot interactions 33 | ├── src/ # Source code 34 | │ ├── api.js # Handles interactions with OpenAI compatible APIs 35 | │ ├── bot.js # Main Telegram bot logic 36 | │ ├── config.js # Configuration file 37 | │ ├── azureOpenAI.js # Handles interactions with Azure OpenAI 38 | │ ├── claude.js # Handles interactions with Claude 39 | │ ├── generateImage.js# Handles interactions with DALL·E 40 | │ ├── geminiApi.js # Handles interactions with Gemini 41 | │ ├── groqapi.js # Handles interactions with Groq 42 | │ ├── uploadhandler.js# Handles image upload and analysis logic 43 | │ ├── localization.js # Handles multilingual support 44 | │ ├── redis.js # Upstash Redis database functionality 45 | ├── locales/ # Multilingual support files 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # Multilingual README files 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # Vercel webpage after deployment 63 | │ └── index.html # Webpage entry file 64 | ├── package.json # Project dependencies 65 | ├── vercel.json # Vercel configuration file 66 | └── README.md # Project description file 67 | ``` 68 | 69 | ## Quick Start 🚀 70 | 71 | ### Prerequisites 72 | 73 | - [Vercel](https://vercel.com/) account 74 | - Telegram account and Bot Token 75 | - [Upstash](https://upstash.com/) Please select the Redis database and enable the [Eviction](https://upstash.com/docs/redis/features/eviction) feature 76 | - API key for at least one AI service 77 | 78 | ### Deployment Steps 79 | 80 | 1. Clone the repository: 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. Install dependencies: 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. Configure environment variables: 92 | Create a `.env` file and fill in the necessary configuration information (refer to the environment variable configuration below). 93 | 94 | 4. Deploy to Vercel: 95 | - Fork this repo 96 | - Modify according to the instructions at the bottom of the readme 97 | - Click the "Deploy with Vercel" button 98 | - Connect your GitHub repository 99 | - Configure environment variables 100 | - Complete deployment 101 | 102 | 5. Set up Telegram Webhook: 103 | After deployment, use the following URL to set up the Webhook: 104 | ``` 105 | https://api.telegram.org/bot/setWebhook?url=/api/telegram 106 | ``` 107 | 108 | ## Environment Variable Configuration 🔧 109 | 110 | Before deploying and running GPT-Telegram-Bot, you need to set the following environment variables. Create a `.env` file in the project root directory and configure the following variables: 111 | 112 | | Variable Name | Description | Default Value | 113 | |--------|------|--------| 114 | | `OPENAI_API_KEY` | OpenAI API key | - | 115 | | `OPENAI_BASE_URL` | OpenAI API base URL | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | OpenAI models to use (comma-separated) | - | 117 | | `DEFAULT_MODEL` | Default model to use | First model in OPENAI_MODELS | 118 | | `AZURE_OPENAI_API_KEY` | Azure OpenAI API key | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Azure OpenAI endpoint | - | 120 | | `AZURE_OPENAI_MODELS` | Azure OpenAI models to use (comma-separated) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Telegram Bot Token | - | 122 | | `WHITELISTED_USERS` | Allowed user IDs (comma-separated) | - | 123 | | `DALL_E_MODEL` | DALL-E model to use | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | Upstash Redis REST URL | - | 125 | | `UPSTASH_REST_TOKEN` | Upstash Redis REST Token | - | 126 | | `SYSTEM_INIT_MESSAGE` | System initialization message | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | System message role | system | 128 | | `GEMINI_API_KEY` | Google Gemini API key | - | 129 | | `GOOGLE_MODELS` | Google models to use (comma-separated) | - | 130 | | `GEMINI_ENDPOINT` | Gemini API endpoint | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | Groq API key | - | 132 | | `GROQ_MODELS` | Groq models to use (comma-separated) | - | 133 | | `MAX_HISTORY_LENGTH` | Maximum history length | 50 | 134 | | `CLAUDE_API_KEY` | Anthropic Claude API key | - | 135 | | `CLAUDE_MODELS` | Claude models to use (comma-separated) | - | 136 | | `CLAUDE_ENDPOINT` | Claude API endpoint | https://api.anthropic.com/v1/chat/completions | 137 | 138 | Make sure to add these environment variables to your project's environment configuration when deploying to Vercel or other platforms. 139 | 140 | ## Usage Guide 📖 141 | 142 | - `/start` - Initialize the bot 143 | - `/new` - Start a new conversation 144 | - `/history` - View conversation history summary 145 | - `/help` - Get help information 146 | - `/switchmodel ` - Switch AI model 147 | - `/img [size]` - Generate image 148 | - `/language ` - Switch interface language 149 | - Send an image for analysis 150 | - Send a message directly for conversation 151 | 152 | Supported languages (use /language command): 153 | - English (en) 154 | - Simplified Chinese (zh-cn) 155 | - Traditional Chinese (zh-hant) 156 | - Japanese (ja) 157 | - Spanish (es) 158 | - French (fr) 159 | - Russian (ru) 160 | - German (de) 161 | 162 | ## Notes ⚠️ 163 | 164 | - Use API quotas reasonably, especially when using image features 💸 165 | - Securely store environment variables and API keys 🔒 166 | - Different AI models may have different features and limitations 🔄 167 | - Regularly check and update dependencies to ensure security and performance 🔧 168 | 169 | ## Contribution 🤝 170 | 171 | Welcome to submit Pull Requests or open Issues to improve this project! Your contributions will make this AI assistant more powerful and interesting. 172 | 173 | ## License 📜 174 | 175 | This project is licensed under the [MIT License](https://choosealicense.com/licenses/mit/). 176 | 177 | --- 178 | 179 | About the "Deploy to Vercel" button: 180 | This button provides a one-click deployment to Vercel, which is very convenient. However, please note: 181 | 182 | 1. The link in the button points to the original repository (https://github.com/snakeying/GPT-Telegram-Bot). 183 | 2. If you've forked this project and want to deploy your own version, you need to update this button link in the README. 184 | 3. Update method: Replace `snakeying/GPT-Telegram-Bot` in the link with your GitHub username and repository name. 185 | 186 | For example, if your GitHub username is "yourname", you should change the button link to: 187 | 188 | ```markdown 189 | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fyourname%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | This ensures that the "Deploy to Vercel" button will deploy your forked version, not the original repository. 193 | -------------------------------------------------------------------------------- /api/telegram.js: -------------------------------------------------------------------------------- 1 | const { bot, handleMessage, handleStart, getMessageFromUpdate, updateBotCommands } = require('../src/bot'); 2 | const { Redis } = require('@upstash/redis'); 3 | const { UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN } = require('../src/config'); 4 | 5 | const redis = new Redis({ 6 | url: UPSTASH_REDIS_REST_URL, 7 | token: UPSTASH_REDIS_REST_TOKEN, 8 | }); 9 | 10 | module.exports = async (req, res) => { 11 | console.log('Received webhook request:', JSON.stringify(req.body)); 12 | try { 13 | if (req.method === 'POST') { 14 | const update = req.body; 15 | console.log('Processing update:', JSON.stringify(update)); 16 | 17 | if (update.update_id) { 18 | const key = `processed:${update.update_id}`; 19 | const isProcessed = await redis.get(key); 20 | 21 | if (!isProcessed) { 22 | await redis.set(key, 'true', { ex: 86400 }); 23 | 24 | const message = getMessageFromUpdate(update); 25 | if (message) { 26 | console.log('Handling message:', JSON.stringify(message)); 27 | 28 | // 检查是否是新用户 29 | const userId = message.from.id; 30 | const userKey = `user:${userId}`; 31 | const userExists = await redis.get(userKey); 32 | 33 | if (!userExists) { 34 | console.log(`New user detected: ${userId}`); 35 | await redis.set(userKey, 'true'); 36 | await updateBotCommands(userId); 37 | } 38 | 39 | await handleMessage(update); 40 | console.log('Message handled successfully'); 41 | } else { 42 | console.log('Update does not contain a valid message'); 43 | } 44 | } else { 45 | console.log('Duplicate update, skipping'); 46 | } 47 | } else { 48 | console.log('Missing update_id, skipping'); 49 | } 50 | } else { 51 | console.log('Received non-POST request'); 52 | } 53 | res.status(200).send('OK'); 54 | } catch (error) { 55 | console.error("Error in webhook handler:", error); 56 | res.status(200).json({ 57 | error: 'Internal Server Error', 58 | message: error.message, 59 | stack: error.stack 60 | }); 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /docs/README.de.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot: Multifunktionaler KI-Assistent 🤖💬 2 | 3 | [English](../README.md) | [简体中文](./README.zh-cn.md) | [繁體中文](./README.zh-hant.md) | [日本語](./README.ja.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [Deutsch](./README.de.md) 4 | 5 | GPT-Telegram-Bot ist ein leistungsstarker Telegram-Bot, der verschiedene KI-Modelle integriert und intelligente Konversationen, Bildgenerierung und -analyse ermöglicht. 6 | 7 | [![Mit Vercel bereitstellen](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## Hauptfunktionen 🌟 10 | 11 | 1. **Unterstützung mehrerer Modelle** 🎭: Alle mit OpenAI API kompatiblen Modelle, Google Gemini, Anthropic Claude, Groq und Azure OpenAI 12 | 2. **Intelligente Konversationen** 💬: Natürlichsprachliche Interaktionen mit Kontextgedächtnis-Unterstützung 13 | 3. **Bildgenerierung** 🎨: Erstellung von Bildern basierend auf Textbeschreibungen 14 | 4. **Bildanalyse** 🔍: Interpretation und Beschreibung hochgeladener Bilder 15 | 5. **Mehrsprachige Unterstützung** 🌐: Lokalisierungsunterstützung für mehrere Sprachen 16 | 6. **Echtzeit-Antworten** ⚡: Echtzeit-Generierung und Anzeige von KI-Antworten 17 | 7. **Benutzer-Whitelist** 🔐: Kann so konfiguriert werden, dass nur bestimmte Benutzer Zugriff haben 18 | 19 | ## Unterstützte KI-Modelle 🧠 20 | 21 | - OpenAI-Serie: Leistungsstarke Sprachmodelle 🚀 22 | - Google Gemini: Googles KI-Modell der nächsten Generation 🧑‍🔬 23 | - Anthropic Claude: Eine weitere leistungsstarke Sprachmodell-Option 🎭 24 | - Groq: Hochgeschwindigkeits-Inferenz-KI-Modell ⚡ 25 | - Azure OpenAI: Von Microsoft gehosteter OpenAI-Dienst 👔 26 | 27 | ## Projektstruktur 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # API-bezogene Konfiguration 32 | │ ├── telegram.js # Verarbeitet Telegram-Bot-Interaktionen 33 | ├── src/ # Quellcode 34 | │ ├── api.js # Verarbeitet Interaktionen mit OpenAI-kompatiblen APIs 35 | │ ├── bot.js # Hauptlogik des Telegram-Bots 36 | │ ├── config.js # Konfigurationsdatei 37 | │ ├── azureOpenAI.js # Verarbeitet Interaktionen mit Azure OpenAI 38 | │ ├── claude.js # Verarbeitet Interaktionen mit Claude 39 | │ ├── generateImage.js# Verarbeitet Interaktionen mit DALL·E 40 | │ ├── geminiApi.js # Verarbeitet Interaktionen mit Gemini 41 | │ ├── groqapi.js # Verarbeitet Interaktionen mit Groq 42 | │ ├── uploadhandler.js# Verarbeitet Bild-Upload- und Analyselogik 43 | │ ├── localization.js # Verarbeitet mehrsprachige Unterstützung 44 | │ ├── redis.js # Upstash Redis-Datenbankfunktionalität 45 | ├── locales/ # Mehrsprachige Unterstützungsdateien 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # Mehrsprachige README-Dateien 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # Vercel Webseite nach Bereitstellung 63 | │ └── index.html # Webseite Einstiegsdatei 64 | ├── package.json # Projektabhängigkeiten 65 | ├── vercel.json # Vercel Konfigurationsdatei 66 | └── README.md # Projektbeschreibungsdatei 67 | ``` 68 | 69 | ## Schnellstart 🚀 70 | 71 | ### Voraussetzungen 72 | 73 | - [Vercel](https://vercel.com/)-Konto 74 | - Telegram-Konto und Bot-Token 75 | - [Upstash](https://upstash.com/) Bitte wählen Sie die Redis-Datenbank und aktivieren Sie die [Eviction](https://upstash.com/docs/redis/features/eviction)-Funktion 76 | - API-Schlüssel für mindestens einen KI-Dienst 77 | 78 | ### Bereitstellungsschritte 79 | 80 | 1. Repository klonen: 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. Abhängigkeiten installieren: 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. Umgebungsvariablen konfigurieren: 92 | Erstellen Sie eine `.env`-Datei und füllen Sie die erforderlichen Konfigurationsinformationen aus (siehe Umgebungsvariablen-Konfiguration unten). 93 | 94 | 4. Auf Vercel bereitstellen: 95 | - Forken Sie dieses Repository 96 | - Ändern Sie es gemäß den Anweisungen am Ende der Readme 97 | - Klicken Sie auf den "Mit Vercel bereitstellen"-Button 98 | - Verbinden Sie Ihr GitHub-Repository 99 | - Konfigurieren Sie die Umgebungsvariablen 100 | - Schließen Sie die Bereitstellung ab 101 | 102 | 5. Telegram-Webhook einrichten: 103 | Verwenden Sie nach der Bereitstellung die folgende URL, um den Webhook einzurichten: 104 | ``` 105 | https://api.telegram.org/bot/setWebhook?url=/api/telegram 106 | ``` 107 | 108 | ## Umgebungsvariablen-Konfiguration 🔧 109 | 110 | Bevor Sie GPT-Telegram-Bot bereitstellen und ausführen, müssen Sie die folgenden Umgebungsvariablen einrichten. Erstellen Sie eine `.env`-Datei im Stammverzeichnis des Projekts und konfigurieren Sie die folgenden Variablen: 111 | 112 | | Variablenname | Beschreibung | Standardwert | 113 | |---------------|--------------|--------------| 114 | | `OPENAI_API_KEY` | OpenAI API-Schlüssel | - | 115 | | `OPENAI_BASE_URL` | OpenAI API Basis-URL | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | Zu verwendende OpenAI-Modelle (kommagetrennt) | - | 117 | | `DEFAULT_MODEL` | Standardmäßig zu verwendendes Modell | Erstes Modell in OPENAI_MODELS | 118 | | `AZURE_OPENAI_API_KEY` | Azure OpenAI API-Schlüssel | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Azure OpenAI-Endpunkt | - | 120 | | `AZURE_OPENAI_MODELS` | Zu verwendende Azure OpenAI-Modelle (kommagetrennt) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Telegram-Bot-Token | - | 122 | | `WHITELISTED_USERS` | Erlaubte Benutzer-IDs (kommagetrennt) | - | 123 | | `DALL_E_MODEL` | Zu verwendenes DALL-E-Modell | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | Upstash Redis REST-URL | - | 125 | | `UPSTASH_REST_TOKEN` | Upstash Redis REST-Token | - | 126 | | `SYSTEM_INIT_MESSAGE` | System-Initialisierungsnachricht | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | Rolle der Systemnachricht | system | 128 | | `GEMINI_API_KEY` | Google Gemini API-Schlüssel | - | 129 | | `GOOGLE_MODELS` | Zu verwendende Google-Modelle (kommagetrennt) | - | 130 | | `GEMINI_ENDPOINT` | Gemini API-Endpunkt | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | Groq API-Schlüssel | - | 132 | | `GROQ_MODELS` | Zu verwendende Groq-Modelle (kommagetrennt) | - | 133 | | `MAX_HISTORY_LENGTH` | Maximale Verlaufslänge | 50 | 134 | | `CLAUDE_API_KEY` | Anthropic Claude API-Schlüssel | - | 135 | | `CLAUDE_MODELS` | Zu verwendende Claude-Modelle (kommagetrennt) | - | 136 | | `CLAUDE_ENDPOINT` | Claude API-Endpunkt | https://api.anthropic.com/v1/chat/completions | 137 | 138 | Stellen Sie sicher, dass Sie diese Umgebungsvariablen zur Umgebungskonfiguration Ihres Projekts hinzufügen, wenn Sie es auf Vercel oder anderen Plattformen bereitstellen. 139 | 140 | ## Nutzungsanleitung 📖 141 | 142 | - `/start` - Bot initialisieren 143 | - `/new` - Neue Konversation starten 144 | - `/history` - Gesprächsverlauf-Zusammenfassung anzeigen 145 | - `/help` - Hilfeinformationen erhalten 146 | - `/switchmodel ` - KI-Modell wechseln 147 | - `/img [Größe]` - Bild generieren 148 | - `/language ` - Schnittstellensprache ändern 149 | - Senden Sie ein Bild zur Analyse 150 | - Senden Sie eine Nachricht direkt für eine Konversation 151 | 152 | Unterstützte Sprachen (verwenden Sie den /language-Befehl): 153 | - Englisch (en) 154 | - Vereinfachtes Chinesisch (zh-cn) 155 | - Traditionelles Chinesisch (zh-hant) 156 | - Japanisch (ja) 157 | - Spanisch (es) 158 | - Französisch (fr) 159 | - Russisch (ru) 160 | - Deutsch (de) 161 | 162 | ## Hinweise ⚠️ 163 | 164 | - Verwenden Sie API-Kontingente vernünftig, insbesondere bei der Nutzung von Bildfunktionen 💸 165 | - Speichern Sie Umgebungsvariablen und API-Schlüssel sicher 🔒 166 | - Verschiedene KI-Modelle können unterschiedliche Funktionen und Einschränkungen haben 🔄 167 | - Überprüfen und aktualisieren Sie regelmäßig Abhängigkeiten, um Sicherheit und Leistung zu gewährleisten 🔧 168 | 169 | ## Mitwirken 🤝 170 | 171 | Pull Requests oder das Öffnen von Issues zur Verbesserung dieses Projekts sind willkommen! Ihre Beiträge werden diesen KI-Assistenten leistungsfähiger und interessanter machen. 172 | 173 | ## Lizenz 📜 174 | 175 | Dieses Projekt steht unter der [MIT-Lizenz](https://choosealicense.com/licenses/mit/). 176 | 177 | --- 178 | 179 | Über den "Mit Vercel bereitstellen"-Button: 180 | Dieser Button bietet eine Ein-Klick-Bereitstellungsfunktion auf Vercel, was sehr praktisch ist. Bitte beachten Sie jedoch: 181 | 182 | 1. Der Link im Button verweist auf das ursprüngliche Repository (https://github.com/snakeying/GPT-Telegram-Bot). 183 | 2. Wenn Sie dieses Projekt geforkt haben und Ihre eigene Version bereitstellen möchten, müssen Sie diesen Button-Link in der README aktualisieren. 184 | 3. Aktualisierungsmethode: Ersetzen Sie `snakeying/GPT-Telegram-Bot` im Link durch Ihren GitHub-Benutzernamen und Repository-Namen. 185 | 186 | Wenn Ihr GitHub-Benutzername beispielsweise "ihrname" ist, sollten Sie den Button-Link wie folgt ändern: 187 | 188 | ```markdown 189 | [![Mit Vercel bereitstellen](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fihrname%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | Dies stellt sicher, dass der "Mit Vercel bereitstellen"-Button Ihre geforkte Version und nicht das ursprüngliche Repository bereitstellt. 193 | -------------------------------------------------------------------------------- /docs/README.es.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot: Asistente de IA Multifuncional 🤖💬 2 | 3 | [English](../README.md) | [简体中文](./README.zh-cn.md) | [繁體中文](./README.zh-hant.md) | [日本語](./README.ja.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [Deutsch](./README.de.md) 4 | 5 | GPT-Telegram-Bot es un potente bot de Telegram que integra varios modelos de IA, proporcionando conversaciones inteligentes, generación y análisis de imágenes. 6 | 7 | [![Desplegar con Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## Características Principales 🌟 10 | 11 | 1. **Soporte Multi-modelo** 🎭: Cualquier modelo compatible con la API de OpenAI, Google Gemini, Anthropic Claude, Groq y Azure OpenAI 12 | 2. **Conversaciones Inteligentes** 💬: Interacciones en lenguaje natural con soporte de memoria contextual 13 | 3. **Generación de Imágenes** 🎨: Crea imágenes basadas en descripciones de texto 14 | 4. **Análisis de Imágenes** 🔍: Interpreta y describe imágenes subidas 15 | 5. **Soporte Multilingüe** 🌐: Soporte de localización para múltiples idiomas 16 | 6. **Respuesta en Tiempo Real** ⚡: Generación y visualización en tiempo real de las respuestas de la IA 17 | 7. **Lista Blanca de Usuarios** 🔐: Se puede configurar para permitir acceso solo a usuarios específicos 18 | 19 | ## Modelos de IA Soportados 🧠 20 | 21 | - Serie OpenAI: Potentes modelos de lenguaje 🚀 22 | - Google Gemini: Modelo de IA de próxima generación de Google 🧑‍🔬 23 | - Anthropic Claude: Otra potente opción de modelo de lenguaje 🎭 24 | - Groq: Modelo de IA de inferencia de alta velocidad ⚡ 25 | - Azure OpenAI: Servicio OpenAI alojado por Microsoft 👔 26 | 27 | ## Estructura del Proyecto 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # Configuración relacionada con la API 32 | │ ├── telegram.js # Gestiona las interacciones del bot de Telegram 33 | ├── src/ # Código fuente 34 | │ ├── api.js # Gestiona las interacciones con las API compatibles con OpenAI 35 | │ ├── bot.js # Lógica principal del bot de Telegram 36 | │ ├── config.js # Archivo de configuración 37 | │ ├── azureOpenAI.js # Gestiona las interacciones con Azure OpenAI 38 | │ ├── claude.js # Gestiona las interacciones con Claude 39 | │ ├── generateImage.js# Gestiona las interacciones con DALL·E 40 | │ ├── geminiApi.js # Gestiona las interacciones con Gemini 41 | │ ├── groqapi.js # Gestiona las interacciones con Groq 42 | │ ├── uploadhandler.js# Gestiona la lógica de carga y análisis de imágenes 43 | │ ├── localization.js # Gestiona el soporte multilingüe 44 | │ ├── redis.js # Funcionalidad de la base de datos Upstash Redis 45 | ├── locales/ # Archivos de soporte multilingüe 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # Archivos README multilingües 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # Página web de Vercel después de la implementación 63 | │ └── index.html # Archivo de entrada de la página web 64 | ├── package.json # Dependencias del proyecto 65 | ├── vercel.json # Archivo de configuración de Vercel 66 | └── README.md # Archivo de descripción del proyecto 67 | ``` 68 | 69 | ## Inicio Rápido 🚀 70 | 71 | ### Requisitos Previos 72 | 73 | - Cuenta de [Vercel](https://vercel.com/) 74 | - Cuenta de Telegram y Token de Bot 75 | - Base de datos [Upstash](https://upstash.com/) Por favor, selecciona la base de datos Redis y habilita la función de [Eviction](https://upstash.com/docs/redis/features/eviction) 76 | - Clave API para al menos un servicio de IA 77 | 78 | ### Pasos de Despliegue 79 | 80 | 1. Clonar el repositorio: 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. Instalar dependencias: 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. Configurar variables de entorno: 92 | Crea un archivo `.env` y completa la información de configuración necesaria (consulta la configuración de variables de entorno más abajo). 93 | 94 | 4. Desplegar en Vercel: 95 | - Haz un fork de este repositorio 96 | - Modifica según las instrucciones al final del readme 97 | - Haz clic en el botón "Desplegar con Vercel" 98 | - Conecta tu repositorio de GitHub 99 | - Configura las variables de entorno 100 | - Completa el despliegue 101 | 102 | 5. Configurar el Webhook de Telegram: 103 | Después del despliegue, utiliza la siguiente URL para configurar el Webhook: 104 | ``` 105 | https://api.telegram.org/bot/setWebhook?url=/api/telegram 106 | ``` 107 | 108 | ## Configuración de Variables de Entorno 🔧 109 | 110 | Antes de desplegar y ejecutar GPT-Telegram-Bot, necesitas configurar las siguientes variables de entorno. Crea un archivo `.env` en el directorio raíz del proyecto y configura las siguientes variables: 111 | 112 | | Nombre de Variable | Descripción | Valor por Defecto | 113 | |--------------------|-------------|-------------------| 114 | | `OPENAI_API_KEY` | Clave API de OpenAI | - | 115 | | `OPENAI_BASE_URL` | URL base de la API de OpenAI | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | Modelos de OpenAI a usar (separados por comas) | - | 117 | | `DEFAULT_MODEL` | Modelo a usar por defecto | Primer modelo en OPENAI_MODELS | 118 | | `AZURE_OPENAI_API_KEY` | Clave API de Azure OpenAI | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Endpoint de Azure OpenAI | - | 120 | | `AZURE_OPENAI_MODELS` | Modelos de Azure OpenAI a usar (separados por comas) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Token del Bot de Telegram | - | 122 | | `WHITELISTED_USERS` | IDs de usuario permitidos (separados por comas) | - | 123 | | `DALL_E_MODEL` | Modelo DALL-E a usar | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | URL REST de Upstash Redis | - | 125 | | `UPSTASH_REST_TOKEN` | Token REST de Upstash Redis | - | 126 | | `SYSTEM_INIT_MESSAGE` | Mensaje de inicialización del sistema | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | Rol del mensaje del sistema | system | 128 | | `GEMINI_API_KEY` | Clave API de Google Gemini | - | 129 | | `GOOGLE_MODELS` | Modelos de Google a usar (separados por comas) | - | 130 | | `GEMINI_ENDPOINT` | Endpoint de la API de Gemini | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | Clave API de Groq | - | 132 | | `GROQ_MODELS` | Modelos de Groq a usar (separados por comas) | - | 133 | | `MAX_HISTORY_LENGTH` | Longitud máxima del historial | 50 | 134 | | `CLAUDE_API_KEY` | Clave API de Anthropic Claude | - | 135 | | `CLAUDE_MODELS` | Modelos de Claude a usar (separados por comas) | - | 136 | | `CLAUDE_ENDPOINT` | Endpoint de la API de Claude | https://api.anthropic.com/v1/chat/completions | 137 | 138 | Asegúrate de añadir estas variables de entorno a la configuración de entorno de tu proyecto cuando lo despliegues en Vercel u otras plataformas. 139 | 140 | ## Guía de Uso 📖 141 | 142 | - `/start` - Inicializar el bot 143 | - `/new` - Iniciar una nueva conversación 144 | - `/history` - Ver resumen del historial de conversaciones 145 | - `/help` - Obtener información de ayuda 146 | - `/switchmodel ` - Cambiar el modelo de IA 147 | - `/img [tamaño]` - Generar imagen 148 | - `/language ` - Cambiar el idioma de la interfaz 149 | - Envía una imagen para analizarla 150 | - Envía un mensaje directamente para conversar 151 | 152 | Idiomas soportados (usa el comando /language): 153 | - Inglés (en) 154 | - Chino Simplificado (zh-cn) 155 | - Chino Tradicional (zh-hant) 156 | - Japonés (ja) 157 | - Español (es) 158 | - Francés (fr) 159 | - Ruso (ru) 160 | - Alemán (de) 161 | 162 | ## Notas ⚠️ 163 | 164 | - Usa las cuotas de API de manera razonable, especialmente al usar funciones de imágenes 💸 165 | - Almacena de forma segura las variables de entorno y las claves API 🔒 166 | - Diferentes modelos de IA pueden tener diferentes características y limitaciones 🔄 167 | - Verifica y actualiza las dependencias regularmente para garantizar la seguridad y el rendimiento 🔧 168 | 169 | ## Contribución 🤝 170 | 171 | ¡Bienvenidas las Pull Requests o la apertura de Issues para mejorar este proyecto! Tus contribuciones harán que este asistente de IA sea más potente e interesante. 172 | 173 | ## Licencia 📜 174 | 175 | Este proyecto está licenciado bajo la [Licencia MIT](https://choosealicense.com/licenses/mit/). 176 | 177 | --- 178 | 179 | Sobre el botón "Desplegar con Vercel": 180 | Este botón proporciona una función de despliegue con un clic en Vercel, lo cual es muy conveniente. Sin embargo, ten en cuenta: 181 | 182 | 1. El enlace en el botón apunta al repositorio original (https://github.com/snakeying/GPT-Telegram-Bot). 183 | 2. Si has hecho un fork de este proyecto y quieres desplegar tu propia versión, necesitas actualizar este enlace del botón en el README. 184 | 3. Método de actualización: Reemplaza `snakeying/GPT-Telegram-Bot` en el enlace con tu nombre de usuario de GitHub y el nombre del repositorio. 185 | 186 | Por ejemplo, si tu nombre de usuario de GitHub es "tunombre", deberías cambiar el enlace del botón a: 187 | 188 | ```markdown 189 | [![Desplegar con Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Ftunombre%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | Esto asegura que el botón "Desplegar con Vercel" desplegará tu versión forkeada, no el repositorio original. 193 | -------------------------------------------------------------------------------- /docs/README.fr.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot : Assistant IA Multifonctionnel 🤖💬 2 | 3 | [English](../README.md) | [简体中文](./README.zh-cn.md) | [繁體中文](./README.zh-hant.md) | [日本語](./README.ja.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [Deutsch](./README.de.md) 4 | 5 | GPT-Telegram-Bot est un puissant bot Telegram qui intègre divers modèles d'IA, offrant des conversations intelligentes, ainsi que des capacités de génération et d'analyse d'images. 6 | 7 | [![Déployer avec Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## Fonctionnalités Principales 🌟 10 | 11 | 1. **Support Multi-modèles** 🎭 : Tout modèle compatible avec l'API OpenAI, Google Gemini, Anthropic Claude, Groq et Azure OpenAI 12 | 2. **Conversations Intelligentes** 💬 : Interactions en langage naturel avec support de mémoire contextuelle 13 | 3. **Génération d'Images** 🎨 : Création d'images basées sur des descriptions textuelles 14 | 4. **Analyse d'Images** 🔍 : Interprétation et description des images téléchargées 15 | 5. **Support Multilingue** 🌐 : Prise en charge de la localisation pour plusieurs langues 16 | 6. **Réponse en Temps Réel** ⚡ : Génération et affichage en temps réel des réponses de l'IA 17 | 7. **Liste Blanche d'Utilisateurs** 🔐 : Peut être configuré pour n'autoriser l'accès qu'à des utilisateurs spécifiques 18 | 19 | ## Modèles d'IA Pris en Charge 🧠 20 | 21 | - Série OpenAI : Modèles de langage puissants 🚀 22 | - Google Gemini : Modèle d'IA de nouvelle génération de Google 🧑‍🔬 23 | - Anthropic Claude : Une autre option puissante de modèle de langage 🎭 24 | - Groq : Modèle d'IA d'inférence haute vitesse ⚡ 25 | - Azure OpenAI : Service OpenAI hébergé par Microsoft 👔 26 | 27 | ## Structure du Projet 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # Configuration relative à l'API 32 | │ ├── telegram.js # Gère les interactions du bot Telegram 33 | ├── src/ # Code source 34 | │ ├── api.js # Gère les interactions avec les API compatibles OpenAI 35 | │ ├── bot.js # Logique principale du bot Telegram 36 | │ ├── config.js # Fichier de configuration 37 | │ ├── azureOpenAI.js # Gère les interactions avec Azure OpenAI 38 | │ ├── claude.js # Gère les interactions avec Claude 39 | │ ├── generateImage.js# Gère les interactions avec DALL·E 40 | │ ├── geminiApi.js # Gère les interactions avec Gemini 41 | │ ├── groqapi.js # Gère les interactions avec Groq 42 | │ ├── uploadhandler.js# Gère la logique de téléchargement et d'analyse des images 43 | │ ├── localization.js # Gère le support multilingue 44 | │ ├── redis.js # Fonctionnalité de la base de données Upstash Redis 45 | ├── locales/ # Fichiers de support multilingue 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # Fichiers README multilingues 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # Page web Vercel après déploiement 63 | │ └── index.html # Fichier d'entrée de la page web 64 | ├── package.json # Dépendances du projet 65 | ├── vercel.json # Fichier de configuration Vercel 66 | └── README.md # Fichier de description du projet 67 | ``` 68 | 69 | ## Démarrage Rapide 🚀 70 | 71 | ### Prérequis 72 | 73 | - Compte [Vercel](https://vercel.com/) 74 | - Compte Telegram et Token de Bot 75 | - Base de données [Upstash](https://upstash.com/) Veuillez sélectionner la base de données Redis et activer la fonctionnalité [Eviction](https://upstash.com/docs/redis/features/eviction) 76 | - Clé API pour au moins un service d'IA 77 | 78 | ### Étapes de Déploiement 79 | 80 | 1. Cloner le dépôt : 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. Installer les dépendances : 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. Configurer les variables d'environnement : 92 | Créez un fichier `.env` et remplissez les informations de configuration nécessaires (référez-vous à la configuration des variables d'environnement ci-dessous). 93 | 94 | 4. Déployer sur Vercel : 95 | - Forkez ce dépôt 96 | - Modifiez selon les instructions en bas du readme 97 | - Cliquez sur le bouton "Déployer avec Vercel" 98 | - Connectez votre dépôt GitHub 99 | - Configurez les variables d'environnement 100 | - Terminez le déploiement 101 | 102 | 5. Configurer le Webhook Telegram : 103 | Après le déploiement, utilisez l'URL suivante pour configurer le Webhook : 104 | ``` 105 | https://api.telegram.org/bot/setWebhook?url=/api/telegram 106 | ``` 107 | 108 | ## Configuration des Variables d'Environnement 🔧 109 | 110 | Avant de déployer et d'exécuter GPT-Telegram-Bot, vous devez configurer les variables d'environnement suivantes. Créez un fichier `.env` dans le répertoire racine du projet et configurez les variables suivantes : 111 | 112 | | Nom de la Variable | Description | Valeur par Défaut | 113 | |--------------------|-------------|-------------------| 114 | | `OPENAI_API_KEY` | Clé API OpenAI | - | 115 | | `OPENAI_BASE_URL` | URL de base de l'API OpenAI | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | Modèles OpenAI à utiliser (séparés par des virgules) | - | 117 | | `DEFAULT_MODEL` | Modèle à utiliser par défaut | Premier modèle dans OPENAI_MODELS | 118 | | `AZURE_OPENAI_API_KEY` | Clé API Azure OpenAI | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Point de terminaison Azure OpenAI | - | 120 | | `AZURE_OPENAI_MODELS` | Modèles Azure OpenAI à utiliser (séparés par des virgules) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Token du Bot Telegram | - | 122 | | `WHITELISTED_USERS` | IDs des utilisateurs autorisés (séparés par des virgules) | - | 123 | | `DALL_E_MODEL` | Modèle DALL-E à utiliser | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | URL REST Upstash Redis | - | 125 | | `UPSTASH_REST_TOKEN` | Token REST Upstash Redis | - | 126 | | `SYSTEM_INIT_MESSAGE` | Message d'initialisation du système | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | Rôle du message système | system | 128 | | `GEMINI_API_KEY` | Clé API Google Gemini | - | 129 | | `GOOGLE_MODELS` | Modèles Google à utiliser (séparés par des virgules) | - | 130 | | `GEMINI_ENDPOINT` | Point de terminaison de l'API Gemini | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | Clé API Groq | - | 132 | | `GROQ_MODELS` | Modèles Groq à utiliser (séparés par des virgules) | - | 133 | | `MAX_HISTORY_LENGTH` | Longueur maximale de l'historique | 50 | 134 | | `CLAUDE_API_KEY` | Clé API Anthropic Claude | - | 135 | | `CLAUDE_MODELS` | Modèles Claude à utiliser (séparés par des virgules) | - | 136 | | `CLAUDE_ENDPOINT` | Point de terminaison de l'API Claude | https://api.anthropic.com/v1/chat/completions | 137 | 138 | Assurez-vous d'ajouter ces variables d'environnement à la configuration de votre projet lors du déploiement sur Vercel ou d'autres plateformes. 139 | 140 | ## Guide d'Utilisation 📖 141 | 142 | - `/start` - Initialiser le bot 143 | - `/new` - Démarrer une nouvelle conversation 144 | - `/history` - Voir le résumé de l'historique des conversations 145 | - `/help` - Obtenir des informations d'aide 146 | - `/switchmodel ` - Changer de modèle d'IA 147 | - `/img [taille]` - Générer une image 148 | - `/language ` - Changer la langue de l'interface 149 | - Envoyer une image pour l'analyser 150 | - Envoyer un message directement pour converser 151 | 152 | Langues prises en charge (utilisez la commande /language) : 153 | - Anglais (en) 154 | - Chinois simplifié (zh-cn) 155 | - Chinois traditionnel (zh-hant) 156 | - Japonais (ja) 157 | - Espagnol (es) 158 | - Français (fr) 159 | - Russe (ru) 160 | - Allemand (de) 161 | 162 | ## Remarques ⚠️ 163 | 164 | - Utilisez les quotas API de manière raisonnable, en particulier lors de l'utilisation des fonctionnalités d'image 💸 165 | - Stockez de manière sécurisée les variables d'environnement et les clés API 🔒 166 | - Différents modèles d'IA peuvent avoir des caractéristiques et des limitations différentes 🔄 167 | - Vérifiez et mettez à jour régulièrement les dépendances pour assurer la sécurité et les performances 🔧 168 | 169 | ## Contribution 🤝 170 | 171 | Les Pull Requests ou l'ouverture d'Issues pour améliorer ce projet sont les bienvenues ! Vos contributions rendront cet assistant IA plus puissant et intéressant. 172 | 173 | ## Licence 📜 174 | 175 | Ce projet est sous licence [MIT](https://choosealicense.com/licenses/mit/). 176 | 177 | --- 178 | 179 | À propos du bouton "Déployer avec Vercel" : 180 | Ce bouton fournit une fonction de déploiement en un clic sur Vercel, ce qui est très pratique. Cependant, veuillez noter : 181 | 182 | 1. Le lien dans le bouton pointe vers le dépôt original (https://github.com/snakeying/GPT-Telegram-Bot). 183 | 2. Si vous avez forké ce projet et souhaitez déployer votre propre version, vous devez mettre à jour ce lien de bouton dans le README. 184 | 3. Méthode de mise à jour : Remplacez `snakeying/GPT-Telegram-Bot` dans le lien par votre nom d'utilisateur GitHub et le nom du dépôt. 185 | 186 | Par exemple, si votre nom d'utilisateur GitHub est "votrenom", vous devriez changer le lien du bouton en : 187 | 188 | ```markdown 189 | [![Déployer avec Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvotrenom%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | Cela garantit que le bouton "Déployer avec Vercel" déploiera votre version forkée, et non le dépôt original. 193 | -------------------------------------------------------------------------------- /docs/README.ja.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot:多機能 AI アシスタント 🤖💬 2 | 3 | [English](../README.md) | [简体中文](./README.zh-cn.md) | [繁體中文](./README.zh-hant.md) | [日本語](./README.ja.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [Deutsch](./README.de.md) 4 | 5 | GPT-Telegram-Bot は、さまざまな AI モデルを統合し、インテリジェントな会話、画像生成、分析機能を提供する強力な Telegram ボットです。 6 | 7 | [![Vercel でデプロイ](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## 主な機能 🌟 10 | 11 | 1. **複数モデルのサポート** 🎭:OpenAI API 互換のモデル、Google Gemini、Anthropic Claude、Groq、Azure OpenAI 12 | 2. **インテリジェントな会話** 💬:コンテキストメモリをサポートする自然言語対話 13 | 3. **画像生成** 🎨:テキスト説明に基づいて画像を作成 14 | 4. **画像分析** 🔍:アップロードされた画像を解釈し説明 15 | 5. **多言語サポート** 🌐:複数言語のローカライゼーションをサポート 16 | 6. **ストリーミングレスポンス** ⚡:AI の返答をリアルタイムで生成・表示 17 | 7. **ユーザーホワイトリスト** 🔐:特定のユーザーのみアクセスを許可するように設定可能 18 | 19 | ## サポートされている AI モデル 🧠 20 | 21 | - OpenAI シリーズ:強力な言語モデル 🚀 22 | - Google Gemini:Google の次世代 AI モデル 🧑‍🔬 23 | - Anthropic Claude:もう一つの強力な言語モデルの選択肢 🎭 24 | - Groq:高速推論 AI モデル ⚡ 25 | - Azure OpenAI:Microsoft がホストする OpenAI サービス 👔 26 | 27 | ## プロジェクト構造 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # API関連の設定 32 | │ ├── telegram.js # Telegramボットのインタラクションを処理 33 | ├── src/ # ソースコード 34 | │ ├── api.js # OpenAI互換APIとのインタラクションを処理 35 | │ ├── bot.js # Telegramボットのメインロジック 36 | │ ├── config.js # 設定ファイル 37 | │ ├── azureOpenAI.js # Azure OpenAIとのインタラクションを処理 38 | │ ├── claude.js # Claudeとのインタラクションを処理 39 | │ ├── generateImage.js# DALL·Eとのインタラクションを処理 40 | │ ├── geminiApi.js # Geminiとのインタラクションを処理 41 | │ ├── groqapi.js # Groqとのインタラクションを処理 42 | │ ├── uploadhandler.js# 画像のアップロードと解析ロジックを処理 43 | │ ├── localization.js # 多言語サポートを処理 44 | │ ├── redis.js # Upstash Redisデータベース機能 45 | ├── locales/ # 多言語サポートファイル 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # 多言語READMEファイル 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # デプロイ後のVercelウェブページ 63 | │ └── index.html # ウェブページのエントリファイル 64 | ├── package.json # プロジェクトの依存関係 65 | ├── vercel.json # Vercel設定ファイル 66 | └── README.md # プロジェクトの説明ファイル 67 | ``` 68 | 69 | ## クイックスタート 🚀 70 | 71 | ### 前提条件 72 | 73 | - [Vercel](https://vercel.com/) アカウント 74 | - Telegram アカウントとボットトークン 75 | - [Upstash](https://upstash.com/) Redisデータベースを選択し、[Eviction](https://upstash.com/docs/redis/features/eviction) 機能を有効にしてください 76 | - 少なくとも1つの AI サービスの API キー 77 | 78 | ### デプロイ手順 79 | 80 | 1. リポジトリをクローン: 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. 依存関係をインストール: 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. 環境変数を設定: 92 | `.env` ファイルを作成し、必要な設定情報を入力します(下記の環境変数設定を参照)。 93 | 94 | 4. Vercel にデプロイ: 95 | - このリポジトリを Fork 96 | - readme の最下部の指示に従って修正 97 | - 「Vercel でデプロイ」ボタンをクリック 98 | - GitHub リポジトリを接続 99 | - 環境変数を設定 100 | - デプロイを完了 101 | 102 | 5. Telegram Webhook を設定: 103 | デプロイ完了後、以下の URL を使用して Webhook を設定: 104 | ``` 105 | https://api.telegram.org/bot/setWebhook?url=/api/telegram 106 | ``` 107 | 108 | ## 環境変数設定 🔧 109 | 110 | GPT-Telegram-Bot をデプロイ・実行する前に、以下の環境変数を設定する必要があります。プロジェクトのルートディレクトリに `.env` ファイルを作成し、以下の変数を設定してください: 111 | 112 | | 変数名 | 説明 | デフォルト値 | 113 | |--------|------|-------------| 114 | | `OPENAI_API_KEY` | OpenAI API キー | - | 115 | | `OPENAI_BASE_URL` | OpenAI API ベース URL | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | 使用する OpenAI モデル(カンマ区切り) | - | 117 | | `DEFAULT_MODEL` | デフォルトで使用するモデル | OPENAI_MODELS の最初のモデル | 118 | | `AZURE_OPENAI_API_KEY` | Azure OpenAI API キー | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Azure OpenAI エンドポイント | - | 120 | | `AZURE_OPENAI_MODELS` | 使用する Azure OpenAI モデル(カンマ区切り) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Telegram ボットトークン | - | 122 | | `WHITELISTED_USERS` | 許可するユーザー ID(カンマ区切り) | - | 123 | | `DALL_E_MODEL` | 使用する DALL-E モデル | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | Upstash Redis REST URL | - | 125 | | `UPSTASH_REST_TOKEN` | Upstash Redis REST トークン | - | 126 | | `SYSTEM_INIT_MESSAGE` | システム初期化メッセージ | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | システムメッセージの役割 | system | 128 | | `GEMINI_API_KEY` | Google Gemini API キー | - | 129 | | `GOOGLE_MODELS` | 使用する Google モデル(カンマ区切り) | - | 130 | | `GEMINI_ENDPOINT` | Gemini API エンドポイント | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | Groq API キー | - | 132 | | `GROQ_MODELS` | 使用する Groq モデル(カンマ区切り) | - | 133 | | `MAX_HISTORY_LENGTH` | 最大履歴長 | 50 | 134 | | `CLAUDE_API_KEY` | Anthropic Claude API キー | - | 135 | | `CLAUDE_MODELS` | 使用する Claude モデル(カンマ区切り) | - | 136 | | `CLAUDE_ENDPOINT` | Claude API エンドポイント | https://api.anthropic.com/v1/chat/completions | 137 | 138 | Vercel やその他のプラットフォームにデプロイする際は、これらの環境変数をプロジェクトの環境設定に追加してください。 139 | 140 | ## 使用ガイド 📖 141 | 142 | - `/start` - ボットを初期化 143 | - `/new` - 新しい会話を開始 144 | - `/history` - 会話履歴の概要を表示 145 | - `/help` - ヘルプ情報を取得 146 | - `/switchmodel <モデル名>` - AI モデルを切り替え 147 | - `/img <説明> [サイズ]` - 画像を生成 148 | - `/language <言語コード>` - インターフェース言語を切り替え 149 | - 画像を送信して分析 150 | - メッセージを直接送信して会話 151 | 152 | サポートされている言語(/language コマンドを使用): 153 | - 英語 (en) 154 | - 簡体字中国語 (zh-cn) 155 | - 繁体字中国語 (zh-hant) 156 | - 日本語 (ja) 157 | - スペイン語 (es) 158 | - フランス語 (fr) 159 | - ロシア語 (ru) 160 | - ドイツ語 (de) 161 | 162 | ## 注意事項 ⚠️ 163 | 164 | - API クォータを適切に使用してください。特に画像機能を使用する際は注意が必要です 💸 165 | - 環境変数と API キーを安全に保管してください 🔒 166 | - 異なる AI モデルには異なる特性と制限がある場合があります 🔄 167 | - セキュリティと性能を確保するために、定期的に依存関係を確認・更新してください 🔧 168 | 169 | ## 貢献 🤝 170 | 171 | プロジェクトを改善するための Pull Request や Issue の提出を歓迎します!皆様の貢献により、この AI アシスタントはより強力で面白いものになります。 172 | 173 | ## ライセンス 📜 174 | 175 | このプロジェクトは [MIT ライセンス](https://choosealicense.com/licenses/mit/)の下で公開されています。 176 | 177 | --- 178 | 179 | 「Vercel でデプロイ」ボタンについて: 180 | このボタンは Vercel へのワンクリックデプロイ機能を提供し、非常に便利です。ただし、以下の点に注意してください: 181 | 182 | 1. ボタン内のリンクは元のリポジトリ(https://github.com/snakeying/GPT-Telegram-Bot)を指しています。 183 | 2. このプロジェクトを Fork して自分のバージョンをデプロイしたい場合は、README 内のこのボタンリンクを更新する必要があります。 184 | 3. 更新方法:リンク内の `snakeying/GPT-Telegram-Bot` を自分の GitHub ユーザー名とリポジトリ名に置き換えてください。 185 | 186 | 例えば、GitHub ユーザー名が "yourname" の場合、ボタンのリンクを以下のように変更します: 187 | 188 | ```markdown 189 | [![Vercel でデプロイ](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fyourname%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | これにより、「Vercel でデプロイ」ボタンが元のリポジトリではなく、Fork したバージョンをデプロイすることを確認できます。 193 | -------------------------------------------------------------------------------- /docs/README.ru.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot: Многофункциональный ИИ-ассистент 🤖💬 2 | 3 | [English](../README.md) | [简体中文](./README.zh-cn.md) | [繁體中文](./README.zh-hant.md) | [日本語](./README.ja.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [Deutsch](./README.de.md) 4 | 5 | GPT-Telegram-Bot — это мощный Telegram-бот, интегрирующий различные модели ИИ, обеспечивающий интеллектуальные беседы, генерацию и анализ изображений. 6 | 7 | [![Развернуть с Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## Основные функции 🌟 10 | 11 | 1. **Поддержка нескольких моделей** 🎭: Любая модель, совместимая с API OpenAI, Google Gemini, Anthropic Claude, Groq и Azure OpenAI 12 | 2. **Интеллектуальные беседы** 💬: Взаимодействие на естественном языке с поддержкой контекстной памяти 13 | 3. **Генерация изображений** 🎨: Создание изображений на основе текстовых описаний 14 | 4. **Анализ изображений** 🔍: Интерпретация и описание загруженных изображений 15 | 5. **Многоязычная поддержка** 🌐: Поддержка локализации для нескольких языков 16 | 6. **Потоковый ответ** ⚡: Генерация и отображение ответов ИИ в реальном времени 17 | 7. **Белый список пользователей** 🔐: Может быть настроен для разрешения доступа только определенным пользователям 18 | 19 | ## Поддерживаемые модели ИИ 🧠 20 | 21 | - Серия OpenAI: Мощные языковые модели 🚀 22 | - Google Gemini: Модель ИИ нового поколения от Google 🧑‍🔬 23 | - Anthropic Claude: Еще один мощный выбор языковой модели 🎭 24 | - Groq: Высокоскоростная модель ИИ для логического вывода ⚡ 25 | - Azure OpenAI: Сервис OpenAI, размещенный Microsoft 👔 26 | 27 | ## Структура проекта 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # Конфигурация, связанная с API 32 | │ ├── telegram.js # Обрабатывает взаимодействия с ботом Telegram 33 | ├── src/ # Исходный код 34 | │ ├── api.js # Обрабатывает взаимодействия с совместимыми с OpenAI API 35 | │ ├── bot.js # Основная логика бота Telegram 36 | │ ├── config.js # Файл конфигурации 37 | │ ├── azureOpenAI.js # Обрабатывает взаимодействия с Azure OpenAI 38 | │ ├── claude.js # Обрабатывает взаимодействия с Claude 39 | │ ├── generateImage.js# Обрабатывает взаимодействия с DALL·E 40 | │ ├── geminiApi.js # Обрабатывает взаимодействия с Gemini 41 | │ ├── groqapi.js # Обрабатывает взаимодействия с Groq 42 | │ ├── uploadhandler.js# Обрабатывает логику загрузки и анализа изображений 43 | │ ├── localization.js # Обрабатывает многоязычную поддержку 44 | │ ├── redis.js # Функциональность базы данных Upstash Redis 45 | ├── locales/ # Файлы многоязычной поддержки 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # Многоязычные файлы README 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # Веб-страница Vercel после развертывания 63 | │ └── index.html # Входной файл веб-страницы 64 | ├── package.json # Зависимости проекта 65 | ├── vercel.json # Файл конфигурации Vercel 66 | └── README.md # Файл описания проекта 67 | ``` 68 | 69 | ## Быстрый старт 🚀 70 | 71 | ### Предварительные требования 72 | 73 | - Аккаунт [Vercel](https://vercel.com/) 74 | - Аккаунт Telegram и токен бота 75 | - База данных [Upstash](https://upstash.com/) Пожалуйста, выберите базу данных Redis и включите функцию [Eviction](https://upstash.com/docs/redis/features/eviction) 76 | - API-ключ хотя бы для одного ИИ-сервиса 77 | 78 | ### Шаги развертывания 79 | 80 | 1. Клонируйте репозиторий: 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. Установите зависимости: 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. Настройте переменные окружения: 92 | Создайте файл `.env` и заполните необходимую информацию конфигурации (см. конфигурацию переменных окружения ниже). 93 | 94 | 4. Разверните на Vercel: 95 | - Сделайте форк этого репозитория 96 | - Измените согласно инструкциям в нижней части readme 97 | - Нажмите кнопку "Развернуть с Vercel" 98 | - Подключите свой репозиторий GitHub 99 | - Настройте переменные окружения 100 | - Завершите развертывание 101 | 102 | 5. Настройте Telegram Webhook: 103 | После развертывания используйте следующий URL для настройки Webhook: 104 | ``` 105 | https://api.telegram.org/bot<ВАШ_ТОКЕН_БОТА>/setWebhook?url=<ВАШ_ДОМЕН_VERCEL>/api/telegram 106 | ``` 107 | 108 | ## Конфигурация переменных окружения 🔧 109 | 110 | Перед развертыванием и запуском GPT-Telegram-Bot вам нужно настроить следующие переменные окружения. Создайте файл `.env` в корневой директории проекта и настройте следующие переменные: 111 | 112 | | Имя переменной | Описание | Значение по умолчанию | 113 | |----------------|----------|------------------------| 114 | | `OPENAI_API_KEY` | API-ключ OpenAI | - | 115 | | `OPENAI_BASE_URL` | Базовый URL API OpenAI | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | Модели OpenAI для использования (разделенные запятыми) | - | 117 | | `DEFAULT_MODEL` | Модель для использования по умолчанию | Первая модель в OPENAI_MODELS | 118 | | `AZURE_OPENAI_API_KEY` | API-ключ Azure OpenAI | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Конечная точка Azure OpenAI | - | 120 | | `AZURE_OPENAI_MODELS` | Модели Azure OpenAI для использования (разделенные запятыми) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Токен Telegram-бота | - | 122 | | `WHITELISTED_USERS` | Разрешенные ID пользователей (разделенные запятыми) | - | 123 | | `DALL_E_MODEL` | Модель DALL-E для использования | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | REST URL Upstash Redis | - | 125 | | `UPSTASH_REST_TOKEN` | REST токен Upstash Redis | - | 126 | | `SYSTEM_INIT_MESSAGE` | Системное инициализационное сообщение | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | Роль системного сообщения | system | 128 | | `GEMINI_API_KEY` | API-ключ Google Gemini | - | 129 | | `GOOGLE_MODELS` | Модели Google для использования (разделенные запятыми) | - | 130 | | `GEMINI_ENDPOINT` | Конечная точка API Gemini | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | API-ключ Groq | - | 132 | | `GROQ_MODELS` | Модели Groq для использования (разделенные запятыми) | - | 133 | | `MAX_HISTORY_LENGTH` | Максимальная длина истории | 50 | 134 | | `CLAUDE_API_KEY` | API-ключ Anthropic Claude | - | 135 | | `CLAUDE_MODELS` | Модели Claude для использования (разделенные запятыми) | - | 136 | | `CLAUDE_ENDPOINT` | Конечная точка API Claude | https://api.anthropic.com/v1/chat/completions | 137 | 138 | Убедитесь, что добавили эти переменные окружения в конфигурацию окружения вашего проекта при развертывании на Vercel или других платформах. 139 | 140 | ## Руководство по использованию 📖 141 | 142 | - `/start` - Инициализировать бота 143 | - `/new` - Начать новый разговор 144 | - `/history` - Просмотреть краткое изложение истории разговоров 145 | - `/help` - Получить справочную информацию 146 | - `/switchmodel <название модели>` - Переключить модель ИИ 147 | - `/img <описание> [размер]` - Сгенерировать изображение 148 | - `/language <код языка>` - Переключить язык интерфейса 149 | - Отправьте изображение для анализа 150 | - Отправьте сообщение напрямую для разговора 151 | 152 | Поддерживаемые языки (используйте команду /language): 153 | - Английский (en) 154 | - Упрощенный китайский (zh-cn) 155 | - Традиционный китайский (zh-hant) 156 | - Японский (ja) 157 | - Испанский (es) 158 | - Французский (fr) 159 | - Русский (ru) 160 | - Немецкий (de) 161 | 162 | ## Примечания ⚠️ 163 | 164 | - Разумно используйте квоты API, особенно при использовании функций изображений 💸 165 | - Надежно храните переменные окружения и API-ключи 🔒 166 | - Разные модели ИИ могут иметь разные характеристики и ограничения 🔄 167 | - Регулярно проверяйте и обновляйте зависимости для обеспечения безопасности и производительности 🔧 168 | 169 | ## Вклад в проект 🤝 170 | 171 | Приветствуются Pull Request'ы или открытие Issues для улучшения этого проекта! Ваш вклад сделает этого ИИ-ассистента более мощным и интересным. 172 | 173 | ## Лицензия 📜 174 | 175 | Этот проект лицензирован под [лицензией MIT](https://choosealicense.com/licenses/mit/). 176 | 177 | --- 178 | 179 | О кнопке "Развернуть с Vercel": 180 | Эта кнопка предоставляет функцию развертывания в один клик на Vercel, что очень удобно. Однако, обратите внимание: 181 | 182 | 1. Ссылка в кнопке указывает на оригинальный репозиторий (https://github.com/snakeying/GPT-Telegram-Bot). 183 | 2. Если вы сделали форк этого проекта и хотите развернуть свою собственную версию, вам нужно обновить эту ссылку кнопки в README. 184 | 3. Метод обновления: Замените `snakeying/GPT-Telegram-Bot` в ссылке на ваше имя пользователя GitHub и название репозитория. 185 | 186 | Например, если ваше имя пользователя GitHub "vashimya", вы должны изменить ссылку кнопки на: 187 | 188 | ```markdown 189 | [![Развернуть с Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvashimya%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | Это обеспечит, что кнопка "Развернуть с Vercel" будет развертывать вашу форкнутую версию, а не оригинальный репозиторий. 193 | -------------------------------------------------------------------------------- /docs/README.zh-cn.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot:多功能 AI 助手 🤖💬 2 | 3 | [English](../README.md) | [简体中文](./README.zh-cn.md) | [繁體中文](./README.zh-hant.md) | [日本語](./README.ja.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [Deutsch](./README.de.md) 4 | 5 | GPT-Telegram-Bot 是一个功能强大的 Telegram 机器人,集成了多种 AI 模型,提供智能对话、图像生成和分析等功能。 6 | 7 | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## 主要功能 🌟 10 | 11 | 1. **多模型支持** 🎭:任意兼容OpenAI API的模型、Google Gemini、Anthropic Claude、Groq 和 Azure OpenAI 12 | 2. **智能对话** 💬:支持上下文记忆的自然语言交互 13 | 3. **图像生成** 🎨:基于文字描述创建图像 14 | 4. **图像分析** 🔍:解读并描述上传的图片 15 | 5. **多语言支持** 🌐:支持多种语言的本地化 16 | 6. **流式响应** ⚡:实时生成和显示 AI 回复 17 | 7. **用户白名单** 🔐:可设置仅允许特定用户访问 18 | 19 | ## 支持的 AI 模型 🧠 20 | 21 | - OpenAI 系列:强大的语言模型 🚀 22 | - Google Gemini:Google 的新一代 AI 模型 🧑‍🔬 23 | - Anthropic Claude:另一个强大的语言模型选择 🎭 24 | - Groq:高速推理的 AI 模型 ⚡ 25 | - Azure OpenAI:微软托管的 OpenAI 服务 👔 26 | 27 | ## 项目结构 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # api相关配置 32 | │ ├── telegram.js # 处理Telegram bot交互 33 | ├── src/ # 源代码 34 | │ ├── api.js # 处理兼容OpenAI的API交互 35 | │ ├── bot.js # 主要的Telegram bot逻辑 36 | │ ├── config.js # 配置文件 37 | │ ├── azureOpenAI.js # 处理azureOpenAI交互 38 | │ ├── claude.js # 处理claude交互 39 | │ ├── generateImage.js# 处理DALL·E交互 40 | │ ├── geminiApi.js # 处理Gemini交互 41 | │ ├── groqapi.js # 处理Groq交互 42 | │ ├── uploadhandler.js# 上传图片处理相关逻辑 43 | │ ├── localization.js # 多语言支持逻辑 44 | │ ├── redis.js # upstash redis数据库功能 45 | ├── locales/ # 多语言支持文件 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # 多语言 README 文件目录 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # 部署完成后的vercel网页 63 | │ └── index.html # 网页入口文件 64 | ├── package.json # 项目依赖 65 | ├── vercel.json # Vercel配置文件 66 | └── README.md # 项目说明文件 67 | ``` 68 | 69 | ## 快速开始 🚀 70 | 71 | ### 前置要求 72 | 73 | - [Vercel](https://vercel.com/) 账号 74 | - Telegram 账号和 Bot Token 75 | - [Upstash](https://upstash.com/) 请选择 Redis 数据库并开启 [Eviction](https://upstash.com/docs/redis/features/eviction) 功能 76 | - 至少一个 AI 服务的 API 密钥 77 | 78 | ### 部署步骤 79 | 80 | 1. 克隆仓库: 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. 安装依赖: 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. 配置环境变量: 92 | 创建 `.env` 文件并填入必要的配置信息(参考下方的环境变量配置)。 93 | 94 | 4. 部署到 Vercel: 95 | - Fork这个repo 96 | - 按照readme最下方的指引修改 97 | - 点击"Deploy with Vercel" 按钮 98 | - 连接你的 GitHub 仓库 99 | - 配置环境变量 100 | - 完成部署 101 | 102 | 5. 设置 Telegram Webhook: 103 | 部署完成后,使用以下 URL 设置 Webhook: 104 | ``` 105 | https://api.telegram.org/bot/setWebhook?url=/api/telegram 106 | ``` 107 | 108 | ## 环境变量配置 🔧 109 | 110 | 在部署和运行 GPT-Telegram-Bot 之前,您需要设置以下环境变量。创建一个 `.env` 文件在项目根目录下,并配置以下变量: 111 | 112 | | 变量名 | 描述 | 默认值 | 113 | |--------|------|--------| 114 | | `OPENAI_API_KEY` | OpenAI API 密钥 | - | 115 | | `OPENAI_BASE_URL` | OpenAI API 基础 URL | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | 使用的 OpenAI 模型(逗号分隔) | - | 117 | | `DEFAULT_MODEL` | 默认使用的模型 | OPENAI_MODELS 的第一个模型 | 118 | | `AZURE_OPENAI_API_KEY` | Azure OpenAI API 密钥 | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Azure OpenAI 端点 | - | 120 | | `AZURE_OPENAI_MODELS` | 使用的 Azure OpenAI 模型(逗号分隔) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Telegram Bot Token | - | 122 | | `WHITELISTED_USERS` | 允许使用的用户 ID(逗号分隔) | - | 123 | | `DALL_E_MODEL` | 使用的 DALL-E 模型 | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | Upstash Redis REST URL | - | 125 | | `UPSTASH_REST_TOKEN` | Upstash Redis REST Token | - | 126 | | `SYSTEM_INIT_MESSAGE` | 系统初始化消息 | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | 系统消息角色 | system | 128 | | `GEMINI_API_KEY` | Google Gemini API 密钥 | - | 129 | | `GOOGLE_MODELS` | 使用的 Google 模型(逗号分隔) | - | 130 | | `GEMINI_ENDPOINT` | Gemini API 端点 | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | Groq API 密钥 | - | 132 | | `GROQ_MODELS` | 使用的 Groq 模型(逗号分隔) | - | 133 | | `MAX_HISTORY_LENGTH` | 最大历史记录长度 | 50 | 134 | | `CLAUDE_API_KEY` | Anthropic Claude API 密钥 | - | 135 | | `CLAUDE_MODELS` | 使用的 Claude 模型(逗号分隔) | - | 136 | | `CLAUDE_ENDPOINT` | Claude API 端点 | https://api.anthropic.com/v1/chat/completions | 137 | 138 | 确保在部署到 Vercel 或其他平台时,将这些环境变量添加到项目的环境配置中。 139 | 140 | ## 使用指南 📖 141 | 142 | - `/start` - 初始化机器人 143 | - `/new` - 开始新的对话 144 | - `/history` - 查看对话历史摘要 145 | - `/help` - 获取帮助信息 146 | - `/switchmodel <模型名称>` - 切换 AI 模型 147 | - `/img <描述> [尺寸]` - 生成图像 148 | - `/language <语言代码>` - 切换界面语言 149 | - 发送图片以进行分析 150 | - 直接发送消息进行对话 151 | 152 | 支持的语言(使用 /language 命令): 153 | - 英语 (en) 154 | - 简体中文 (zh-cn) 155 | - 繁体中文 (zh-hant) 156 | - 日语 (ja) 157 | - 西班牙语 (es) 158 | - 法语 (fr) 159 | - 俄语 (ru) 160 | - 德语 (de) 161 | 162 | ## 注意事项 ⚠️ 163 | 164 | - 合理使用 API 配额,特别是在使用图像功能时 💸 165 | - 妥善保管环境变量和 API 密钥 🔒 166 | - 不同 AI 模型可能有不同的特性和限制 🔄 167 | - 定期检查和更新依赖,以确保安全性和性能 🔧 168 | 169 | ## 贡献 🤝 170 | 171 | 欢迎提交 Pull Requests 或开 Issues 来改进这个项目!您的贡献将使这个 AI 助手变得更加强大和有趣。 172 | 173 | ## 许可证 📜 174 | 175 | 本项目采用 [MIT 许可证](https://choosealicense.com/licenses/mit/)。 176 | 177 | --- 178 | 179 | 关于 "Deploy to Vercel" 按钮: 180 | 这个按钮提供了一键部署到 Vercel 的功能,非常方便。但是,请注意: 181 | 182 | 1. 按钮中的链接指向的是原始仓库(https://github.com/snakeying/GPT-Telegram-Bot)。 183 | 2. 如果您 fork 了这个项目并希望部署您自己的版本,您需要更新 README 中的这个按钮链接。 184 | 3. 更新方法:将链接中的 `snakeying/GPT-Telegram-Bot` 替换为您的 GitHub 用户名和仓库名。 185 | 186 | 例如,如果您的 GitHub 用户名是 "yourname",您应该将按钮的链接更改为: 187 | 188 | ```markdown 189 | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fyourname%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | 这样可以确保 "Deploy to Vercel" 按钮会部署您 fork 的版本,而不是原始仓库。 193 | -------------------------------------------------------------------------------- /docs/README.zh-hant.md: -------------------------------------------------------------------------------- 1 | # GPT-Telegram-Bot:多功能 AI 助手 🤖💬 2 | 3 | [English](../README.md) | [简体中文](./README.zh-cn.md) | [繁體中文](./README.zh-hant.md) | [日本語](./README.ja.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [Deutsch](./README.de.md) 4 | 5 | GPT-Telegram-Bot 是一個功能強大的 Telegram 機器人,整合了多種 AI 模型,提供智慧對話、圖像生成和分析等功能。 6 | 7 | [![使用 Vercel 部署](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsnakeying%2FGPT-Telegram-Bot) 8 | 9 | ## 主要功能 🌟 10 | 11 | 1. **多模型支援** 🎭:任何與 OpenAI API 相容的模型、Google Gemini、Anthropic Claude、Groq 和 Azure OpenAI 12 | 2. **智慧對話** 💬:支援上下文記憶的自然語言互動 13 | 3. **圖像生成** 🎨:根據文字描述創建圖像 14 | 4. **圖像分析** 🔍:解讀並描述上傳的圖片 15 | 5. **多語言支援** 🌐:支援多種語言的在地化 16 | 6. **串流回應** ⚡:即時生成和顯示 AI 回覆 17 | 7. **使用者白名單** 🔐:可設定僅允許特定使用者存取 18 | 19 | ## 支援的 AI 模型 🧠 20 | 21 | - OpenAI 系列:強大的語言模型 🚀 22 | - Google Gemini:Google 的新一代 AI 模型 🧑‍🔬 23 | - Anthropic Claude:另一個強大的語言模型選擇 🎭 24 | - Groq:高速推理的 AI 模型 ⚡ 25 | - Azure OpenAI:微軟託管的 OpenAI 服務 👔 26 | 27 | ## 專案結構 📁 28 | 29 | ``` 30 | GPT-Telegram-Bot/ 31 | ├── api/ # API 相關配置 32 | │ ├── telegram.js # 處理 Telegram 機器人互動 33 | ├── src/ # 原始碼 34 | │ ├── api.js # 處理與 OpenAI 相容的 API 互動 35 | │ ├── bot.js # Telegram 機器人的主要邏輯 36 | │ ├── config.js # 配置文件 37 | │ ├── azureOpenAI.js # 處理與 Azure OpenAI 的互動 38 | │ ├── claude.js # 處理與 Claude 的互動 39 | │ ├── generateImage.js# 處理與 DALL·E 的互動 40 | │ ├── geminiApi.js # 處理與 Gemini 的互動 41 | │ ├── groqapi.js # 處理與 Groq 的互動 42 | │ ├── uploadhandler.js# 處理圖片上傳和分析邏輯 43 | │ ├── localization.js # 處理多語言支援 44 | │ ├── redis.js # Upstash Redis 資料庫功能 45 | ├── locales/ # 多語言支援文件 46 | │ ├── en.json 47 | │ ├── zh-cn.json 48 | │ ├── zh-hant.json 49 | │ └── ja.json 50 | │ └── es.json 51 | │ └── fr.json 52 | │ └── ru.json 53 | │ └── de.json 54 | ├── docs/ # 多語言 README 文件 55 | │ ├── README.zh-cn.md 56 | │ ├── README.zh-hant.md 57 | │ ├── README.ja.md 58 | │ ├── README.es.md 59 | │ ├── README.fr.md 60 | │ ├── README.ru.md 61 | │ └── README.de.md 62 | ├── public/ # 部署完成後的 Vercel 網頁 63 | │ └── index.html # 網頁入口文件 64 | ├── package.json # 專案依賴 65 | ├── vercel.json # Vercel 配置文件 66 | └── README.md # 專案說明文件 67 | ``` 68 | 69 | ## 快速開始 🚀 70 | 71 | ### 前置要求 72 | 73 | - [Vercel](https://vercel.com/) 帳號 74 | - Telegram 帳號和 Bot Token 75 | - [Upstash](https://upstash.com/) 請選擇 Redis 數據庫並啟用 [Eviction](https://upstash.com/docs/redis/features/eviction) 功能 76 | - 至少一個 AI 服務的 API 金鑰 77 | 78 | ### 部署步驟 79 | 80 | 1. 複製儲存庫: 81 | ```bash 82 | git clone https://github.com/snakeying/GPT-Telegram-Bot.git 83 | cd GPT-Telegram-Bot 84 | ``` 85 | 86 | 2. 安裝相依套件: 87 | ```bash 88 | npm install 89 | ``` 90 | 91 | 3. 設定環境變數: 92 | 建立 `.env` 檔案並填入必要的設定資訊(參考下方的環境變數設定)。 93 | 94 | 4. 部署到 Vercel: 95 | - Fork 這個儲存庫 96 | - 按照 readme 最下方的指引修改 97 | - 點擊「使用 Vercel 部署」按鈕 98 | - 連接你的 GitHub 儲存庫 99 | - 設定環境變數 100 | - 完成部署 101 | 102 | 5. 設定 Telegram Webhook: 103 | 部署完成後,使用以下 URL 設定 Webhook: 104 | ``` 105 | https://api.telegram.org/bot/setWebhook?url=/api/telegram 106 | ``` 107 | 108 | ## 環境變數設定 🔧 109 | 110 | 在部署和運行 GPT-Telegram-Bot 之前,您需要設定以下環境變數。在專案根目錄下建立一個 `.env` 檔案,並設定以下變數: 111 | 112 | | 變數名 | 描述 | 預設值 | 113 | |--------|------|--------| 114 | | `OPENAI_API_KEY` | OpenAI API 金鑰 | - | 115 | | `OPENAI_BASE_URL` | OpenAI API 基礎 URL | https://api.openai.com/v1 | 116 | | `OPENAI_MODELS` | 使用的 OpenAI 模型(逗號分隔) | - | 117 | | `DEFAULT_MODEL` | 預設使用的模型 | OPENAI_MODELS 的第一個模型 | 118 | | `AZURE_OPENAI_API_KEY` | Azure OpenAI API 金鑰 | - | 119 | | `AZURE_OPENAI_ENDPOINT` | Azure OpenAI 端點 | - | 120 | | `AZURE_OPENAI_MODELS` | 使用的 Azure OpenAI 模型(逗號分隔) | - | 121 | | `TELEGRAM_BOT_TOKEN` | Telegram Bot Token | - | 122 | | `WHITELISTED_USERS` | 允許使用的使用者 ID(逗號分隔) | - | 123 | | `DALL_E_MODEL` | 使用的 DALL-E 模型 | dall-e-3 | 124 | | `UPSTASH_REDIS_REST_URL` | Upstash Redis REST URL | - | 125 | | `UPSTASH_REST_TOKEN` | Upstash Redis REST Token | - | 126 | | `SYSTEM_INIT_MESSAGE` | 系統初始化訊息 | You are a helpful assistant. | 127 | | `SYSTEM_INIT_MESSAGE_ROLE` | 系統訊息角色 | system | 128 | | `GEMINI_API_KEY` | Google Gemini API 金鑰 | - | 129 | | `GOOGLE_MODELS` | 使用的 Google 模型(逗號分隔) | - | 130 | | `GEMINI_ENDPOINT` | Gemini API 端點 | https://generativelanguage.googleapis.com/v1beta/models | 131 | | `GROQ_API_KEY` | Groq API 金鑰 | - | 132 | | `GROQ_MODELS` | 使用的 Groq 模型(逗號分隔) | - | 133 | | `MAX_HISTORY_LENGTH` | 最大歷史記錄長度 | 50 | 134 | | `CLAUDE_API_KEY` | Anthropic Claude API 金鑰 | - | 135 | | `CLAUDE_MODELS` | 使用的 Claude 模型(逗號分隔) | - | 136 | | `CLAUDE_ENDPOINT` | Claude API 端點 | https://api.anthropic.com/v1/chat/completions | 137 | 138 | 請確保在部署到 Vercel 或其他平台時,將這些環境變數添加到專案的環境設定中。 139 | 140 | ## 使用指南 📖 141 | 142 | - `/start` - 初始化機器人 143 | - `/new` - 開始新的對話 144 | - `/history` - 查看對話歷史摘要 145 | - `/help` - 獲取說明資訊 146 | - `/switchmodel <模型名稱>` - 切換 AI 模型 147 | - `/img <描述> [尺寸]` - 生成圖像 148 | - `/language <語言代碼>` - 切換介面語言 149 | - 發送圖片以進行分析 150 | - 直接發送訊息進行對話 151 | 152 | 支援的語言(使用 /language 指令): 153 | - 英語 (en) 154 | - 簡體中文 (zh-cn) 155 | - 繁體中文 (zh-hant) 156 | - 日語 (ja) 157 | - 西班牙語 (es) 158 | - 法語 (fr) 159 | - 俄語 (ru) 160 | - 德語 (de) 161 | 162 | ## 注意事項 ⚠️ 163 | 164 | - 合理使用 API 配額,特別是在使用圖像功能時 💸 165 | - 妥善保管環境變數和 API 金鑰 🔒 166 | - 不同 AI 模型可能有不同的特性和限制 🔄 167 | - 定期檢查和更新相依套件,以確保安全性和效能 🔧 168 | 169 | ## 貢獻 🤝 170 | 171 | 歡迎提交 Pull Requests 或開啟 Issues 來改進這個專案!您的貢獻將使這個 AI 助理變得更加強大和有趣。 172 | 173 | ## 授權條款 📜 174 | 175 | 本專案採用 [MIT 授權條款](https://choosealicense.com/licenses/mit/)。 176 | 177 | --- 178 | 179 | 關於「使用 Vercel 部署」按鈕: 180 | 這個按鈕提供了一鍵部署到 Vercel 的功能,非常方便。但是,請注意: 181 | 182 | 1. 按鈕中的連結指向的是原始儲存庫(https://github.com/snakeying/GPT-Telegram-Bot)。 183 | 2. 如果您 fork 了這個專案並希望部署您自己的版本,您需要更新 README 中的這個按鈕連結。 184 | 3. 更新方法:將連結中的 `snakeying/GPT-Telegram-Bot` 替換為您的 GitHub 使用者名稱和儲存庫名稱。 185 | 186 | 例如,如果您的 GitHub 使用者名稱是 "yourname",您應該將按鈕的連結更改為: 187 | 188 | ```markdown 189 | [![使用 Vercel 部署](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fyourname%2FGPT-Telegram-Bot) 190 | ``` 191 | 192 | 這樣可以確保「使用 Vercel 部署」按鈕會部署您 fork 的版本,而不是原始儲存庫。 193 | -------------------------------------------------------------------------------- /locales/de.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "Hallo~👋 Sie verwenden derzeit das Modell {model}. Was kann ich für Sie tun?", 3 | "new_conversation": "Alles klar, lass uns neu anfangen! Sie verwenden jetzt das Modell {model}. Alle vorherigen Gesprächsverläufe wurden gelöscht.", 4 | "history_intro": "Hier ist eine Zusammenfassung deines Gesprächsverlaufs:\n\n", 5 | "no_history": "Oh, ich konnte keinen Gesprächsverlauf zum Zusammenfassen finden.", 6 | "help_message": "Hey, willkommen bei Ihrem persönlichen Assistenten-Bot! 👋 Hier ist eine Benutzeranleitung:\n\n🚀 Grundlegende Befehle:\n/start - Sagen Sie Hallo und beginnen Sie zu chatten\n/new - Möchten Sie neu beginnen? Dieser Befehl löscht den vorherigen Gesprächsverlauf\n/history - Sehen Sie sich an, worüber wir gesprochen haben\n/switchmodel [Modellname] - Wechseln Sie zu einem anderen Modell\n/img [Beschreibung] [Größe] - Lassen Sie mich ein Bild für Sie zeichnen!\n/language - Ändern Sie die Spracheinstellungen\n\n💬 Täglicher Chat:\nSenden Sie mir einfach eine Nachricht, und ich antworte mit dem aktuellen KI-Modell~\n\n🎨 Bilderzeugung:\n- Verwenden Sie den Befehl /img, gefolgt von Ihrer Bildbeschreibung\n- Möchten Sie eine bestimmte Größe? Fügen Sie die Größe am Ende hinzu (z.B.: 1024x1024, 1792x1024, 1024x1792)\n- Beispiel: /img Ein süßes Kätzchen, das in der Sonne spielt 1024x1024\n\n🔍 Bildanalyse:\n- Senden Sie mir ein Bild (mit oder ohne Textbeschreibung)\n- Ich werde es sorgfältig analysieren und Ihnen sagen, was ich sehe\n\n🤖 Derzeit verfügbare KI-Modelle:\n{models}\n\n😎 Aktuell verwendetes Modell: {current_model}\n\nFragen oder Vorschläge? Zögern Sie nicht, es meinem Administrator mitzuteilen~\n\nLos geht's, beginnen wir ein interessantes Gespräch! ✨", 7 | "model_switched": "Modell gewechselt zu: {model}. Der vorherige Gesprächsverlauf wurde gelöscht.", 8 | "invalid_model": "Ups, der Modellname ist ungültig oder der API-Schlüssel ist nicht gesetzt. Verfügbare Modelle sind: {available_models}", 9 | "no_api_key": "Entschuldigung, ich kann keine Bilder generieren, da Sie keinen OpenAI API-Schlüssel eingerichtet haben.", 10 | "invalid_size": "Ungültige Bildgröße: {size}. Bitte verwenden Sie eine der folgenden gültigen Größen: {valid_sizes}", 11 | "no_image_description": "Bitte geben Sie eine Bildbeschreibung an.", 12 | "processing_image": "Analysiere Ihr Bild, bitte warten Sie einen Moment...", 13 | "unsupported_message": "Entschuldigung, ich kann nur Textnachrichten und Bilder verarbeiten. Bitte überprüfen Sie Ihre Datei.", 14 | "error_message": "Ups, sieht aus, als hätten wir ein kleines Problem 😅\n\nBeim Verarbeiten Ihrer Nachricht ist eine unerwartete Situation aufgetreten.\nKeine Sorge, so etwas passiert manchmal.\n\n💡 Vorschläge:\n1. Versuchen Sie es später noch einmal\n2. Verwenden Sie den Befehl /help, um die Benutzeranleitung anzuzeigen, vielleicht finden Sie dort eine Lösung\n3. Wenn das Problem weiterhin besteht, kontaktieren Sie bitte den Administrator\n\nVielen Dank für Ihr Verständnis und Ihre Geduld!", 15 | "choose_language": "Bitte wählen Sie Ihre Sprache:", 16 | "language_set": "Sprache erfolgreich eingestellt!", 17 | "language_changed": "Ihre Sprache wurde auf Deutsch geändert.", 18 | "en": "Englisch", 19 | "zh-cn": "Vereinfachtes Chinesisch", 20 | "zh-hant": "Traditionelles Chinesisch", 21 | "ja": "Japanisch", 22 | "es": "Spanisch", 23 | "fr": "Französisch", 24 | "ru": "Russisch", 25 | "de": "Deutsch", 26 | "no_image": "Bitte fügen Sie ein Bild für die Analyse bei.", 27 | "use_help_command": "Sie können den Befehl /help für Nutzungsanweisungen verwenden.", 28 | "provide_image_description": "Bitte geben Sie eine Beschreibung oder Frage für die Bildanalyse an.", 29 | "forgot_model_name": "Ups, haben Sie vergessen, den Modellnamen einzugeben? Verfügbare Modelle sind: {available_models}", 30 | "cmd_start": "Bot initialisieren", 31 | "cmd_new": "Neue Unterhaltung beginnen", 32 | "cmd_history": "Gesprächsverlauf-Zusammenfassung anzeigen", 33 | "cmd_help": "Hilfeinformationen erhalten", 34 | "cmd_switchmodel": "AI-Modell wechseln", 35 | "cmd_img": "Bild generieren", 36 | "cmd_language": "Oberflächensprache wechseln" 37 | } 38 | -------------------------------------------------------------------------------- /locales/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "Hi~👋 You're currently using the {model} model. What can I do for you?", 3 | "new_conversation": "Alright, let's start over! You're now using the {model} model. All previous conversation history has been cleared.", 4 | "history_intro": "Here's a summary of our conversation history:\n\n", 5 | "no_history": "Oops, I couldn't find any conversation history to summarize.", 6 | "help_message": "Hey, welcome to your personal assistant bot! 👋 Here's a user guide:\n\n🚀 Basic commands:\n/start - Say hi and start chatting\n/new - Want to start over? This command clears previous conversation history\n/history - Review what we've talked about\n/switchmodel [model name] - Switch to a different model\n/img [description] [size] - Let me draw an image for you!\n/language - Change language settings\n\n💬 Daily chat:\nJust send me a message, and I'll reply using the current AI model~\n\n🎨 Image generation:\n- Use the /img command, followed by your image description\n- Want a specific size? Add the size at the end (e.g., 1024x1024, 1792x1024, 1024x1792)\n- Example: /img A cute kitten playing in the sunshine 1024x1024\n\n🔍 Image analysis:\n- Send me an image (with or without text description)\n- I'll analyze it carefully and tell you what I see\n\n🤖 Currently available AI models:\n{models}\n\n😎 Currently using model: {current_model}\n\nAny questions or suggestions? Feel free to tell my admin~\n\nCome on, let's start an interesting conversation! ✨", 7 | "model_switched": "Model switched to: {model}. Previous conversation history has been cleared.", 8 | "invalid_model": "Oops, the model name is invalid or the API key is not set. Available models are: {available_models}", 9 | "no_api_key": "Sorry, I can't generate images because you haven't set up an OpenAI API key.", 10 | "invalid_size": "Invalid image size: {size}. Please use one of the following valid sizes: {valid_sizes}", 11 | "no_image_description": "Please provide an image description.", 12 | "processing_image": "Analyzing your image, please wait a moment...", 13 | "unsupported_message": "Sorry, I can only process text messages and images. Please check your file.", 14 | "error_message": "Oops, looks like we've hit a small snag 😅\n\nAn unexpected situation occurred while processing your message.\nDon't worry, these things happen occasionally.\n\n💡 Suggestions:\n1. Try again later\n2. Use the /help command to view the user guide, you might find a solution there\n3. If the problem persists, please contact the admin\n\nThank you for your understanding and patience!", 15 | "choose_language": "Please choose your language:", 16 | "language_set": "Language set successfully!", 17 | "language_changed": "Your language has been changed to English.", 18 | "en": "English", 19 | "zh-cn": "Simplified Chinese", 20 | "zh-hant": "Traditional Chinese", 21 | "ja": "Japanese", 22 | "es": "Spanish", 23 | "fr": "French", 24 | "ru": "Russian", 25 | "de": "German", 26 | "no_image": "Please attach an image for analysis.", 27 | "use_help_command": "You can use the /help command for usage instructions.", 28 | "provide_image_description": "Please provide a description or question for the image analysis.", 29 | "forgot_model_name": "Oops, you forgot to input the model name? Available models are: {available_models}", 30 | "cmd_start": "Initialize the bot", 31 | "cmd_new": "Start a new conversation", 32 | "cmd_help": "Get help information", 33 | "cmd_switchmodel": "Switch AI model", 34 | "cmd_img": "Generate image", 35 | "cmd_language": "Switch interface language", 36 | "cmd_history": "View conversation history summary" 37 | } -------------------------------------------------------------------------------- /locales/es.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "¡Hola~👋 Actualmente estás usando el modelo {model}. ¿En qué puedo ayudarte?", 3 | "new_conversation": "¡De acuerdo, empecemos de nuevo! Ahora estás usando el modelo {model}. Todo el historial de conversación anterior ha sido borrado.", 4 | "history_intro": "Aquí tienes un resumen de tu historial de conversaciones:\n\n", 5 | "no_history": "Ups, no pude encontrar ningún historial de conversaciones para resumir.", 6 | "help_message": "¡Hola, bienvenido a tu bot asistente personal! 👋 Aquí tienes una guía de usuario:\n\n🚀 Comandos básicos:\n/start - Saluda y comienza a chatear\n/new - ¿Quieres empezar de nuevo? Este comando borra el historial de conversación anterior\n/history - Revisa de qué hemos hablado\n/switchmodel [nombre del modelo] - Cambia a un modelo diferente\n/img [descripción] [tamaño] - ¡Déjame dibujar una imagen para ti!\n/language - Cambia la configuración de idioma\n\n💬 Chat diario:\nSolo envíame un mensaje y te responderé usando el modelo de IA actual~\n\n🎨 Generación de imágenes:\n- Usa el comando /img, seguido de tu descripción de la imagen\n- ¿Quieres un tamaño específico? Añade el tamaño al final (ej. 1024x1024, 1792x1024, 1024x1792)\n- Ejemplo: /img Un lindo gatito jugando bajo el sol 1024x1024\n\n🔍 Análisis de imágenes:\n- Envíame una imagen (con o sin descripción de texto)\n- La analizaré cuidadosamente y te diré lo que veo\n\n🤖 Modelos de IA actualmente disponibles:\n{models}\n\n😎 Modelo en uso actualmente: {current_model}\n\n¿Alguna pregunta o sugerencia? ¡No dudes en decírselo a mi administrador~\n\n¡Vamos, comencemos una conversación interesante! ✨", 7 | "model_switched": "Modelo cambiado a: {model}. El historial de conversación anterior ha sido borrado.", 8 | "invalid_model": "Ups, el nombre del modelo no es válido o la clave API no está configurada. Los modelos disponibles son: {available_models}", 9 | "no_api_key": "Lo siento, no puedo generar imágenes porque no has configurado una clave API de OpenAI.", 10 | "invalid_size": "Tamaño de imagen inválido: {size}. Por favor, usa uno de los siguientes tamaños válidos: {valid_sizes}", 11 | "no_image_description": "Por favor, proporciona una descripción de la imagen.", 12 | "processing_image": "Analizando tu imagen, por favor espera un momento...", 13 | "unsupported_message": "Lo siento, solo puedo procesar mensajes de texto e imágenes. Por favor, verifica tu archivo.", 14 | "error_message": "Ups, parece que hemos encontrado un pequeño problema 😅\n\nOcurrió una situación inesperada mientras procesaba tu mensaje.\nNo te preocupes, estas cosas suceden ocasionalmente.\n\n💡 Sugerencias:\n1. Intenta de nuevo más tarde\n2. Usa el comando /help para ver la guía de usuario, podrías encontrar una solución allí\n3. Si el problema persiste, por favor contacta al administrador\n\n¡Gracias por tu comprensión y paciencia!", 15 | "choose_language": "Por favor, elige tu idioma:", 16 | "language_set": "¡Idioma configurado con éxito!", 17 | "language_changed": "Tu idioma ha sido cambiado a Español.", 18 | "en": "Inglés", 19 | "zh-cn": "Chino Simplificado", 20 | "zh-hant": "Chino Tradicional", 21 | "ja": "Japonés", 22 | "es": "Español", 23 | "fr": "Francés", 24 | "ru": "Ruso", 25 | "de": "Alemán", 26 | "no_image": "Por favor, adjunta una imagen para el análisis.", 27 | "use_help_command": "Puedes usar el comando /help para ver las instrucciones de uso.", 28 | "provide_image_description": "Por favor, proporciona una descripción o pregunta para el análisis de la imagen.", 29 | "forgot_model_name": "Ups, ¿olvidaste introducir el nombre del modelo? Los modelos disponibles son: {available_models}", 30 | "cmd_start": "Inicializar el bot", 31 | "cmd_new": "Iniciar una nueva conversación", 32 | "cmd_history": "Ver resumen del historial de conversaciones", 33 | "cmd_help": "Obtener información de ayuda", 34 | "cmd_switchmodel": "Cambiar modelo de IA", 35 | "cmd_img": "Generar imagen", 36 | "cmd_language": "Cambiar el idioma de la interfaz" 37 | } 38 | -------------------------------------------------------------------------------- /locales/fr.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "Salut~👋 Vous utilisez actuellement le modèle {model}. Que puis-je faire pour vous ?", 3 | "new_conversation": "D'accord, recommençons ! Vous utilisez maintenant le modèle {model}. Tout l'historique de conversation précédent a été effacé.", 4 | "history_intro": "Voici un résumé de votre historique de conversation :\n\n", 5 | "no_history": "Oups, je n'ai trouvé aucun historique de conversation à résumer.", 6 | "help_message": "Hé, bienvenue sur votre bot assistant personnel ! 👋 Voici un guide d'utilisation :\n\n🚀 Commandes de base :\n/start - Dis bonjour et commence à discuter\n/new - Vous voulez recommencer ? Cette commande efface l'historique de conversation précédent\n/history - Revoyez ce dont nous avons parlé\n/switchmodel [nom du modèle] - Passez à un modèle différent\n/img [description] [taille] - Laissez-moi dessiner une image pour vous !\n/language - Changez les paramètres de langue\n\n💬 Chat quotidien :\nEnvoyez-moi simplement un message, et je répondrai en utilisant le modèle d'IA actuel~\n\n🎨 Génération d'images :\n- Utilisez la commande /img, suivie de votre description d'image\n- Vous voulez une taille spécifique ? Ajoutez la taille à la fin (ex : 1024x1024, 1792x1024, 1024x1792)\n- Exemple : /img Un mignon chaton jouant au soleil 1024x1024\n\n🔍 Analyse d'image :\n- Envoyez-moi une image (avec ou sans description textuelle)\n- Je l'analyserai attentivement et vous dirai ce que je vois\n\n🤖 Modèles d'IA actuellement disponibles :\n{models}\n\n😎 Modèle actuellement utilisé : {current_model}\n\nDes questions ou des suggestions ? N'hésitez pas à en informer mon administrateur~\n\nAllez, commençons une conversation intéressante ! ✨", 7 | "model_switched": "Modèle changé pour : {model}. L'historique de conversation précédent a été effacé.", 8 | "invalid_model": "Oups, le nom du modèle est invalide ou la clé API n'est pas définie. Les modèles disponibles sont : {available_models}", 9 | "no_api_key": "Désolé, je ne peux pas générer d'images car vous n'avez pas configuré de clé API OpenAI.", 10 | "invalid_size": "Taille d'image invalide : {size}. Veuillez utiliser l'une des tailles valides suivantes : {valid_sizes}", 11 | "no_image_description": "Veuillez fournir une description de l'image.", 12 | "processing_image": "Analyse de votre image en cours, veuillez patienter un moment...", 13 | "unsupported_message": "Désolé, je ne peux traiter que des messages texte et des images. Veuillez vérifier votre fichier.", 14 | "error_message": "Oups, on dirait qu'on a rencontré un petit problème 😅\n\nUne situation inattendue s'est produite lors du traitement de votre message.\nNe vous inquiétez pas, ces choses arrivent parfois.\n\n💡 Suggestions :\n1. Essayez à nouveau plus tard\n2. Utilisez la commande /help pour voir le guide d'utilisation, vous pourriez y trouver une solution\n3. Si le problème persiste, veuillez contacter l'administrateur\n\nMerci pour votre compréhension et votre patience !", 15 | "choose_language": "Veuillez choisir votre langue :", 16 | "language_set": "Langue définie avec succès !", 17 | "language_changed": "Votre langue a été changée en Français.", 18 | "en": "Anglais", 19 | "zh-cn": "Chinois simplifié", 20 | "zh-hant": "Chinois traditionnel", 21 | "ja": "Japonais", 22 | "es": "Espagnol", 23 | "fr": "Français", 24 | "ru": "Russe", 25 | "de": "Allemand", 26 | "no_image": "Veuillez joindre une image pour l'analyse.", 27 | "use_help_command": "Vous pouvez utiliser la commande /help pour les instructions d'utilisation.", 28 | "provide_image_description": "Veuillez fournir une description ou une question pour l'analyse de l'image.", 29 | "forgot_model_name": "Oups, avez-vous oublié d'entrer le nom du modèle ? Les modèles disponibles sont : {available_models}", 30 | "cmd_start": "Initialiser le bot", 31 | "cmd_new": "Démarrer une nouvelle conversation", 32 | "cmd_history": "Voir le résumé de l'historique des conversations", 33 | "cmd_help": "Obtenir des informations d'aide", 34 | "cmd_switchmodel": "Changer de modèle AI", 35 | "cmd_img": "Générer une image", 36 | "cmd_language": "Changer la langue de l'interface" 37 | } 38 | -------------------------------------------------------------------------------- /locales/ja.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "こんにちは〜👋 現在 {model} モデルを使用しています。何かお手伝いできることはありますか?", 3 | "new_conversation": "はい、新しく始めましょう!現在 {model} モデルを使用しています。以前の会話履歴はすべてクリアされました。", 4 | "history_intro": "こちらはあなたの会話履歴の概要です:\n\n", 5 | "no_history": "おっと、要約できる会話履歴が見つかりませんでした。", 6 | "help_message": "やあ、あなた専用のアシスタントボットへようこそ!👋 使い方ガイドはこちらです:\n\n🚀 基本コマンド:\n/start - 挨拶して、チャットを始めましょう\n/new - 新しく始めたいですか?このコマンドで以前の会話履歴をクリアします\n/history - 私たちが話したことを振り返ります\n/switchmodel [モデル名] - 別のモデルに切り替えます\n/img [説明] [サイズ] - あなたのために画像を描きましょう!\n/language - 言語設定を変更します\n\n💬 日常会話:\nメッセージを送るだけで、現在のAIモデルを使って返信します〜\n\n🎨 画像生成:\n- /imgコマンドを使用し、その後に画像の説明を入力してください\n- 特定のサイズが欲しいですか?最後にサイズを追加してください(例:1024x1024, 1792x1024, 1024x1792)\n- 例:/img 日光の中で遊ぶかわいい子猫 1024x1024\n\n🔍 画像分析:\n- 画像を送ってください(テキストの説明があってもなくても大丈夫です)\n- 注意深く分析し、見たものをお伝えします\n\n🤖 現在利用可能なAIモデル:\n{models}\n\n😎 現在使用中のモデル:{current_model}\n\n質問や提案がありますか?遠慮なく管理者に伝えてください〜\n\nさあ、面白い会話を始めましょう!✨", 7 | "model_switched": "モデルが {model} に切り替わりました。以前の会話履歴はクリアされました。", 8 | "invalid_model": "申し訳ありませんが、モデル名が無効であるか、APIキーが設定されていません。利用可能なモデル:{available_models}", 9 | "no_api_key": "申し訳ありませんが、OpenAI APIキーが設定されていないため、画像を生成できません。", 10 | "invalid_size": "無効な画像サイズ:{size}。以下の有効なサイズのいずれかを使用してください:{valid_sizes}", 11 | "no_image_description": "画像の説明を入力してください。", 12 | "processing_image": "画像を分析中です。少々お待ちください...", 13 | "unsupported_message": "申し訳ありませんが、テキストメッセージと画像のみ処理できます。ファイルを確認してください。", 14 | "error_message": "おっと、小さな問題が発生したようです 😅\n\nメッセージの処理中に予期せぬ状況が発生しました。\n心配しないでください、こういうことは時々起こります。\n\n💡 提案:\n1. 後でもう一度試してみてください\n2. /helpコマンドを使用してユーザーガイドを確認してください。そこに解決策があるかもしれません\n3. 問題が続く場合は、管理者に連絡してください\n\nご理解とご patience をありがとうございます!", 15 | "choose_language": "言語を選択してください:", 16 | "language_set": "言語が正常に設定されました!", 17 | "language_changed": "言語が日本語に変更されました。", 18 | "en": "英語", 19 | "zh-cn": "簡体字中国語", 20 | "zh-hant": "繁体字中国語", 21 | "ja": "日本語", 22 | "es": "スペイン語", 23 | "fr": "フランス語", 24 | "ru": "ロシア語", 25 | "de": "ドイツ語", 26 | "no_image": "分析用の画像を添付してください。", 27 | "use_help_command": "使用方法については /help コマンドを使用してください。", 28 | "provide_image_description": "画像分析のための説明や質問を提供してください。", 29 | "forgot_model_name": "おっと、モデル名の入力を忘れましたか?利用可能なモデル:{available_models}", 30 | "cmd_start": "ボットを初期化する", 31 | "cmd_new": "新しい会話を開始する", 32 | "cmd_history": "会話履歴の概要を表示", 33 | "cmd_help": "ヘルプ情報を取得する", 34 | "cmd_switchmodel": "AIモデルを切り替える", 35 | "cmd_img": "画像を生成する", 36 | "cmd_language": "インターフェース言語を切り替える" 37 | } 38 | -------------------------------------------------------------------------------- /locales/ru.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "Привет~👋 В настоящее время вы используете модель {model}. Чем я могу вам помочь?", 3 | "new_conversation": "Хорошо, давайте начнем сначала! Теперь вы используете модель {model}. Вся предыдущая история разговора была очищена.", 4 | "history_intro": "Вот краткое изложение вашей истории разговоров:\n\n", 5 | "no_history": "Упс, не удалось найти историю разговоров для резюме.", 6 | "help_message": "Привет, добро пожаловать в вашего персонального бота-ассистента! 👋 Вот руководство пользователя:\n\n🚀 Основные команды:\n/start - Поздоровайтесь и начните общение\n/new - Хотите начать сначала? Эта команда очистит предыдущую историю разговора\n/history - Просмотрите, о чем мы говорили\n/switchmodel [название модели] - Переключитесь на другую модель\n/img [описание] [размер] - Позвольте мне нарисовать для вас картинку!\n/language - Измените языковые настройки\n\n💬 Ежедневное общение:\nПросто отправьте мне сообщение, и я отвечу, используя текущую модель ИИ~\n\n🎨 Генерация изображений:\n- Используйте команду /img, за которой следует описание вашего изображения\n- Хотите определенный размер? Добавьте размер в конце (например: 1024x1024, 1792x1024, 1024x1792)\n- Пример: /img Милый котенок, играющий на солнышке 1024x1024\n\n🔍 Анализ изображений:\n- Отправьте мне изображение (с текстовым описанием или без него)\n- Я внимательно проанализирую его и расскажу, что вижу\n\n🤖 Доступные в настоящее время модели ИИ:\n{models}\n\n😎 Текущая используемая модель: {current_model}\n\nЕсть вопросы или предложения? Не стесняйтесь сообщить моему администратору~\n\nДавайте начнем интересный разговор! ✨", 7 | "model_switched": "Модель переключена на: {model}. Предыдущая история разговора была очищена.", 8 | "invalid_model": "Упс, название модели недействительно или API-ключ не установлен. Доступные модели: {available_models}", 9 | "no_api_key": "Извините, я не могу генерировать изображения, потому что вы не настроили API-ключ OpenAI.", 10 | "invalid_size": "Недопустимый размер изображения: {size}. Пожалуйста, используйте один из следующих допустимых размеров: {valid_sizes}", 11 | "no_image_description": "Пожалуйста, предоставьте описание изображения.", 12 | "processing_image": "Анализирую ваше изображение, подождите момент...", 13 | "unsupported_message": "Извините, я могу обрабатывать только текстовые сообщения и изображения. Пожалуйста, проверьте ваш файл.", 14 | "error_message": "Ой, кажется, мы столкнулись с небольшой проблемой 😅\n\nПри обработке вашего сообщения возникла непредвиденная ситуация.\nНе волнуйтесь, такое иногда случается.\n\n💡 Предложения:\n1. Попробуйте еще раз позже\n2. Используйте команду /help, чтобы просмотреть руководство пользователя, возможно, вы найдете там решение\n3. Если проблема сохраняется, пожалуйста, свяжитесь с администратором\n\nСпасибо за ваше понимание и терпение!", 15 | "choose_language": "Пожалуйста, выберите ваш язык:", 16 | "language_set": "Язык успешно установлен!", 17 | "language_changed": "Ваш язык был изменен на Русский.", 18 | "en": "Английский", 19 | "zh-cn": "Упрощенный китайский", 20 | "zh-hant": "Традиционный китайский", 21 | "ja": "Японский", 22 | "es": "Испанский", 23 | "fr": "Французский", 24 | "ru": "Русский", 25 | "de": "Немецкий", 26 | "no_image": "Пожалуйста, прикрепите изображение для анализа.", 27 | "use_help_command": "Вы можете использовать команду /help для получения инструкций по использованию.", 28 | "provide_image_description": "Пожалуйста, предоставьте описание или вопрос для анализа изображения.", 29 | "forgot_model_name": "Ой, вы забыли ввести название модели? Доступные модели: {available_models}", 30 | "cmd_start": "Инициализировать бота", 31 | "cmd_new": "Начать новый разговор", 32 | "cmd_history": "Просмотреть краткое изложение истории разговоров", 33 | "cmd_help": "Получить информацию помощи", 34 | "cmd_switchmodel": "Сменить модель ИИ", 35 | "cmd_img": "Создать изображение", 36 | "cmd_language": "Сменить язык интерфейса" 37 | } 38 | -------------------------------------------------------------------------------- /locales/zh-cn.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "Hi~👋 你目前正在使用的模型是 {model}。请问我可以为你做些什么呢?", 3 | "new_conversation": "好的,让我们重新开始吧!你现在使用的模型是 {model}。之前所有的对话记录已被清除了哦", 4 | "history_intro": "以下是我们的对话历史摘要:\n\n", 5 | "no_history": "哎呀,没有找到任何可以总结的对话历史。", 6 | "help_message": "嘿,欢迎使用你的专属助手机器人!👋 这里是使用指南:\n\n🚀 基本命令:\n/start - 和我打个招呼,开始聊天吧\n/new - 想要重新开始?这个命令可以清除之前的对话记录\n/history - 回顾一下我们之前聊了什么\n/switchmodel [模型名称] - 换个模型聊聊?\n/img [描述] [尺寸] - 来,让我为你画张图!\n/language - 更改语言设置\n\n💬 日常聊天:\n直接发消息给我就行,我会用当前的 AI 模型回复你哦~\n\n🎨 生成图片:\n- 使用 /img 命令,后面跟上你想要的图片描述\n- 想要特定尺寸?可以在最后加上尺寸大小(比如:1024x1024, 1792x1024, 1024x1792)\n- 举个例子:/img 一只可爱的小猫咪在阳光下玩耍 1024x1024\n\n🔍 图片分析:\n- 发送一张图片给我(带不带文字描述都行)\n- 我会仔细分析,然后告诉你我看到了什么\n\n🤖 当前可用的 AI 模型:\n{models}\n\n😎 目前正在使用的模型:{current_model}\n\n有什么问题或建议?随时告诉我的管理员~\n\n来吧,让我们开始有趣的对话吧!✨", 7 | "model_switched": "模型已切换到: {model}。之前的对话记录已经清除了哦。", 8 | "invalid_model": "哎呀,模型名称无效或者API密钥未设置。可用的模型有: {available_models}", 9 | "no_api_key": "抱歉,因为你没有设置OpenAI API密钥,无法生成图片。", 10 | "invalid_size": "无效的图片大小: {size}。请使用以下有效尺寸之一: {valid_sizes}", 11 | "no_image_description": "请提供图片描述。", 12 | "processing_image": "正在分析你的图片,请稍等片刻...", 13 | "unsupported_message": "抱歉,我只能处理文字消息和图片,请检查你的文件。", 14 | "error_message": "哎呀,看来出了点小问题 😅\n\n处理你的消息时遇到了意外情况。\n不用担心,这种事情偶尔会发生。\n\n💡 建议:\n1. 稍后再试一次\n2. 使用 /help 命令查看使用指南,也许能找到解决方法\n3. 如果问题持续存在,请联系管理员\n\n感谢你的理解和耐心!", 15 | "choose_language": "请选择你的语言:", 16 | "language_set": "语言设置成功!", 17 | "language_changed": "您的语言已更改为简体中文。", 18 | "en": "英语", 19 | "zh-cn": "简体中文", 20 | "zh-hant": "繁体中文", 21 | "ja": "日语", 22 | "es": "西班牙语", 23 | "fr": "法语", 24 | "ru": "俄语", 25 | "de": "德语", 26 | "no_image": "请附上一张要分析的图片。", 27 | "use_help_command": "请使用 /help 命令查看使用说明。", 28 | "provide_image_description": "请为图片分析提供一个描述或问题。", 29 | "forgot_model_name": "哎呀,您是不是忘记输入模型名称了?可用的模型有:{available_models}", 30 | "cmd_start": "初始化机器人", 31 | "cmd_new": "开始新的对话", 32 | "cmd_history": "查看对话历史摘要", 33 | "cmd_help": "获取帮助信息", 34 | "cmd_switchmodel": "切换AI模型", 35 | "cmd_img": "生成图片", 36 | "cmd_language": "切换界面语言" 37 | } -------------------------------------------------------------------------------- /locales/zh-hant.json: -------------------------------------------------------------------------------- 1 | { 2 | "welcome": "Hi~👋 你目前正在使用的模型是 {model}。請問我可以為你做些什麼呢?", 3 | "new_conversation": "好的,讓我們重新開始吧!你現在使用的模型是 {model}。之前所有的對話記錄已被清除了哦", 4 | "history_intro": "以下是你的對話歷史摘要:\n\n", 5 | "no_history": "哎呀,沒有找到任何可以總結的對話歷史。", 6 | "help_message": "嘿,歡迎使用你的專屬助手機器人!👋 這裡是使用指南:\n\n🚀 基本命令:\n/start - 和我打個招呼,開始聊天吧\n/new - 想要重新開始?這個命令可以清除之前的對話記錄\n/history - 回顧一下我們之前聊了什麼\n/switchmodel [模型名稱] - 換個模型聊聊?\n/img [描述] [尺寸] - 來,讓我為你畫張圖!\n/language - 更改語言設置\n\n💬 日常聊天:\n直接發消息給我就行,我會用當前的 AI 模型回覆你哦~\n\n🎨 生成圖片:\n- 使用 /img 命令,後面跟上你想要的圖片描述\n- 想要特定尺寸?可以在最後加上尺寸大小(比如:1024x1024, 1792x1024, 1024x1792)\n- 舉個例子:/img 一隻可愛的小貓咪在陽光下玩耍 1024x1024\n\n🔍 圖片分析:\n- 發送一張圖片給我(帶不帶文字描述都行)\n- 我會仔細分析,然後告訴你我看到了什麼\n\n🤖 當前可用的 AI 模型:\n{models}\n\n😎 目前正在使用的模型:{current_model}\n\n有什麼問題或建議?隨時告訴我的管理員~\n\n來吧,讓我們開始有趣的對話吧!✨", 7 | "model_switched": "模型已切換到:{model}。之前的對話記錄已經清除了哦。", 8 | "invalid_model": "哎呀,模型名稱無效或者API密鑰未設置。可用的模型有:{available_models}", 9 | "no_api_key": "抱歉,因為你沒有設置OpenAI API密鑰,無法生成圖片。", 10 | "invalid_size": "無效的圖片大小:{size}。請使用以下有效尺寸之一:{valid_sizes}", 11 | "no_image_description": "請提供圖片描述。", 12 | "processing_image": "正在分析你的圖片,請稍等片刻...", 13 | "unsupported_message": "抱歉,我只能處理文字消息和圖片,請檢查你的文件。", 14 | "error_message": "哎呀,看來出了點小問題 😅\n\n處理你的消息時遇到了意外情況。\n不用擔心,這種事情偶爾會發生。\n\n💡 建議:\n1. 稍後再試一次\n2. 使用 /help 命令查看使用指南,也許能找到解決方法\n3. 如果問題持續存在,請聯繫管理員\n\n感謝你的理解和耐心!", 15 | "choose_language": "請選擇你的語言:", 16 | "language_set": "語言設置成功!", 17 | "language_changed": "您的語言已更改為繁體中文。", 18 | "en": "英語", 19 | "zh-cn": "簡體中文", 20 | "zh-hant": "繁體中文", 21 | "ja": "日語", 22 | "es": "西班牙語", 23 | "fr": "法語", 24 | "ru": "俄語", 25 | "de": "德語", 26 | "no_image": "請附上一張要分析的圖片。", 27 | "use_help_command": "請使用 /help 命令查看使用說明。", 28 | "provide_image_description": "請為圖片分析提供一個描述或問題。", 29 | "forgot_model_name": "哎呀,您是不是忘記輸入模型名稱了?可用的模型有:{available_models}", 30 | "cmd_start": "初始化機器人", 31 | "cmd_new": "開始新的對話", 32 | "cmd_history": "查看對話歷史摘要", 33 | "cmd_help": "獲取幫助信息", 34 | "cmd_switchmodel": "切換AI模型", 35 | "cmd_img": "生成圖片", 36 | "cmd_language": "切換界面語言" 37 | } 38 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gpt-telegram-bot", 3 | "version": "1.0.0", 4 | "description": "Your own GPT Telegram bot on Vercel", 5 | "main": "api/telegram.js", 6 | "scripts": { 7 | "start": "node api/telegram.js", 8 | "dev": "nodemon api/telegram.js" 9 | }, 10 | "dependencies": { 11 | "dotenv": "^10.0.0", 12 | "@upstash/redis": "^1.20.2", 13 | "node-telegram-bot-api": "^0.54.0", 14 | "openai": "^4.0.0", 15 | "file-type": "^16.5.3", 16 | "axios": "^0.21.1", 17 | "@google/generative-ai": "^0.1.0" 18 | }, 19 | "devDependencies": { 20 | "nodemon": "^2.0.7" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | GPT-Telegram-Bot Deployment 7 | 131 | 132 | 133 |
134 |

Deployment Successful! 🎉

135 |
136 |

Your GPT-Telegram-Bot has been successfully deployed to Vercel.

137 |

Next Steps:

138 |
    139 |
  1. Set up your Telegram Webhook to connect your bot.
  2. 140 |
  3. Configure your environment variables if you haven't already.
  4. 141 |
142 |

For detailed instructions and troubleshooting, please refer to My GitHub repository:

143 | Visit GitHub Repository 144 |

Happy chatting with your new AI assistant! 🤖💬

145 |
146 |
147 | 148 | 185 | 186 | 187 | -------------------------------------------------------------------------------- /src/api.js: -------------------------------------------------------------------------------- 1 | const { OpenAI } = require('openai'); 2 | const { OPENAI_API_KEY, OPENAI_BASE_URL, SYSTEM_INIT_MESSAGE, SYSTEM_INIT_MESSAGE_ROLE } = require('./config'); 3 | 4 | const client = new OpenAI({ 5 | apiKey: OPENAI_API_KEY, 6 | baseURL: OPENAI_BASE_URL 7 | }); 8 | 9 | async function generateResponse(prompt, conversationHistory, model) { 10 | console.log('Generating response for:', prompt); 11 | console.log('Using model:', model); 12 | console.log('Conversation history:', JSON.stringify(conversationHistory)); 13 | 14 | try { 15 | const messages = [ 16 | { role: SYSTEM_INIT_MESSAGE_ROLE, content: SYSTEM_INIT_MESSAGE }, 17 | ...conversationHistory, 18 | { role: 'user', content: prompt } 19 | ]; 20 | 21 | const response = await client.chat.completions.create({ 22 | model: model, 23 | messages: messages, 24 | temperature: 0.7, 25 | }); 26 | 27 | console.log('Received response from OpenAI API'); 28 | 29 | if (response.choices && response.choices.length > 0) { 30 | const generatedText = response.choices[0].message.content.trim(); 31 | console.log('Generated text:', generatedText); 32 | return generatedText; 33 | } else { 34 | throw new Error('Unexpected API response structure'); 35 | } 36 | } catch (error) { 37 | console.error('Error in generateResponse function:', error); 38 | throw new Error(`Failed to generate response: ${error.message}`); 39 | } 40 | } 41 | 42 | async function* generateStreamResponse(prompt, conversationHistory, model) { 43 | console.log('Generating stream response for:', prompt); 44 | console.log('Using model:', model); 45 | console.log('Conversation history:', JSON.stringify(conversationHistory)); 46 | 47 | try { 48 | const messages = [ 49 | { role: SYSTEM_INIT_MESSAGE_ROLE, content: SYSTEM_INIT_MESSAGE }, 50 | ...conversationHistory, 51 | { role: 'user', content: prompt } 52 | ]; 53 | 54 | const stream = await client.chat.completions.create({ 55 | model: model, 56 | messages: messages, 57 | temperature: 0.7, 58 | stream: true, 59 | }); 60 | 61 | console.log('Received stream from OpenAI API'); 62 | 63 | for await (const chunk of stream) { 64 | if (chunk.choices && chunk.choices[0] && chunk.choices[0].delta && chunk.choices[0].delta.content) { 65 | yield chunk.choices[0].delta.content; 66 | } 67 | } 68 | } catch (error) { 69 | console.error('Error in generateStreamResponse function:', error); 70 | throw new Error(`Failed to generate stream response: ${error.message}`); 71 | } 72 | } 73 | 74 | module.exports = { generateResponse, generateStreamResponse }; 75 | -------------------------------------------------------------------------------- /src/azureOpenAI.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | const { 3 | AZURE_OPENAI_API_KEY, 4 | AZURE_OPENAI_ENDPOINT, 5 | SYSTEM_INIT_MESSAGE, 6 | SYSTEM_INIT_MESSAGE_ROLE 7 | } = require('./config'); 8 | 9 | async function generateAzureOpenAIResponse(prompt, conversationHistory, model) { 10 | try { 11 | const response = await axios.post( 12 | `${AZURE_OPENAI_ENDPOINT}/openai/deployments/${model}/chat/completions?api-version=2023-06-01`, 13 | { 14 | messages: [ 15 | { role: SYSTEM_INIT_MESSAGE_ROLE, content: SYSTEM_INIT_MESSAGE }, 16 | ...conversationHistory, 17 | { role: 'user', content: prompt } 18 | ], 19 | stream: true 20 | }, 21 | { 22 | headers: { 23 | 'Content-Type': 'application/json', 24 | 'api-key': AZURE_OPENAI_API_KEY 25 | }, 26 | responseType: 'stream' 27 | } 28 | ); 29 | 30 | return response.data; 31 | } catch (error) { 32 | console.error('Error in generateAzureOpenAIResponse:', error); 33 | throw new Error(`Failed to generate Azure OpenAI response: ${error.message}`); 34 | } 35 | } 36 | 37 | module.exports = { generateAzureOpenAIResponse }; 38 | -------------------------------------------------------------------------------- /src/bot.js: -------------------------------------------------------------------------------- 1 | const TelegramBot = require('node-telegram-bot-api'); 2 | const { Redis } = require('@upstash/redis'); 3 | const { 4 | TELEGRAM_BOT_TOKEN, 5 | WHITELISTED_USERS, 6 | OPENAI_MODELS, 7 | GOOGLE_MODELS, 8 | GROQ_MODELS, 9 | CLAUDE_MODELS, 10 | AZURE_OPENAI_MODELS, 11 | DEFAULT_MODEL, 12 | OPENAI_API_KEY, 13 | GEMINI_API_KEY, 14 | GROQ_API_KEY, 15 | CLAUDE_API_KEY, 16 | AZURE_OPENAI_API_KEY, 17 | UPSTASH_REDIS_REST_URL, 18 | UPSTASH_REDIS_REST_TOKEN 19 | } = require('./config'); 20 | const { generateResponse, generateStreamResponse } = require('./api'); 21 | const { generateGeminiResponse } = require('./geminiApi'); 22 | const { generateGroqResponse } = require('./groqapi'); 23 | const { generateClaudeResponse } = require('./claude'); 24 | const { generateAzureOpenAIResponse } = require('./azureOpenAI'); 25 | const { getConversationHistory, addToConversationHistory, clearConversationHistory, getSummarizedConversationHistory } = require('./redis'); 26 | const { generateImage, VALID_SIZES } = require('./generateImage'); 27 | const { handleImageUpload } = require('./uploadHandler'); 28 | const { getUserLanguage, setUserLanguage, translate, supportedLanguages, getLocalizedCommands } = require('./localization'); 29 | 30 | let currentModel = OPENAI_API_KEY ? DEFAULT_MODEL : null; 31 | 32 | const bot = new TelegramBot(TELEGRAM_BOT_TOKEN, { 33 | webhook: { 34 | port: process.env.PORT 35 | } 36 | }); 37 | 38 | const redis = new Redis({ 39 | url: UPSTASH_REDIS_REST_URL, 40 | token: UPSTASH_REDIS_REST_TOKEN, 41 | }); 42 | 43 | function getMessageFromUpdate(update) { 44 | if (update.callback_query) { 45 | return update.callback_query.message; 46 | } 47 | return update.message || update.edited_message; 48 | } 49 | 50 | async function sendMessageWithFallback(chatId, text, parseMode = 'Markdown') { 51 | try { 52 | await bot.sendMessage(chatId, text, { parse_mode: parseMode }); 53 | } catch (error) { 54 | console.error('Error sending message with Markdown:', error); 55 | try { 56 | // 移除 Markdown 语法 57 | const plainText = text.replace(/[*_`\[\]()~>#+=|{}.!-]/g, ''); 58 | await bot.sendMessage(chatId, plainText); 59 | } catch (secondError) { 60 | console.error('Error sending plain text message:', secondError); 61 | throw new Error('Failed to send message in any format'); 62 | } 63 | } 64 | } 65 | 66 | async function updateBotCommands(userId) { 67 | const commands = await getLocalizedCommands(userId); 68 | try { 69 | await bot.setMyCommands(commands, { scope: { type: 'chat', chat_id: userId } }); 70 | console.log(`Updated bot commands for user ${userId}`); 71 | } catch (error) { 72 | console.error(`Failed to update bot commands for user ${userId}:`, error); 73 | } 74 | } 75 | 76 | async function handleStart(msg) { 77 | const chatId = msg.chat.id; 78 | const userId = msg.from.id; 79 | const userLang = await getUserLanguage(userId); 80 | try { 81 | await bot.sendMessage(chatId, translate('welcome', userLang, {model: currentModel}), {parse_mode: 'Markdown'}); 82 | console.log('Start message sent successfully'); 83 | } catch (error) { 84 | console.error('Error sending start message:', error); 85 | } 86 | } 87 | 88 | async function handleNew(msg) { 89 | const chatId = msg.chat.id; 90 | const userId = msg.from.id; 91 | const userLang = await getUserLanguage(userId); 92 | try { 93 | await clearConversationHistory(userId); 94 | await bot.sendMessage(chatId, translate('new_conversation', userLang, {model: currentModel}), {parse_mode: 'Markdown'}); 95 | console.log('New conversation message sent successfully'); 96 | } catch (error) { 97 | console.error('Error handling new conversation:', error); 98 | } 99 | } 100 | 101 | async function handleHistory(msg) { 102 | const chatId = msg.chat.id; 103 | const userId = msg.from.id; 104 | const userLang = await getUserLanguage(userId); 105 | try { 106 | const summarizedHistory = await getSummarizedConversationHistory(userId, currentModel); 107 | if (!summarizedHistory) { 108 | await bot.sendMessage(chatId, translate('no_history', userLang), {parse_mode: 'Markdown'}); 109 | return; 110 | } 111 | await bot.sendMessage(chatId, translate('history_intro', userLang) + summarizedHistory, {parse_mode: 'Markdown'}); 112 | } catch (error) { 113 | console.error('Error retrieving summarized conversation history:', error); 114 | await bot.sendMessage(chatId, translate('error_message', userLang), {parse_mode: 'Markdown'}); 115 | } 116 | } 117 | 118 | async function handleHelp(msg) { 119 | const chatId = msg.chat.id; 120 | const userId = msg.from.id; 121 | const userLang = await getUserLanguage(userId); 122 | try { 123 | const availableModels = [ 124 | ...(OPENAI_API_KEY ? OPENAI_MODELS : []), 125 | ...(GEMINI_API_KEY ? GOOGLE_MODELS : []), 126 | ...(GROQ_API_KEY ? GROQ_MODELS : []), 127 | ...(CLAUDE_API_KEY ? CLAUDE_MODELS : []), 128 | ...(AZURE_OPENAI_API_KEY ? AZURE_OPENAI_MODELS : []) 129 | ]; 130 | const helpMessage = translate('help_message', userLang, { 131 | models: availableModels.join(', '), 132 | current_model: currentModel 133 | }); 134 | await bot.sendMessage(chatId, helpMessage, {parse_mode: 'Markdown'}); 135 | console.log('Help message sent successfully'); 136 | } catch (error) { 137 | console.error('Error sending help message:', error); 138 | } 139 | } 140 | 141 | async function handleSwitchModel(msg) { 142 | const chatId = msg.chat.id; 143 | const userId = msg.from.id; 144 | const userLang = await getUserLanguage(userId); 145 | const args = msg.text.split(' '); 146 | 147 | const availableModels = [ 148 | ...(OPENAI_API_KEY ? OPENAI_MODELS : []), 149 | ...(GEMINI_API_KEY ? GOOGLE_MODELS : []), 150 | ...(GROQ_API_KEY ? GROQ_MODELS : []), 151 | ...(CLAUDE_API_KEY ? CLAUDE_MODELS : []), 152 | ...(AZURE_OPENAI_API_KEY ? AZURE_OPENAI_MODELS : []) 153 | ]; 154 | 155 | if (args.length < 2) { 156 | await bot.sendMessage(chatId, translate('forgot_model_name', userLang, {available_models: availableModels.join(', ')}), {parse_mode: 'Markdown'}); 157 | return; 158 | } 159 | 160 | const modelName = args[1].trim(); 161 | 162 | if ((OPENAI_MODELS.includes(modelName) && OPENAI_API_KEY) || 163 | (GOOGLE_MODELS.includes(modelName) && GEMINI_API_KEY) || 164 | (GROQ_MODELS.includes(modelName) && GROQ_API_KEY) || 165 | (CLAUDE_MODELS.includes(modelName) && CLAUDE_API_KEY) || 166 | (AZURE_OPENAI_MODELS.includes(modelName) && AZURE_OPENAI_API_KEY)) { 167 | currentModel = modelName; 168 | await clearConversationHistory(userId); 169 | await bot.sendMessage(chatId, translate('model_switched', userLang, {model: modelName}), {parse_mode: 'Markdown'}); 170 | } else { 171 | await bot.sendMessage(chatId, translate('invalid_model', userLang, {available_models: availableModels.join(', ')}), {parse_mode: 'Markdown'}); 172 | } 173 | } 174 | 175 | async function handleImageGeneration(msg) { 176 | const chatId = msg.chat.id; 177 | const userId = msg.from.id; 178 | const userLang = await getUserLanguage(userId); 179 | 180 | if (!OPENAI_API_KEY) { 181 | await bot.sendMessage(chatId, translate('no_api_key', userLang)); 182 | return; 183 | } 184 | 185 | const args = msg.text.split(' '); 186 | args.shift(); // Remove "/img" command 187 | 188 | let size = '1024x1024'; 189 | let prompt; 190 | 191 | // Check if the last argument is possibly a size 192 | const possibleSize = args[args.length - 1]; 193 | if (possibleSize && possibleSize.includes('x')) { 194 | const [width, height] = possibleSize.split('x').map(Number); 195 | if (VALID_SIZES.includes(`${width}x${height}`)) { 196 | size = `${width}x${height}`; 197 | args.pop(); // Remove size from the argument list 198 | } else { 199 | // If size is invalid, send error message and return 200 | await bot.sendMessage(chatId, translate('invalid_size', userLang, {size: possibleSize, valid_sizes: VALID_SIZES.join(', ')})); 201 | return; 202 | } 203 | } 204 | 205 | prompt = args.join(' '); 206 | 207 | if (prompt.trim() === '') { 208 | // If no description is provided, suggest using /help command 209 | await bot.sendMessage(chatId, translate('no_image_description', userLang) + ' ' + translate('use_help_command', userLang)); 210 | return; 211 | } 212 | 213 | try { 214 | console.log(`Processing image generation request. Chat ID: ${chatId}, Prompt: "${prompt}", Size: ${size}`); 215 | await bot.sendChatAction(chatId, 'upload_photo'); 216 | 217 | const requestId = `img_req:${userId}:${Date.now()}`; 218 | 219 | const existingImageUrl = await redis.get(requestId); 220 | 221 | if (existingImageUrl) { 222 | console.log(`Using existing image URL: ${existingImageUrl}`); 223 | await bot.sendPhoto(chatId, existingImageUrl, { caption: prompt }); 224 | return; 225 | } 226 | 227 | console.log(`Generating image with prompt: "${prompt}" and size: ${size}`); 228 | const imageUrl = await generateImage(prompt, size); 229 | console.log(`Image URL generated: ${imageUrl}`); 230 | 231 | if (imageUrl) { 232 | await redis.set(requestId, imageUrl, { ex: 86400 }); // Expires after 1 day 233 | 234 | console.log(`Sending image. URL: ${imageUrl}`); 235 | await bot.sendPhoto(chatId, imageUrl, { caption: prompt }); 236 | console.log('Photo sent successfully'); 237 | } else { 238 | throw new Error('Failed to get image URL'); 239 | } 240 | } catch (error) { 241 | console.error('Error in image generation or sending:', error); 242 | let errorMessage = translate('error_message', userLang); 243 | if (error.response) { 244 | console.error('API error response:', error.response.data); 245 | errorMessage += ` API Error: ${error.response.data.error.message}`; 246 | } else if (error.request) { 247 | console.error('No response received from API'); 248 | errorMessage += ' No response received from API.'; 249 | } else { 250 | errorMessage += ` ${error.message}`; 251 | } 252 | await bot.sendMessage(chatId, errorMessage); 253 | } 254 | } 255 | 256 | async function handleStreamMessage(msg) { 257 | const chatId = msg.chat.id; 258 | const userId = msg.from.id; 259 | const userLang = await getUserLanguage(userId); 260 | 261 | await bot.sendChatAction(chatId, 'typing'); 262 | const conversationHistory = await getConversationHistory(userId); 263 | 264 | const MESSAGE_LENGTH_THRESHOLD = 4000; 265 | 266 | async function sendLongMessage(text) { 267 | let remainingText = text; 268 | while (remainingText.length > 0) { 269 | const chunk = remainingText.slice(0, MESSAGE_LENGTH_THRESHOLD); 270 | await sendMessageWithFallback(chatId, chunk); 271 | remainingText = remainingText.slice(MESSAGE_LENGTH_THRESHOLD); 272 | } 273 | } 274 | 275 | if (GROQ_MODELS.includes(currentModel) && GROQ_API_KEY) { 276 | try { 277 | const response = await generateGroqResponse(msg.text, conversationHistory, currentModel); 278 | await sendLongMessage(response); 279 | await addToConversationHistory(userId, msg.text, response); 280 | } catch (error) { 281 | console.error('Error in Groq processing:', error); 282 | await sendMessageWithFallback(chatId, translate('error_message', userLang)); 283 | } 284 | return; 285 | } 286 | 287 | if (GOOGLE_MODELS.includes(currentModel) && GEMINI_API_KEY) { 288 | try { 289 | const response = await generateGeminiResponse(msg.text, conversationHistory, currentModel); 290 | await sendLongMessage(response); 291 | await addToConversationHistory(userId, msg.text, response); 292 | } catch (error) { 293 | console.error('Error in Gemini processing:', error); 294 | await sendMessageWithFallback(chatId, translate('error_message', userLang)); 295 | } 296 | return; 297 | } 298 | 299 | let stream; 300 | if (OPENAI_API_KEY && OPENAI_MODELS.includes(currentModel)) { 301 | stream = generateStreamResponse(msg.text, conversationHistory, currentModel); 302 | } else if (CLAUDE_API_KEY && CLAUDE_MODELS.includes(currentModel)) { 303 | stream = generateClaudeResponse(msg.text, conversationHistory, currentModel); 304 | } else if (AZURE_OPENAI_API_KEY && AZURE_OPENAI_MODELS.includes(currentModel)) { 305 | stream = generateAzureOpenAIResponse(msg.text, conversationHistory, currentModel); 306 | } else { 307 | await bot.sendMessage(chatId, translate('no_api_key', userLang)); 308 | return; 309 | } 310 | 311 | let fullResponse = ''; 312 | let messageSent = false; 313 | let messageId; 314 | let lastUpdateLength = 0; 315 | 316 | try { 317 | for await (const chunk of stream) { 318 | fullResponse += chunk; 319 | 320 | if (fullResponse.length > MESSAGE_LENGTH_THRESHOLD) { 321 | if (messageSent) { 322 | // 发送新消息并重置 323 | await bot.sendMessage(chatId, fullResponse, {parse_mode: 'Markdown'}); 324 | } else { 325 | // 首次发送消息 326 | const sentMsg = await bot.sendMessage(chatId, fullResponse, {parse_mode: 'Markdown'}); 327 | messageId = sentMsg.message_id; 328 | messageSent = true; 329 | } 330 | fullResponse = ''; 331 | lastUpdateLength = 0; 332 | } else if (fullResponse.length > 0 && !messageSent) { 333 | // 首次发送消息(短于阈值) 334 | const sentMsg = await bot.sendMessage(chatId, fullResponse, {parse_mode: 'Markdown'}); 335 | messageId = sentMsg.message_id; 336 | messageSent = true; 337 | lastUpdateLength = fullResponse.length; 338 | } else if (messageSent && fullResponse.length % Math.max(20, Math.floor((fullResponse.length - lastUpdateLength) / 10)) === 0) { 339 | // 更新现有消息 340 | try { 341 | await bot.editMessageText(fullResponse, { 342 | chat_id: chatId, 343 | message_id: messageId, 344 | parse_mode: 'Markdown' 345 | }); 346 | lastUpdateLength = fullResponse.length; 347 | } catch (error) { 348 | if (!error.response || error.response.description !== 'Bad Request: message is not modified') { 349 | console.error('Error editing message:', error); 350 | } 351 | } 352 | } 353 | } 354 | 355 | // 发送剩余的内容(如果有) 356 | if (fullResponse.length > 0) { 357 | if (messageSent) { 358 | await bot.sendMessage(chatId, fullResponse, {parse_mode: 'Markdown'}); 359 | } else { 360 | await bot.editMessageText(fullResponse, { 361 | chat_id: chatId, 362 | message_id: messageId, 363 | parse_mode: 'Markdown' 364 | }); 365 | } 366 | } 367 | 368 | await addToConversationHistory(userId, msg.text, fullResponse); 369 | } catch (error) { 370 | console.error('Error in stream processing:', error); 371 | await bot.sendMessage(chatId, translate('error_message', userLang), {parse_mode: 'Markdown'}); 372 | } 373 | } 374 | 375 | async function handleImageAnalysis(msg) { 376 | const chatId = msg.chat.id; 377 | const userId = msg.from.id; 378 | const userLang = await getUserLanguage(userId); 379 | 380 | if (!OPENAI_API_KEY) { 381 | await bot.sendMessage(chatId, translate('no_api_key', userLang)); 382 | return; 383 | } 384 | 385 | // Check if a photo is attached 386 | const photo = msg.photo && msg.photo[msg.photo.length - 1]; 387 | if (!photo) { 388 | await bot.sendMessage(chatId, translate('no_image', userLang)); 389 | return; 390 | } 391 | 392 | // Get the prompt from the caption or wait for it 393 | let prompt = msg.caption; 394 | if (!prompt) { 395 | await bot.sendMessage(chatId, translate('provide_image_description', userLang)); 396 | // Wait for the next message to be the prompt 397 | const promptMsg = await new Promise(resolve => bot.once('message', resolve)); 398 | prompt = promptMsg.text; 399 | } 400 | 401 | await bot.sendMessage(chatId, translate('processing_image', userLang)); 402 | 403 | try { 404 | const fileInfo = await bot.getFile(photo.file_id); 405 | const result = await handleImageUpload(fileInfo, prompt, currentModel); 406 | await bot.sendMessage(chatId, result, { parse_mode: 'Markdown' }); 407 | } catch (error) { 408 | console.error('Error in image analysis:', error); 409 | await bot.sendMessage(chatId, translate('error_message', userLang)); 410 | } 411 | } 412 | 413 | async function handleLanguageChange(msg) { 414 | const chatId = msg.chat.id; 415 | const userId = msg.from.id; 416 | const currentLang = await getUserLanguage(userId); 417 | 418 | const keyboard = supportedLanguages.map(lang => [{text: translate(lang, currentLang), callback_data: `lang_${lang}`}]); 419 | 420 | await bot.sendMessage(chatId, translate('choose_language', currentLang), { 421 | reply_markup: JSON.stringify({ 422 | inline_keyboard: keyboard 423 | }) 424 | }); 425 | } 426 | 427 | async function handleMessage(update) { 428 | if (update.callback_query) { 429 | await handleCallbackQuery(update.callback_query); 430 | return; 431 | } 432 | 433 | const msg = getMessageFromUpdate(update); 434 | if (!msg) { 435 | console.log('Update does not contain a valid message'); 436 | return; 437 | } 438 | 439 | const chatId = msg.chat.id; 440 | const userId = msg.from.id; 441 | 442 | try { 443 | if (!WHITELISTED_USERS.includes(userId)) { 444 | await bot.sendMessage(chatId, 'Sorry, you are not authorized to use this bot.', {parse_mode: 'Markdown'}); 445 | return; 446 | } 447 | 448 | const userLang = await getUserLanguage(userId); 449 | 450 | if (msg.photo) { 451 | await handleImageAnalysis(msg); 452 | } else if (msg.text) { 453 | if (msg.text === '/start') { 454 | await handleStart(msg); 455 | } else if (msg.text === '/new') { 456 | await handleNew(msg); 457 | } else if (msg.text === '/history') { 458 | await handleHistory(msg); 459 | } else if (msg.text === '/help') { 460 | await handleHelp(msg); 461 | } else if (msg.text.startsWith('/switchmodel')) { 462 | await handleSwitchModel(msg); 463 | } else if (msg.text.startsWith('/img')) { 464 | await handleImageGeneration(msg); 465 | } else if (msg.text === '/language') { 466 | await handleLanguageChange(msg); 467 | } else { 468 | await handleStreamMessage(msg); 469 | } 470 | } else { 471 | console.log('Received unsupported message type'); 472 | await bot.sendMessage(chatId, translate('unsupported_message', userLang), {parse_mode: 'Markdown'}); 473 | } 474 | } catch (error) { 475 | console.error('Error in handleMessage:', error); 476 | await bot.sendMessage(chatId, translate('error_message', userLang), {parse_mode: 'Markdown'}); 477 | } 478 | } 479 | 480 | async function handleCallbackQuery(callbackQuery) { 481 | const action = callbackQuery.data; 482 | const msg = callbackQuery.message; 483 | const userId = callbackQuery.from.id; 484 | 485 | if (action.startsWith('lang_')) { 486 | const newLang = action.split('_')[1]; 487 | if (await setUserLanguage(userId, newLang)) { 488 | const userLang = await getUserLanguage(userId); 489 | await updateBotCommands(userId); 490 | await bot.answerCallbackQuery(callbackQuery.id, {text: translate('language_set', userLang)}); 491 | await bot.sendMessage(msg.chat.id, translate('language_changed', userLang)); 492 | } 493 | } 494 | } 495 | 496 | module.exports = { 497 | bot, 498 | handleMessage, 499 | handleStart, 500 | getMessageFromUpdate, 501 | handleCallbackQuery, 502 | updateBotCommands 503 | }; 504 | -------------------------------------------------------------------------------- /src/claude.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | const { CLAUDE_API_KEY, CLAUDE_ENDPOINT, SYSTEM_INIT_MESSAGE, SYSTEM_INIT_MESSAGE_ROLE } = require('./config'); 3 | 4 | async function generateClaudeResponse(prompt, conversationHistory, model) { 5 | try { 6 | const response = await axios.post( 7 | CLAUDE_ENDPOINT, 8 | { 9 | model: model, 10 | messages: [ 11 | { role: SYSTEM_INIT_MESSAGE_ROLE, content: SYSTEM_INIT_MESSAGE }, 12 | ...conversationHistory, 13 | { role: 'user', content: prompt } 14 | ], 15 | stream: true 16 | }, 17 | { 18 | headers: { 19 | 'Authorization': `Bearer ${CLAUDE_API_KEY}`, 20 | 'Content-Type': 'application/json' 21 | }, 22 | responseType: 'stream' 23 | } 24 | ); 25 | 26 | return response.data; 27 | } catch (error) { 28 | console.error('Error in generateClaudeResponse:', error); 29 | throw new Error(`Failed to generate Claude response: ${error.message}`); 30 | } 31 | } 32 | 33 | module.exports = { generateClaudeResponse }; 34 | -------------------------------------------------------------------------------- /src/config.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | 3 | module.exports = { 4 | OPENAI_API_KEY: process.env.OPENAI_API_KEY, 5 | OPENAI_BASE_URL: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1', 6 | OPENAI_MODELS: process.env.OPENAI_MODELS ? process.env.OPENAI_MODELS.split(',').map(model => model.trim()) : [], 7 | DEFAULT_MODEL: process.env.OPENAI_MODELS ? process.env.OPENAI_MODELS.split(',').map(model => model.trim())[0] : null, 8 | AZURE_OPENAI_API_KEY: process.env.AZURE_OPENAI_API_KEY, 9 | AZURE_OPENAI_ENDPOINT: process.env.AZURE_OPENAI_ENDPOINT, 10 | AZURE_OPENAI_MODELS: process.env.AZURE_OPENAI_MODELS ? process.env.AZURE_OPENAI_MODELS.split(',').map(model => model.trim()) : [], 11 | TELEGRAM_BOT_TOKEN: process.env.TELEGRAM_BOT_TOKEN, 12 | WHITELISTED_USERS: process.env.WHITELISTED_USERS ? process.env.WHITELISTED_USERS.split(',').map(id => parseInt(id.trim())) : [], 13 | DALL_E_MODEL: process.env.DALL_E_MODEL || "dall-e-3", 14 | UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL, 15 | UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REST_TOKEN, 16 | SYSTEM_INIT_MESSAGE: process.env.SYSTEM_INIT_MESSAGE || 'You are a helpful assistant.', 17 | SYSTEM_INIT_MESSAGE_ROLE: process.env.SYSTEM_INIT_MESSAGE_ROLE || 'system', 18 | GEMINI_API_KEY: process.env.GEMINI_API_KEY, 19 | GOOGLE_MODELS: process.env.GOOGLE_MODELS ? process.env.GOOGLE_MODELS.split(',').map(model => model.trim()) : [], 20 | GEMINI_ENDPOINT: process.env.GEMINI_ENDPOINT || 'https://generativelanguage.googleapis.com/v1beta/models', 21 | GROQ_API_KEY: process.env.GROQ_API_KEY, 22 | GROQ_MODELS: process.env.GROQ_MODELS ? process.env.GROQ_MODELS.split(',').map(model => model.trim()) : [], 23 | MAX_HISTORY_LENGTH: parseInt(process.env.MAX_HISTORY_LENGTH) || 50, 24 | CLAUDE_API_KEY: process.env.CLAUDE_API_KEY, 25 | CLAUDE_MODELS: process.env.CLAUDE_MODELS ? process.env.CLAUDE_MODELS.split(',').map(model => model.trim()) : [], 26 | CLAUDE_ENDPOINT: process.env.CLAUDE_ENDPOINT || 'https://api.anthropic.com/v1/chat/completions', 27 | }; 28 | -------------------------------------------------------------------------------- /src/geminiApi.js: -------------------------------------------------------------------------------- 1 | const { GoogleGenerativeAI } = require("@google/generative-ai"); 2 | const { GEMINI_API_KEY, GEMINI_ENDPOINT, SYSTEM_INIT_MESSAGE, SYSTEM_INIT_MESSAGE_ROLE } = require('./config'); 3 | 4 | const genAI = new GoogleGenerativeAI(GEMINI_API_KEY, GEMINI_ENDPOINT); 5 | 6 | async function generateGeminiResponse(prompt, conversationHistory, model) { 7 | try { 8 | const geminiModel = genAI.getGenerativeModel({ model: model }); 9 | 10 | const chat = geminiModel.startChat({ 11 | history: [ 12 | { 13 | role: SYSTEM_INIT_MESSAGE_ROLE === 'system' ? 'user' : SYSTEM_INIT_MESSAGE_ROLE, 14 | parts: [{ text: SYSTEM_INIT_MESSAGE }], 15 | }, 16 | ...conversationHistory.map(msg => ({ 17 | role: msg.role === 'assistant' ? 'model' : 'user', 18 | parts: [{ text: msg.content }], 19 | })), 20 | ], 21 | }); 22 | 23 | const result = await chat.sendMessage(prompt); 24 | const response = result.response; 25 | return response.text(); 26 | } catch (error) { 27 | console.error('Error in generateGeminiResponse:', error); 28 | throw new Error(`Failed to generate Gemini response: ${error.message}`); 29 | } 30 | } 31 | 32 | module.exports = { generateGeminiResponse }; 33 | -------------------------------------------------------------------------------- /src/generateImage.js: -------------------------------------------------------------------------------- 1 | const { OpenAI } = require('openai'); 2 | const { OPENAI_API_KEY, OPENAI_BASE_URL, DALL_E_MODEL } = require('./config'); 3 | 4 | const client = new OpenAI({ 5 | apiKey: OPENAI_API_KEY, 6 | baseURL: OPENAI_BASE_URL 7 | }); 8 | 9 | const VALID_SIZES = ['1024x1024', '1792x1024', '1024x1792']; 10 | 11 | async function generateImage(prompt, size = '1024x1024') { 12 | console.log(`开始生成图片. 提示: "${prompt}", 尺寸: ${size}`); 13 | if (!VALID_SIZES.includes(size)) { 14 | console.log(`无效的图片尺寸: ${size}`); 15 | throw new Error(`Invalid size. Please use one of the following valid sizes: ${VALID_SIZES.join(', ')}`); 16 | } 17 | 18 | try { 19 | console.log('调用 OpenAI API...'); 20 | const response = await client.images.generate({ 21 | model: DALL_E_MODEL, 22 | prompt: prompt, 23 | n: 1, 24 | size: size 25 | }); 26 | console.log('OpenAI API 响应接收成功'); 27 | 28 | if (response.data && response.data.length > 0) { 29 | console.log(`生成的图片 URL: ${response.data[0].url}`); 30 | return response.data[0].url; 31 | } else { 32 | console.log('OpenAI 响应中没有图片 URL'); 33 | throw new Error('生成图片失败,未返回图片URL。'); 34 | } 35 | } catch (error) { 36 | console.error('生成图片时出错:', error); 37 | throw error; // 抛出原始错误,以便在调用函数中捕获更多细节 38 | } 39 | } 40 | 41 | module.exports = { generateImage, VALID_SIZES }; 42 | -------------------------------------------------------------------------------- /src/groqapi.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | const { GROQ_API_KEY, SYSTEM_INIT_MESSAGE, SYSTEM_INIT_MESSAGE_ROLE } = require('./config'); 3 | 4 | async function generateGroqResponse(prompt, conversationHistory, model) { 5 | try { 6 | const response = await axios.post( 7 | 'https://api.groq.com/openai/v1/chat/completions', 8 | { 9 | model: model, 10 | messages: [ 11 | { role: SYSTEM_INIT_MESSAGE_ROLE, content: SYSTEM_INIT_MESSAGE }, 12 | ...conversationHistory, 13 | { role: 'user', content: prompt } 14 | ], 15 | }, 16 | { 17 | headers: { 18 | 'Authorization': `Bearer ${GROQ_API_KEY}`, 19 | 'Content-Type': 'application/json' 20 | } 21 | } 22 | ); 23 | 24 | return response.data.choices[0].message.content; 25 | } catch (error) { 26 | console.error('Error in generateGroqResponse:', error); 27 | throw new Error(`Failed to generate Groq response: ${error.message}`); 28 | } 29 | } 30 | 31 | module.exports = { generateGroqResponse }; 32 | -------------------------------------------------------------------------------- /src/localization.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const { Redis } = require('@upstash/redis'); 4 | 5 | const defaultLanguage = 'en'; 6 | const supportedLanguages = ['en', 'zh-cn', 'zh-hant', 'ja', 'es', 'fr', 'ru', 'de']; 7 | 8 | let translations = {}; 9 | 10 | // Load all language files 11 | supportedLanguages.forEach(lang => { 12 | const filePath = path.join(__dirname, '..', 'locales', `${lang}.json`); 13 | translations[lang] = JSON.parse(fs.readFileSync(filePath, 'utf8')); 14 | }); 15 | 16 | const redis = new Redis({ 17 | url: process.env.UPSTASH_REDIS_REST_URL, 18 | token: process.env.UPSTASH_REST_TOKEN, 19 | }); 20 | 21 | async function getUserLanguage(userId) { 22 | const lang = await redis.get(`user_lang:${userId}`); 23 | return lang || defaultLanguage; 24 | } 25 | 26 | async function setUserLanguage(userId, language) { 27 | if (supportedLanguages.includes(language)) { 28 | await redis.set(`user_lang:${userId}`, language, { ex: 31536000 }); // 1 year TTL 29 | return true; 30 | } 31 | return false; 32 | } 33 | 34 | function translate(key, language, params = {}) { 35 | let text = translations[language]?.[key] || translations[defaultLanguage][key] || key; 36 | 37 | // Replace parameters 38 | Object.keys(params).forEach(param => { 39 | text = text.replace(`{${param}}`, params[param]); 40 | }); 41 | 42 | return text; 43 | } 44 | 45 | const commandKeys = ['start', 'new', 'history', 'help', 'switchmodel', 'img', 'language']; 46 | 47 | async function getLocalizedCommands(userId) { 48 | const userLang = await getUserLanguage(userId); 49 | return commandKeys.map(key => ({ 50 | command: key, 51 | description: translate(`cmd_${key}`, userLang) 52 | })); 53 | } 54 | 55 | module.exports = { getUserLanguage, setUserLanguage, translate, supportedLanguages, getLocalizedCommands }; 56 | -------------------------------------------------------------------------------- /src/redis.js: -------------------------------------------------------------------------------- 1 | const { Redis } = require('@upstash/redis'); 2 | const { UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN, MAX_HISTORY_LENGTH } = require('./config'); 3 | const { generateResponse } = require('./api'); 4 | const { generateGeminiResponse } = require('./geminiApi'); 5 | const { generateGroqResponse } = require('./groqapi'); 6 | const { generateClaudeResponse } = require('./claude'); 7 | const { generateAzureOpenAIResponse } = require('./azureOpenAI'); 8 | const { OPENAI_MODELS, GOOGLE_MODELS, GROQ_MODELS, CLAUDE_MODELS, AZURE_OPENAI_MODELS } = require('./config'); 9 | 10 | const redis = new Redis({ 11 | url: UPSTASH_REDIS_REST_URL, 12 | token: UPSTASH_REDIS_REST_TOKEN, 13 | }); 14 | 15 | async function getConversationHistory(userId) { 16 | try { 17 | const key = `user:${userId}:history`; 18 | const history = await redis.get(key); 19 | console.log(`Retrieved raw history for user ${userId}:`, history); 20 | 21 | if (typeof history === 'string') { 22 | return JSON.parse(history); 23 | } else if (Array.isArray(history)) { 24 | return history; 25 | } else if (history && typeof history === 'object') { 26 | return [history]; 27 | } else { 28 | return []; 29 | } 30 | } catch (error) { 31 | console.error('Error getting conversation history:', error); 32 | return []; 33 | } 34 | } 35 | 36 | async function addToConversationHistory(userId, message, response) { 37 | try { 38 | const key = `user:${userId}:history`; 39 | const history = await getConversationHistory(userId); 40 | history.push({ role: 'user', content: message }); 41 | history.push({ role: 'assistant', content: response }); 42 | 43 | // Keep only the last MAX_HISTORY_LENGTH messages 44 | if (history.length > MAX_HISTORY_LENGTH) { 45 | history.splice(0, history.length - MAX_HISTORY_LENGTH); 46 | } 47 | 48 | const jsonHistory = JSON.stringify(history); 49 | await redis.set(key, jsonHistory, { ex: 2592000 }); // 30 days TTL 50 | console.log(`Updated history for user ${userId}:`, jsonHistory); 51 | } catch (error) { 52 | console.error('Error adding to conversation history:', error); 53 | } 54 | } 55 | 56 | async function clearConversationHistory(userId) { 57 | try { 58 | const key = `user:${userId}:history`; 59 | await redis.del(key); 60 | console.log(`Cleared history for user ${userId}`); 61 | } catch (error) { 62 | console.error('Error clearing conversation history:', error); 63 | } 64 | } 65 | 66 | async function getSummarizedConversationHistory(userId, currentModel) { 67 | try { 68 | const history = await getConversationHistory(userId); 69 | if (history.length === 0) { 70 | return null; 71 | } 72 | 73 | // Prepare the prompt for summarization 74 | const historyText = history.map(m => `${m.role}: ${m.content}`).join('\n\n'); 75 | const summarizationPrompt = `Please summarize the following conversation history concisely:\n\n${historyText}\n\nSummary:`; 76 | 77 | // Generate summary using the current model 78 | let summary; 79 | if (OPENAI_MODELS.includes(currentModel)) { 80 | summary = await generateResponse(summarizationPrompt, [], currentModel); 81 | } else if (GOOGLE_MODELS.includes(currentModel)) { 82 | summary = await generateGeminiResponse(summarizationPrompt, [], currentModel); 83 | } else if (GROQ_MODELS.includes(currentModel)) { 84 | summary = await generateGroqResponse(summarizationPrompt, [], currentModel); 85 | } else if (CLAUDE_MODELS.includes(currentModel)) { 86 | summary = await generateClaudeResponse(summarizationPrompt, [], currentModel); 87 | } else if (AZURE_OPENAI_MODELS.includes(currentModel)) { 88 | summary = await generateAzureOpenAIResponse(summarizationPrompt, [], currentModel); 89 | } else { 90 | throw new Error('Unsupported model for summarization'); 91 | } 92 | 93 | return summary.trim(); 94 | } catch (error) { 95 | console.error('Error summarizing conversation history:', error); 96 | return null; 97 | } 98 | } 99 | 100 | module.exports = { 101 | getConversationHistory, 102 | addToConversationHistory, 103 | clearConversationHistory, 104 | getSummarizedConversationHistory 105 | }; 106 | -------------------------------------------------------------------------------- /src/uploadHandler.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const fileType = require('file-type'); 3 | const axios = require('axios'); 4 | const { OpenAI } = require('openai'); 5 | const { OPENAI_API_KEY, OPENAI_BASE_URL, SYSTEM_INIT_MESSAGE, SYSTEM_INIT_MESSAGE_ROLE } = require('./config'); 6 | 7 | const client = new OpenAI({ 8 | apiKey: OPENAI_API_KEY, 9 | baseURL: OPENAI_BASE_URL 10 | }); 11 | 12 | const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB 13 | const SUPPORTED_MODELS = ['gpt-4o', 'gpt-4o-mini', 'gpt-4']; 14 | const SUPPORTED_IMAGE_TYPES = ['image/jpeg', 'image/png']; 15 | const SUPPORTED_EXTENSIONS = ['jpg', 'jpeg', 'png']; 16 | 17 | async function handleImageUpload(fileInfo, prompt, model) { 18 | // Check file size 19 | if (fileInfo.file_size > MAX_FILE_SIZE) { 20 | return 'File size exceeds the 10MB limit.'; 21 | } 22 | 23 | // Check if the model is supported 24 | if (!SUPPORTED_MODELS.includes(model)) { 25 | return `Unsupported model. This feature only supports: ${SUPPORTED_MODELS.join(', ')}`; 26 | } 27 | 28 | // Check file extension 29 | const fileExtension = fileInfo.file_path.split('.').pop().toLowerCase(); 30 | if (!SUPPORTED_EXTENSIONS.includes(fileExtension)) { 31 | return `Unsupported file type. Supported types are: ${SUPPORTED_EXTENSIONS.join(', ')}`; 32 | } 33 | 34 | // Download file 35 | const filePath = `/tmp/${fileInfo.file_id}`; 36 | await downloadFile(fileInfo.file_path, filePath); 37 | 38 | try { 39 | // Verify file type 40 | const fileBuffer = fs.readFileSync(filePath); 41 | const detectedType = await fileType.fromBuffer(fileBuffer); 42 | 43 | if (!detectedType || !SUPPORTED_IMAGE_TYPES.includes(detectedType.mime)) { 44 | fs.unlinkSync(filePath); 45 | return 'Invalid file type. The file content does not match its extension. Only JPEG and PNG images are supported.'; 46 | } 47 | 48 | // Convert file to base64 49 | const base64Content = fileBuffer.toString('base64'); 50 | 51 | // Delete temporary file 52 | fs.unlinkSync(filePath); 53 | 54 | // Send to OpenAI for analysis 55 | const response = await analyzeImage(base64Content, detectedType.mime, prompt, model); 56 | 57 | return response; 58 | } catch (error) { 59 | console.error('Error in image processing:', error); 60 | return `Image processing error: ${error.message}`; 61 | } 62 | } 63 | 64 | async function downloadFile(filePath, destPath) { 65 | const response = await axios({ 66 | method: 'GET', 67 | url: `https://api.telegram.org/file/bot${process.env.TELEGRAM_BOT_TOKEN}/${filePath}`, 68 | responseType: 'stream' 69 | }); 70 | 71 | const writer = fs.createWriteStream(destPath); 72 | response.data.pipe(writer); 73 | 74 | return new Promise((resolve, reject) => { 75 | writer.on('finish', resolve); 76 | writer.on('error', reject); 77 | }); 78 | } 79 | 80 | async function analyzeImage(base64Content, mimeType, prompt, model) { 81 | try { 82 | const response = await client.chat.completions.create({ 83 | model: model, 84 | messages: [ 85 | { role: SYSTEM_INIT_MESSAGE_ROLE, content: SYSTEM_INIT_MESSAGE }, 86 | { 87 | role: "user", 88 | content: [ 89 | { type: "text", text: prompt }, 90 | { 91 | type: "image_url", 92 | image_url: { 93 | url: `data:${mimeType};base64,${base64Content}` 94 | } 95 | } 96 | ] 97 | } 98 | ], 99 | max_tokens: 300, 100 | }); 101 | 102 | return response.choices[0].message.content; 103 | } catch (error) { 104 | console.error('Error in OpenAI API call:', error); 105 | if (error.response) { 106 | return `API Error: ${error.response.status} - ${error.response.data.error.message}`; 107 | } else if (error.request) { 108 | return 'No response received from the API. Please try again later.'; 109 | } else { 110 | return `Error: ${error.message}`; 111 | } 112 | } 113 | } 114 | 115 | module.exports = { handleImageUpload }; 116 | -------------------------------------------------------------------------------- /vercel.json: -------------------------------------------------------------------------------- 1 | { 2 | "functions": { 3 | "api/**/*.js": { 4 | "memory": 1024, 5 | "maxDuration": 60 6 | } 7 | }, 8 | "routes": [ 9 | { "src": "/api/(.*)", "dest": "/api/$1" } 10 | ] 11 | } 12 | --------------------------------------------------------------------------------