Skip to content

feat(import): 增强Telegram JSON导出格式支持#245

Merged
ModerRAS merged 9 commits into
masterfrom
issue-81-telegram-json-export
Apr 23, 2026
Merged

feat(import): 增强Telegram JSON导出格式支持#245
ModerRAS merged 9 commits into
masterfrom
issue-81-telegram-json-export

Conversation

@ModerRAS

@ModerRAS ModerRAS commented Mar 19, 2026

Copy link
Copy Markdown
Owner

实现Issue #81 - 增加Telegram官方JSON格式导出历史记录适配

增强功能

  1. 扩展ChatExport模型

    • Video、Voice、VideoNote字段支持
    • Sticker、Contact、Poll、Location模型
    • ForwardedFrom、Reactions、ViaBot字段
    • Caption和Caption_Entities支持
    • 服务消息(Actor、Action)支持
  2. 增强文本提取

    • 支持简单的Text数组(不仅限Text_Entities)
    • 添加贴纸、语音、视频等媒体类型标记
    • 添加投票、联系人、位置等消息类型处理
    • 添加服务消息处理

文件变更

    • 扩展模型定义
    • 增强文本提取逻辑

Fixes #81

Summary by CodeRabbit

  • New Features

    • Enhanced chat import now supports stickers, voice notes, video notes, polls, contacts, locations, and reactions.
    • Improved message metadata preservation including forwarding information and bot references.
  • Bug Fixes

    • Better handling of chat exports where embedded media files are not included.
  • Tests

    • Added test suite for chat import service covering text-only exports.

Copilot AI and others added 4 commits March 3, 2026 08:33
…e bundle support

- Add EnableLocalBotAPI, TelegramBotApiId, TelegramBotApiHash, LocalBotApiPort to Config/Env
- Auto-set BaseUrl and IsLocalAPI when EnableLocalBotAPI is true
- Launch telegram-bot-api.exe as a ChildProcessManager-managed process in GeneralBootstrap
- Add conditional Content entry for telegram-bot-api.exe in .csproj
- Build telegram-bot-api from source via cmake+vcpkg in GitHub Actions push workflow

Co-authored-by: ModerRAS <28183976+ModerRAS@users.noreply.github.com>
- 扩展ChatExport模型支持更多消息类型
  - 添加Video、Voice、VideoNote字段
  - 添加Sticker、Contact、Poll、Location模型
  - 添加ForwardedFrom、Reactions、ViaBot字段
  - 添加Caption和Caption_Entities支持
  - 添加服务消息(Actor、Action)支持

- 增强ChatImportService文本提取
  - 支持简单的Text数组(不仅限Text_Entities)
  - 添加贴纸、语音、视频等媒体类型标记
  - 添加投票、联系人、位置等消息类型处理
  - 添加服务消息处理

Fixes #81
@coderabbitai

coderabbitai Bot commented Mar 19, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@ModerRAS has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 42 minutes and 19 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 42 minutes and 19 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: aa1c41cb-4293-4ff7-a9d8-2059f7b6c1c4

📥 Commits

Reviewing files that changed from the base of the PR and between e397fde and cf0a775.

📒 Files selected for processing (5)
  • TelegramSearchBot.LLM.Test/McpToolHelperTestCollection.cs
  • TelegramSearchBot.LLM.Test/Service/AI/LLM/McpToolHelperTests.cs
  • TelegramSearchBot.LLM.Test/Service/Tools/McpInstallerToolServiceTests.cs
  • TelegramSearchBot/Model/ChatExport/ChatExport.cs
  • TelegramSearchBot/Service/Manage/ChatImportService.cs
📝 Walkthrough

Walkthrough

Extended Telegram chat export support by adding comprehensive JSON model mappings for diverse message types (media, reactions, forwarding), introducing a custom text converter for flexible deserialization, enhancing message text composition logic to include captions and metadata, and adding validation with an integration test demonstrating import of text-only exports.

Changes

Cohort / File(s) Summary
Test Suite
TelegramSearchBot.Test/Service/Manage/ChatImportServiceTests.cs
New xUnit test validating ChatImportService import of text-only JSON exports, verifying message count, FromUserId parsing, entity-to-markdown conversion, and link extraction from text entities.
Chat Export Model
TelegramSearchBot/Model/ChatExport/ChatExport.cs
Extended Message class with 25+ new properties covering media types (video, voice, video-note, sticker), metadata (forwarded_from, via_bot, reactions, actions), and supporting DTOs (StickerInfo, ContactInfo, PollInfo, ReactionInfo). Introduced TextItemListConverter to normalize variable JSON text representations (null/string/object/array) into unified List<TextItem> format.
Service Logic
TelegramSearchBot/Service/Manage/ChatImportService.cs
Added deserialization validation, refactored FromUserId derivation to use new ParseExportUserId() helper supporting ActorId fallback, replaced string-matching media detection with HasEmbeddedFile() checks with warning logs, and comprehensively rewrote GetMessageText() to compose messages from captions, multiple media types, forwarding/reactions metadata, and formatted text entities.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test
    participant Service as ChatImportService
    participant Parser as JSON Parser
    participant DB as DataDbContext
    participant Converter as TextItemListConverter

    Test->>Service: ImportFromFileAsync(jsonFilePath)
    Service->>Parser: Read & Deserialize JSON
    Parser->>Converter: Normalize Message.Text variants
    Converter-->>Parser: List<TextItem>
    Parser-->>Service: ChatExport object
    Service->>Service: Validate ChatExport not null
    Service->>DB: Create messages from export
    loop For each message
        Service->>Service: Parse FromUserId (From_Id or ActorId)
        Service->>Service: Check HasEmbeddedFile for media
        Service->>Service: Compose text (captions + entities + metadata)
        Service->>DB: Insert message with formatted content
    end
    DB-->>Service: Persisted messages
    Service-->>Test: Import complete
    Test->>DB: Query & verify 4 messages, entities, markdown
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 A chatty export hops into view,
With stickers, reactions, and forwards too!
From text to bold with converters bright,
Our imports now handle each media type right.
Telegram tales preserved with delight! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive While PR objectives mention commits introducing telegram-bot-api subprocess management with config options and CI pipeline changes, the provided raw_summary shows only ChatExport model extensions, TextItemListConverter, ChatImportService enhancements, and a test suite—all directly scoped to JSON export format support per Issue #81. Clarify whether subprocess management and CI/build system changes mentioned in commit messages are included in this PR or separate from the core JSON export support objective.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(import): 增强Telegram JSON导出格式支持' (enhance Telegram JSON export format support) directly aligns with the PR's main objective of extending ChatExport model and enhancing text extraction logic for Telegram's official JSON export.
Linked Issues check ✅ Passed The PR successfully implements Issue #81 by extending ChatExport model with new fields (Video, Voice, VideoNote, Sticker, Contact, Poll, Location, etc.), adding TextItemListConverter for flexible text deserialization, and enhancing ChatImportService to handle diverse message types including media, reactions, and service messages.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-81-telegram-json-export

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Mar 19, 2026

