fix telegram request ipv6 issue (#20)

* fix telegram request ipv6 issue

* fix telegram request ipv6 issue

* telegram config forceIPv4
This commit is contained in:
Henter 2025-08-03 01:57:03 +09:00 committed by GitHub
parent a74e11f3f7
commit 41543eb4b9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 67 additions and 14 deletions

View File

@ -69,6 +69,10 @@ TELEGRAM_BOT_TOKEN=your-telegram-bot-token
# Telegram webhook URL您的公開 HTTPS URL # Telegram webhook URL您的公開 HTTPS URL
# TELEGRAM_WEBHOOK_URL=https://your-domain.com # TELEGRAM_WEBHOOK_URL=https://your-domain.com
# 強制使用 IPv4 連接 Telegram API預設false
# 在某些網路環境下IPv6 連接可能不穩定,設置為 true 可強制使用 IPv4
# TELEGRAM_FORCE_IPV4=false
# ===== 系统配置 ===== # ===== 系统配置 =====
# 会话映射文件路径 # 会话映射文件路径
SESSION_MAP_PATH=/path/to/your/project/src/data/session-map.json SESSION_MAP_PATH=/path/to/your/project/src/data/session-map.json

View File

@ -141,6 +141,22 @@ TELEGRAM_WEBHOOK_URL=https://your-ngrok-url.app
SESSION_MAP_PATH=/your/path/to/Claude-Code-Remote/src/data/session-map.json SESSION_MAP_PATH=/your/path/to/Claude-Code-Remote/src/data/session-map.json
``` ```
**Optional Telegram settings:**
```env
# Force IPv4 connections to Telegram API (default: false)
# Enable this if you experience connectivity issues with IPv6
TELEGRAM_FORCE_IPV4=true
```
**Network Configuration Notes:**
- **IPv4 vs IPv6**: Some network environments may have unstable IPv6 connectivity to Telegram's API servers
- **When to use `TELEGRAM_FORCE_IPV4=true`**:
- Connection timeouts or failures when sending messages
- Inconsistent webhook delivery
- Network environments that don't properly support IPv6
- **Default behavior**: Uses system default (usually IPv6 when available, fallback to IPv4)
- **Performance impact**: Minimal - only affects initial connection establishment
#### Option C: Configure LINE #### Option C: Configure LINE
**Required LINE settings:** **Required LINE settings:**

View File

@ -24,7 +24,8 @@
"botToken": "", "botToken": "",
"chatId": "", "chatId": "",
"groupId": "", "groupId": "",
"whitelist": [] "whitelist": [],
"forceIPv4": false
} }
}, },
"whatsapp": { "whatsapp": {

View File

@ -41,6 +41,18 @@ class TelegramChannel extends NotificationChannel {
return true; return true;
} }
/**
* Generate network options for axios requests
* @returns {Object} Network options object
*/
_getNetworkOptions() {
const options = {};
if (this.config.forceIPv4) {
options.family = 4;
}
return options;
}
_generateToken() { _generateToken() {
// Generate short Token (uppercase letters + numbers, 8 digits) // Generate short Token (uppercase letters + numbers, 8 digits)
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
@ -73,7 +85,8 @@ class TelegramChannel extends NotificationChannel {
try { try {
const response = await axios.get( const response = await axios.get(
`${this.apiBaseUrl}/bot${this.config.botToken}/getMe` `${this.apiBaseUrl}/bot${this.config.botToken}/getMe`,
this._getNetworkOptions()
); );
if (response.data.ok && response.data.result.username) { if (response.data.ok && response.data.result.username) {
@ -145,7 +158,8 @@ class TelegramChannel extends NotificationChannel {
try { try {
const response = await axios.post( const response = await axios.post(
`${this.apiBaseUrl}/bot${this.config.botToken}/sendMessage`, `${this.apiBaseUrl}/bot${this.config.botToken}/sendMessage`,
requestData requestData,
this._getNetworkOptions()
); );
this.logger.info(`Telegram message sent successfully, Session: ${sessionId}`); this.logger.info(`Telegram message sent successfully, Session: ${sessionId}`);
@ -229,4 +243,4 @@ class TelegramChannel extends NotificationChannel {
} }
} }
module.exports = TelegramChannel; module.exports = TelegramChannel;

View File

@ -33,13 +33,25 @@ class TelegramWebhookHandler {
_setupRoutes() { _setupRoutes() {
// Telegram webhook endpoint // Telegram webhook endpoint
this.app.post('/webhook/telegram', this._handleWebhook.bind(this)); this.app.post('/webhook/telegram', this._handleWebhook.bind(this));
// Health check endpoint // Health check endpoint
this.app.get('/health', (req, res) => { this.app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'telegram-webhook' }); res.json({ status: 'ok', service: 'telegram-webhook' });
}); });
} }
/**
* Generate network options for axios requests
* @returns {Object} Network options object
*/
_getNetworkOptions() {
const options = {};
if (this.config.forceIPv4) {
options.family = 4;
}
return options;
}
async _handleWebhook(req, res) { async _handleWebhook(req, res) {
try { try {
const update = req.body; const update = req.body;
@ -226,7 +238,8 @@ class TelegramWebhookHandler {
try { try {
const response = await axios.get( const response = await axios.get(
`${this.apiBaseUrl}/bot${this.config.botToken}/getMe` `${this.apiBaseUrl}/bot${this.config.botToken}/getMe`,
this._getNetworkOptions()
); );
if (response.data.ok && response.data.result.username) { if (response.data.ok && response.data.result.username) {
@ -277,7 +290,8 @@ class TelegramWebhookHandler {
chat_id: chatId, chat_id: chatId,
text: text, text: text,
...options ...options
} },
this._getNetworkOptions()
); );
} catch (error) { } catch (error) {
this.logger.error('Failed to send message:', error.response?.data || error.message); this.logger.error('Failed to send message:', error.response?.data || error.message);
@ -291,7 +305,8 @@ class TelegramWebhookHandler {
{ {
callback_query_id: callbackQueryId, callback_query_id: callbackQueryId,
text: text text: text
} },
this._getNetworkOptions()
); );
} catch (error) { } catch (error) {
this.logger.error('Failed to answer callback query:', error.response?.data || error.message); this.logger.error('Failed to answer callback query:', error.response?.data || error.message);
@ -305,9 +320,10 @@ class TelegramWebhookHandler {
{ {
url: webhookUrl, url: webhookUrl,
allowed_updates: ['message', 'callback_query'] allowed_updates: ['message', 'callback_query']
} },
this._getNetworkOptions()
); );
this.logger.info('Webhook set successfully:', response.data); this.logger.info('Webhook set successfully:', response.data);
return response.data; return response.data;
} catch (error) { } catch (error) {
@ -323,4 +339,4 @@ class TelegramWebhookHandler {
} }
} }
module.exports = TelegramWebhookHandler; module.exports = TelegramWebhookHandler;

View File

@ -96,10 +96,12 @@ class ConfigManager {
}, },
telegram: { telegram: {
type: 'chat', type: 'chat',
enabled: false, enabled: process.env.TELEGRAM_ENABLED === 'true',
config: { config: {
token: '', botToken: process.env.TELEGRAM_BOT_TOKEN || '',
chatId: '' chatId: process.env.TELEGRAM_CHAT_ID || '',
groupId: process.env.TELEGRAM_GROUP_ID || '',
forceIPv4: process.env.TELEGRAM_FORCE_IPV4 === 'true'
} }
} }
}; };