# Telegram Bot MCP Server

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![npm version](https://img.shields.io/npm/v/telegram-chat-bot-mcp.svg)](https://www.npmjs.com/package/telegram-chat-bot-mcp)

An MCP (Model Context Protocol) server for sending rich-formatted messages via Telegram Bot API.
Supports both **HTML** and **MarkdownV2** output modes with full Telegram entity coverage.

## Key Features

- **Dual Parse Mode**: Choose between `HTML` (default, recommended) and `MarkdownV2` output
- **Full Telegram Entity Support**: Bold, italic, underline, strikethrough, spoiler, blockquote, code, links, and more
- **Nested Formatting**: `**bold _italic_ bold**` renders correctly via token-based parser
- **Smart Auto-splitting**: Messages exceeding 4096 chars are automatically split at natural boundaries
- **Auto Fallback**: Falls back to plain text when conversion or sending fails
- **MCP Protocol**: Works with Claude Desktop, Claude Code, VS Code Copilot, Cursor, Windsurf, and more
- **Inline Keyboards**: Buttons with URL, callback_data, etc.
- **Photo Sending**: Send photos with formatted captions
- **Structured Logging**: JSON format logs with configurable retention

## Installation

```bash
npm install -g telegram-chat-bot-mcp
```

### Update

```bash
npm update -g telegram-chat-bot-mcp
```

## Telegram Bot Setup

### 1) Create Bot via @BotFather

1. Search for **@BotFather** in Telegram
2. Send `/newbot` and follow the instructions
3. Set bot name and username (username must end with `bot`)
4. Save the Bot Token (format: `<digits>:<alphanumeric_string>`)

### 2) Get Chat ID

- **Use @userinfobot or @getidsbot**: Start the bot to see your user ID
- **For groups**: Add bot to group, send a test message, then call:
  ```
  https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  ```
  Find the `chat.id` value (group IDs are negative, e.g., `-1001234567890`)

## MCP Client Configuration

This MCP server integrates with various AI coding tools. Choose your tool below:

### Claude Desktop

**Configuration file:**
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`

**Access:** Claude > Settings > Developer > Edit Config

**Example:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### Claude Code (CLI)

**Configuration files (by priority):**
1. **Project** (team-shared): `.mcp.json` (at project root)
2. **User** (global): `~/.config/claude-code/mcp.json`

**Add server via command:**
```bash
nano ~/.config/claude-code/mcp.json

# After changes, reconnect
claude mcp reconnect telegram
```

**Example:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### VS Code (GitHub Copilot)

**Requirements:** VS Code 1.99+ (March 2025), Agent Mode enabled

**Configuration files:**
- **Workspace**: `.vscode/mcp.json` (project-specific)
- **User**: Command Palette > "MCP: Open User Configuration"

**Example (.vscode/mcp.json):**
```json
{
  "servers": {
    "telegram": {
      "type": "stdio",
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### Cursor IDE

**Configuration files:**
- **Global**: `~/.cursor/mcp.json`
- **Project**: `.cursor/mcp.json`

**Access:** Settings > MCP or direct file edit

**Example:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### Windsurf IDE (Codeium)

**Configuration file:**
- **macOS**: `~/.codeium/windsurf/mcp_config.json`
- **Windows**: `%USERPROFILE%\.codeium\windsurf\mcp_config.json`

**Access:** Cascade toolbar > Hammer icon > Configure

**Example:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

## Provided Tools (6)

| Tool | Description |
|------|-------------|
| **`send_telegram_text`** | Send plain text messages |
| **`send_telegram_markdown`** | Convert Markdown and send via HTML or MarkdownV2 (recommended) |
| **`send_telegram_with_buttons`** | Send messages with inline keyboard buttons |
| **`send_telegram_photo`** | Send images/photos (URL or Telegram file_id) |
| **`markdown_to_telegram_html`** | Convert Markdown to Telegram HTML (utility) |
| **`convert_markdown`** | Convert Markdown to HTML or MarkdownV2 format (utility) |

All tools use `TELEGRAM_CHAT_ID` from environment variables by default. You can optionally override with individual `chatId` parameter.

### Parse Mode Selection

The `send_telegram_markdown` and `convert_markdown` tools accept a `parseMode` parameter:

| Mode | Description | When to Use |
|------|-------------|-------------|
| `HTML` (default) | Converts Markdown to Telegram HTML | Recommended for most use cases. Easier escaping (3 chars). |
| `MarkdownV2` | Converts Markdown to Telegram MarkdownV2 | When native MarkdownV2 output is needed. Stricter escaping (18 chars). |

**Example — sending with MarkdownV2:**
```json
{
  "tool": "send_telegram_markdown",
  "arguments": {
    "markdown": "**Bold** and __underline__ text",
    "parseMode": "MarkdownV2"
  }
}
```

## Supported Markdown Syntax

| Syntax | Input | HTML Output | MarkdownV2 Output |
|--------|-------|-------------|-------------------|
| Bold | `**bold**` | `<b>bold</b>` | `*bold*` |
| Italic | `*italic*` | `<i>italic</i>` | `_italic_` |
| Underline | `__underline__` | `<u>underline</u>` | `__underline__` |
| Strikethrough | `~~strike~~` | `<s>strike</s>` | `~strike~` |
| Spoiler | `\|\|spoiler\|\|` | `<tg-spoiler>spoiler</tg-spoiler>` | `\|\|spoiler\|\|` |
| Inline Code | `` `code` `` | `<code>code</code>` | `` `code` `` |
| Code Block | ` ```lang\ncode\n``` ` | `<pre>code</pre>` | ` ```lang\ncode\n``` ` |
| Blockquote | `> quote` | `<blockquote>quote</blockquote>` | `>quote` |
| Link | `[text](url)` | `<a href="url">text</a>` | `[text](url)` |
| Image | `![alt](url)` | Link with emoji prefix | `![alt](url)` |
| Header | `# H1`, `## H2` | Bold heading | Bold text |
| List | `- item` | Bullet point | Escaped list |
| Table | `\| A \| B \|` | `<pre>` monospace | ` ``` ` monospace |
| Nested | `**bold _italic_**` | `<b>bold <i>italic</i></b>` | `*bold _italic_*` |

### Escaping

Escaping is handled automatically by the converter:

- **HTML mode**: Escapes `&`, `<`, `>` (3 characters)
- **MarkdownV2 mode**: Escapes `_ * [ ] ( ) ~ \` > # + - = | { } . !` (18 characters)
- **Inside code blocks**: Minimal escaping (only `` ` `` and `\` in MarkdownV2)
- **Inside URLs**: Only `)` and `\` in MarkdownV2

## Environment Variables

### Required

| Variable | Description |
|----------|-------------|
| `TELEGRAM_BOT_TOKEN` | Bot Token from @BotFather |
| `TELEGRAM_CHAT_ID` | Target Chat ID (user or group) |

### Optional (Logging)

| Variable | Description | Default |
|----------|-------------|---------|
| `LOG_LEVEL` | Log level (DEBUG, INFO, WARN, ERROR) | `INFO` |
| `LOG_DIR` | Log directory path | `./logs` |
| `LOG_RETENTION_DAYS` | Days to keep logs | `30` |
| `LOG_ENABLE_CONSOLE` | Enable console output | `true` |

## Testing

```bash
# Set environment variables
export TELEGRAM_BOT_TOKEN="<YOUR_BOT_TOKEN>"
export TELEGRAM_CHAT_ID="<YOUR_CHAT_ID>"

# Build first
npm run build

# Unit tests (154 tests)
npx vitest run

# Individual test scripts
npm run test:telegram:text       # Plain text test
npm run test:telegram:markdown   # Markdown conversion test
npm run test:mcp:server          # MCP protocol test
```

## Development

```bash
npm install         # Install dependencies
npm run build       # Build TypeScript
npm run dev         # Run in dev mode
npm run lint        # Lint code
npm run lint:fix    # Auto-fix lint issues
npx vitest run      # Run all tests
```

## Architecture

```
src/
├── server.ts                       # MCP server & tool registration
├── tools/
│   ├── markdownToTelegram.ts       # Markdown → Telegram HTML (token-based parser)
│   ├── markdownToMarkdownV2.ts     # Markdown → Telegram MarkdownV2
│   ├── markdownConverter.ts        # Dual-mode router (HTML / MarkdownV2)
│   ├── sendTelegramMarkdown.ts     # Send with auto-conversion & splitting
│   ├── sendTelegramText.ts         # Send plain text
│   ├── sendTelegramWithButtons.ts  # Send with inline keyboard
│   └── sendTelegramPhoto.ts        # Send photos
├── utils/
│   ├── escapeUtils.ts              # HTML & MarkdownV2 escape functions
│   ├── markdownSplitter.ts         # Auto-split long messages
│   ├── axiosConfig.ts              # HTTP client config
│   └── logger.ts                   # Structured JSON logger
└── types/
    └── telegram.ts                 # Telegram API type definitions
```

## Limitations and Considerations

### Telegram Bot API Constraints

- **HTML Tags**: Supports `b`, `i`, `u`, `s`, `code`, `pre`, `a`, `blockquote`, `tg-spoiler`
- **Tables**: Rendered as `<pre>` monospace text (Telegram doesn't support `<table>`)
- **Images**: HTTPS only, ~10MB file size limit
- **Message Length**: 4096 character limit (auto-split when exceeded)
- **MarkdownV2 Escaping**: All 18 special characters must be escaped (handled automatically)

### HTML vs MarkdownV2 Comparison

| Aspect | HTML | MarkdownV2 |
|--------|------|------------|
| Escape chars | 3 (`<`, `>`, `&`) | 18 (`_`, `*`, `[`, `]`, etc.) |
| Error risk | Low | Higher (one missed escape = 400 error) |
| Nested formatting | Clear XML-style tags | Symbol-based, ambiguity possible |
| Recommendation | Default choice | When native V2 output is required |

## Security

**Bot Token and Chat ID are sensitive information.**

- Never commit credentials to Git
- Do not expose in public repositories
- Use environment variables for secrets
- If leaked, regenerate token via @BotFather

## Troubleshooting

**MCP server not connecting:**
- Verify global installation: `npm install -g telegram-chat-bot-mcp`
- Check environment variables are set correctly
- Restart your AI tool after configuration changes

**Timeout errors (WSL users):**
- This package includes IPv4 enforcement to prevent WSL IPv6 timeout issues
- If timeout persists, check network connectivity to api.telegram.org

**Tools not appearing:**
- Verify configuration file is in the correct location for your tool
- Validate JSON syntax
- Restart MCP server or reconnect

**MarkdownV2 sending fails (400 Bad Request):**
- This usually means an unescaped special character
- Switch to HTML mode (default) which is more forgiving
- Check the Telegram Bot API documentation for MarkdownV2 escaping rules

## License

MIT License - See [LICENSE](LICENSE) file

## Links

- [Telegram Bot API](https://core.telegram.org/bots/api)
- [Telegram Formatting Options](https://core.telegram.org/bots/api#formatting-options)
- [Model Context Protocol](https://github.com/modelcontextprotocol)
- [GitHub Repository](https://github.com/ice3x2/telegram-chat-bot-mcp)
- [npm Package](https://www.npmjs.com/package/telegram-chat-bot-mcp)

---

# Korean Documentation

# Telegram Bot MCP Server

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![npm version](https://img.shields.io/npm/v/telegram-chat-bot-mcp.svg)](https://www.npmjs.com/package/telegram-chat-bot-mcp)

Telegram Bot API를 통해 서식이 적용된 메시지를 전송하는 MCP (Model Context Protocol) 서버입니다.
**HTML**과 **MarkdownV2** 두 가지 출력 모드를 지원하며, Telegram의 모든 텍스트 엔티티를 지원합니다.

## 주요 기능

- **듀얼 파싱 모드**: `HTML` (기본값, 권장)과 `MarkdownV2` 출력 선택 가능
- **전체 Telegram 엔티티 지원**: 굵게, 기울임, 밑줄, 취소선, 스포일러, 인용, 코드, 링크 등
- **중첩 포맷팅**: `**bold _italic_ bold**`가 토큰 기반 파서로 정확히 렌더링
- **자동 메시지 분할**: 4096자 초과 시 자연스러운 경계에서 자동 분할
- **자동 폴백**: 변환 또는 전송 실패 시 평문으로 자동 전환
- **MCP 프로토콜 지원**: Claude Desktop, Claude Code, VS Code Copilot, Cursor, Windsurf 등
- **인라인 키보드**: URL, callback_data 등 다양한 버튼 지원
- **사진 전송**: 서식이 적용된 캡션과 함께 사진 전송
- **구조화된 로깅**: JSON 형식 로그, 설정 가능한 보관 정책

## 설치

```bash
npm install -g telegram-chat-bot-mcp
```

### 업데이트

```bash
npm update -g telegram-chat-bot-mcp
```

## Telegram 봇 설정

### 1) @BotFather로 봇 생성

1. Telegram에서 **@BotFather** 검색
2. `/newbot` 명령어 전송 후 안내 따르기
3. 봇 이름과 사용자명 설정 (사용자명은 `bot`으로 끝나야 함)
4. Bot Token 안전하게 저장 (형식: `<숫자>:<영숫자>`)

### 2) Chat ID 얻기

- **@userinfobot 또는 @getidsbot 사용**: 봇 시작하면 사용자 ID 표시
- **그룹의 경우**: 봇을 그룹에 추가하고 테스트 메시지 전송 후:
  ```
  https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  ```
  `chat.id` 값 확인 (그룹 ID는 음수, 예: `-1001234567890`)

## MCP 클라이언트 설정

다양한 AI 코딩 도구와 통합 가능합니다. 사용하는 도구를 선택하세요:

### Claude Desktop

**설정 파일:**
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`

**접근 방법:** Claude > Settings > Developer > Edit Config

**예시:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### Claude Code (CLI)

**설정 파일 (우선순위 순):**
1. **프로젝트**: `.mcp.json` (팀 공유용)
2. **사용자**: `~/.config/claude-code/mcp.json` (개인 전역 설정)

**명령어로 추가:**
```bash
nano ~/.config/claude-code/mcp.json

# 변경 후 재연결
claude mcp reconnect telegram
```

**예시:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### VS Code (GitHub Copilot)

**요구사항:** VS Code 1.99 이상 (2025년 3월), Agent Mode 활성화

**설정 파일:**
- **워크스페이스**: `.vscode/mcp.json` (프로젝트별)
- **사용자**: Command Palette > "MCP: Open User Configuration"

**예시 (.vscode/mcp.json):**
```json
{
  "servers": {
    "telegram": {
      "type": "stdio",
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### Cursor IDE

**설정 파일:**
- **전역**: `~/.cursor/mcp.json`
- **프로젝트**: `.cursor/mcp.json`

**접근 방법:** Settings > MCP 또는 파일 직접 편집

**예시:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

### Windsurf IDE (Codeium)

**설정 파일:**
- **macOS**: `~/.codeium/windsurf/mcp_config.json`
- **Windows**: `%USERPROFILE%\.codeium\windsurf\mcp_config.json`

**접근 방법:** Cascade 툴바 > Hammer 아이콘 > Configure

**예시:**
```json
{
  "mcpServers": {
    "telegram": {
      "command": "telegram-chat-bot-mcp",
      "env": {
        "TELEGRAM_BOT_TOKEN": "<YOUR_BOT_TOKEN>",
        "TELEGRAM_CHAT_ID": "<YOUR_CHAT_ID>"
      }
    }
  }
}
```

## 제공 도구 (6개)

| 도구 | 설명 |
|------|------|
| **`send_telegram_text`** | 평문 메시지 전송 |
| **`send_telegram_markdown`** | Markdown을 HTML 또는 MarkdownV2로 변환하여 전송 (권장) |
| **`send_telegram_with_buttons`** | 인라인 키보드 버튼 포함 메시지 전송 |
| **`send_telegram_photo`** | 이미지/사진 전송 (URL 또는 Telegram file_id) |
| **`markdown_to_telegram_html`** | Markdown을 Telegram HTML로 변환 (유틸리티) |
| **`convert_markdown`** | Markdown을 HTML 또는 MarkdownV2로 변환 (유틸리티) |

모든 도구는 기본적으로 환경변수의 `TELEGRAM_CHAT_ID`를 사용합니다. 개별 `chatId` 파라미터로 재정의 가능합니다.

### 파싱 모드 선택

`send_telegram_markdown`과 `convert_markdown` 도구는 `parseMode` 파라미터를 지원합니다:

| 모드 | 설명 | 사용 시기 |
|------|------|----------|
| `HTML` (기본값) | Markdown을 Telegram HTML로 변환 | 대부분의 경우 권장. 이스케이프가 간단 (3개 문자). |
| `MarkdownV2` | Markdown을 Telegram MarkdownV2로 변환 | 네이티브 MarkdownV2 출력이 필요할 때. 이스케이프가 엄격 (18개 문자). |

**예시 — MarkdownV2로 전송:**
```json
{
  "tool": "send_telegram_markdown",
  "arguments": {
    "markdown": "**Bold** and __underline__ text",
    "parseMode": "MarkdownV2"
  }
}
```

## 지원하는 Markdown 문법

| 문법 | 입력 | HTML 출력 | MarkdownV2 출력 |
|------|------|-----------|----------------|
| 굵게 | `**bold**` | `<b>bold</b>` | `*bold*` |
| 기울임 | `*italic*` | `<i>italic</i>` | `_italic_` |
| 밑줄 | `__underline__` | `<u>underline</u>` | `__underline__` |
| 취소선 | `~~strike~~` | `<s>strike</s>` | `~strike~` |
| 스포일러 | `\|\|spoiler\|\|` | `<tg-spoiler>spoiler</tg-spoiler>` | `\|\|spoiler\|\|` |
| 인라인 코드 | `` `code` `` | `<code>code</code>` | `` `code` `` |
| 코드 블록 | ` ```lang\ncode\n``` ` | `<pre>code</pre>` | ` ```lang\ncode\n``` ` |
| 인용 | `> quote` | `<blockquote>quote</blockquote>` | `>quote` |
| 링크 | `[text](url)` | `<a href="url">text</a>` | `[text](url)` |
| 이미지 | `![alt](url)` | 이모지 + 링크 | `![alt](url)` |
| 헤더 | `# H1`, `## H2` | 굵은 제목 | 굵은 텍스트 |
| 리스트 | `- item` | 불릿 포인트 | 이스케이프된 리스트 |
| 표 | `\| A \| B \|` | `<pre>` 고정폭 | ` ``` ` 고정폭 |
| 중첩 | `**bold _italic_**` | `<b>bold <i>italic</i></b>` | `*bold _italic_*` |

### 이스케이프 처리

이스케이프는 변환기가 자동으로 처리합니다:

- **HTML 모드**: `&`, `<`, `>` 3개 문자 이스케이프
- **MarkdownV2 모드**: `_ * [ ] ( ) ~ \` > # + - = | { } . !` 18개 문자 이스케이프
- **코드 블록 내부**: 최소 이스케이프 (MarkdownV2에서 `` ` ``과 `\`만)
- **URL 내부**: MarkdownV2에서 `)`과 `\`만

## 환경 변수

### 필수

| 변수 | 설명 |
|------|------|
| `TELEGRAM_BOT_TOKEN` | @BotFather에서 받은 Bot Token |
| `TELEGRAM_CHAT_ID` | 대상 Chat ID (사용자 또는 그룹) |

### 선택 (로깅 관련)

| 변수 | 설명 | 기본값 |
|------|------|--------|
| `LOG_LEVEL` | 로그 레벨 (DEBUG, INFO, WARN, ERROR) | `INFO` |
| `LOG_DIR` | 로그 디렉토리 경로 | `./logs` |
| `LOG_RETENTION_DAYS` | 로그 보관 일수 | `30` |
| `LOG_ENABLE_CONSOLE` | 콘솔 출력 활성화 | `true` |

## 테스트

```bash
# 환경변수 설정
export TELEGRAM_BOT_TOKEN="<YOUR_BOT_TOKEN>"
export TELEGRAM_CHAT_ID="<YOUR_CHAT_ID>"

# 빌드
npm run build

# 단위 테스트 (154개)
npx vitest run

# 개별 테스트 스크립트
npm run test:telegram:text       # 평문 메시지 테스트
npm run test:telegram:markdown   # Markdown 변환 테스트
npm run test:mcp:server          # MCP 프로토콜 테스트
```

## 개발

```bash
npm install         # 의존성 설치
npm run build       # TypeScript 빌드
npm run dev         # 개발 모드 실행
npm run lint        # 코드 린트
npm run lint:fix    # 린트 자동 수정
npx vitest run      # 모든 테스트 실행
```

## 아키텍처

```
src/
├── server.ts                       # MCP 서버 및 도구 등록
├── tools/
│   ├── markdownToTelegram.ts       # Markdown → Telegram HTML (토큰 기반 파서)
│   ├── markdownToMarkdownV2.ts     # Markdown → Telegram MarkdownV2
│   ├── markdownConverter.ts        # 듀얼 모드 라우터 (HTML / MarkdownV2)
│   ├── sendTelegramMarkdown.ts     # 자동 변환 및 분할 전송
│   ├── sendTelegramText.ts         # 평문 전송
│   ├── sendTelegramWithButtons.ts  # 인라인 키보드 전송
│   └── sendTelegramPhoto.ts        # 사진 전송
├── utils/
│   ├── escapeUtils.ts              # HTML 및 MarkdownV2 이스케이프 함수
│   ├── markdownSplitter.ts         # 긴 메시지 자동 분할
│   ├── axiosConfig.ts              # HTTP 클라이언트 설정
│   └── logger.ts                   # 구조화된 JSON 로거
└── types/
    └── telegram.ts                 # Telegram API 타입 정의
```

## 제한사항 및 고려사항

### Telegram Bot API 제약

- **HTML 태그**: `b`, `i`, `u`, `s`, `code`, `pre`, `a`, `blockquote`, `tg-spoiler` 지원
- **표**: `<pre>` 고정폭 텍스트로 변환 (Telegram은 `<table>`을 지원하지 않음)
- **이미지**: HTTPS만 허용, 약 10MB 파일 크기 제한
- **메시지 길이**: 4096자 제한 (초과 시 자동 분할)
- **MarkdownV2 이스케이프**: 18개 특수문자를 모두 이스케이프해야 함 (자동 처리됨)

### HTML vs MarkdownV2 비교

| 항목 | HTML | MarkdownV2 |
|------|------|------------|
| 이스케이프 문자 수 | 3개 (`<`, `>`, `&`) | 18개 (`_`, `*`, `[`, `]` 등) |
| 오류 위험도 | 낮음 | 높음 (하나라도 누락 시 400 에러) |
| 중첩 포맷팅 | 명확한 XML 스타일 태그 | 기호 기반, 모호성 가능 |
| 권장 | 기본 선택 | 네이티브 V2 출력이 필요할 때 |

## 보안

**Bot Token과 Chat ID는 민감 정보입니다.**

- Git에 절대 커밋하지 마세요
- 공개 저장소에 노출하지 마세요
- 비밀 정보는 환경변수 사용
- 유출 의심 시 @BotFather를 통해 토큰 재발급

## 문제 해결

**MCP 서버가 연결되지 않음:**
- 전역 설치 확인: `npm install -g telegram-chat-bot-mcp`
- 환경변수가 올바르게 설정되었는지 확인
- 설정 변경 후 AI 도구 재시작

**타임아웃 에러 (WSL 사용자):**
- 이 패키지는 WSL IPv6 타임아웃 문제를 방지하기 위해 IPv4 강제를 포함합니다
- 타임아웃이 지속되면 api.telegram.org에 대한 네트워크 연결 확인

**도구가 표시되지 않음:**
- 사용하는 도구에 맞는 올바른 위치에 설정 파일이 있는지 확인
- JSON 문법이 유효한지 확인
- MCP 서버 재시작 또는 재연결

**MarkdownV2 전송 실패 (400 Bad Request):**
- 이스케이프되지 않은 특수문자가 원인일 수 있습니다
- HTML 모드(기본값)로 전환하면 더 관대하게 처리됩니다
- Telegram Bot API 문서의 MarkdownV2 이스케이프 규칙을 확인하세요

## 라이선스

MIT License - [LICENSE](LICENSE) 파일 참조

## 링크

- [Telegram Bot API](https://core.telegram.org/bots/api)
- [Telegram 포맷팅 옵션](https://core.telegram.org/bots/api#formatting-options)
- [Model Context Protocol](https://github.com/modelcontextprotocol)
- [GitHub Repository](https://github.com/ice3x2/telegram-chat-bot-mcp)
- [npm Package](https://www.npmjs.com/package/telegram-chat-bot-mcp)
- [Issues](https://github.com/ice3x2/telegram-chat-bot-mcp/issues)