Copy link
Copy Markdown
Contributor

🔍 PR检查报告

📋 检查概览

🧪 测试结果

平台 状态 详情
Ubuntu 🟢 成功 测试通过,产物已上传
Windows 🟢 成功 测试通过,产物已上传

📊 代码质量

  • ✅ 代码格式化检查
  • ✅ 安全漏洞扫描
  • ✅ 依赖包分析
  • ✅ 代码覆盖率收集

📁 测试产物

  • 测试结果 artifacts 数量: 2
  • 代码覆盖率已上传到Codecov

🔗 相关链接


此报告由GitHub Actions自动生成

Test User and others added 3 commits March 19, 2026 13:05
Fix whitespace formatting issues detected by CI on Windows
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
TelegramSearchBot/Model/ChatExport/ChatExport.cs (1)

133-189: Set CanWrite to false on TextItemListConverter to prevent infinite recursion during serialization.

The WriteJson method currently delegates to serializer.Serialize(writer, value). Because the converter is attached to Message.Text via [JsonConverter(typeof(TextItemListConverter))], Newtonsoft will re-invoke this same converter during serialization, causing infinite recursion. While the current code only deserializes, serializing a ChatExport (for caching, logging, or round-tripping) will stack-overflow. Setting CanWrite = false disables the custom write logic and lets the default serializer handle it.

♻️ Proposed change
 public class TextItemListConverter : JsonConverter {
+    public override bool CanWrite => false;
+
     public override bool CanConvert(Type objectType) {
         return objectType == typeof(List<TextItem>);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@TelegramSearchBot/Model/ChatExport/ChatExport.cs` around lines 133 - 189, The
JsonConverter TextItemListConverter currently implements WriteJson and calls
serializer.Serialize, which causes infinite recursion when this converter is
applied to Message.Text; to fix, override the converter's CanWrite property to
return false (in the TextItemListConverter class) so Newtonsoft will skip the
converter for writing and use the default serialization path, leaving ReadJson
as-is and preventing stack overflows during serialization.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@TelegramSearchBot/Service/Manage/ChatImportService.cs`:
- Around line 226-242: FormatEntity can throw NullReferenceException because
branches like "mention", "bot_command", and "email" use entity.Text (and call
TrimStart) without null checks; update FormatEntity to short-circuit when
entity.Text is null or empty (similar to FormatItem) before using TrimStart or
interpolating, e.g., for the "mention" / "bot_command" / "email" cases check
string.IsNullOrEmpty(entity.Text) and return entity.Text ?? "" (or the plain
fallback) instead of calling TrimStart on a null value; keep changes confined to
the FormatEntity method and only guard the branches that access entity.Text
directly.

---

Nitpick comments:
In `@TelegramSearchBot/Model/ChatExport/ChatExport.cs`:
- Around line 133-189: The JsonConverter TextItemListConverter currently
implements WriteJson and calls serializer.Serialize, which causes infinite
recursion when this converter is applied to Message.Text; to fix, override the
converter's CanWrite property to return false (in the TextItemListConverter
class) so Newtonsoft will skip the converter for writing and use the default
serialization path, leaving ReadJson as-is and preventing stack overflows during
serialization.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e7d33891-ceb7-4e59-bcb2-2bb9f8443334

📥 Commits

Reviewing files that changed from the base of the PR and between 42a8c2a and e397fde.

📒 Files selected for processing (3)
  • TelegramSearchBot.Test/Service/Manage/ChatImportServiceTests.cs
  • TelegramSearchBot/Model/ChatExport/ChatExport.cs
  • TelegramSearchBot/Service/Manage/ChatImportService.cs

Comment thread TelegramSearchBot/Service/Manage/ChatImportService.cs
ModerRAS and others added 2 commits April 23, 2026 10:25
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@ModerRAS ModerRAS merged commit 2c28709 into master Apr 23, 2026
5 checks passed
@ModerRAS ModerRAS deleted the issue-81-telegram-json-export branch April 23, 2026 02:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

增加Teleram官方的JSON格式导出历史记录适配

2 participants