ParseMessageLink 解析 Telegram 消息链接 支持格式: - https://t.me/username/123 - https://t.me/c/123456789/123 - https://t.me/c/123456789/111/456 (topic id) - https://t.me/username/123?comment=2 (评论)
(ctx context.Context, link string)
| 66 | // - https://t.me/c/123456789/111/456 (topic id) |
| 67 | // - https://t.me/username/123?comment=2 (评论) |
| 68 | func ParseMessageLink(ctx context.Context, link string) (int64, int, error) { |
| 69 | u, err := url.Parse(link) |
| 70 | if err != nil { |
| 71 | return 0, 0, fmt.Errorf("invalid URL: %w", err) |
| 72 | } |
| 73 | paths := strings.Split(strings.TrimPrefix(u.Path, "/"), "/") |
| 74 | |
| 75 | if cmt := u.Query().Get("comment"); cmt != "" { |
| 76 | // 频道评论的消息链接 |
| 77 | if len(paths) < 1 { |
| 78 | return 0, 0, fmt.Errorf("invalid message link format: %s", link) |
| 79 | } |
| 80 | // 简化处理:返回错误,提示不支持评论链接 |
| 81 | return 0, 0, fmt.Errorf("comment links are not supported") |
| 82 | } |
| 83 | |
| 84 | switch len(paths) { |
| 85 | case 2: // https://t.me/username/123 |
| 86 | chatID, err := resolveChatID(ctx, paths[0]) |
| 87 | if err != nil { |
| 88 | return 0, 0, fmt.Errorf("failed to resolve chat ID: %w", err) |
| 89 | } |
| 90 | msgID, err := strconv.Atoi(paths[1]) |
| 91 | if err != nil { |
| 92 | return 0, 0, fmt.Errorf("failed to parse message ID: %w", err) |
| 93 | } |
| 94 | return chatID, msgID, nil |
| 95 | case 3: |
| 96 | // https://t.me/c/123456789/123 |
| 97 | // https://t.me/username/123/456 , 123: topic id |
| 98 | chatPart, msgPart := paths[1], paths[2] |
| 99 | if paths[0] != "c" { |
| 100 | chatPart = paths[0] |
| 101 | } |
| 102 | chatID, err := resolveChatID(ctx, chatPart) |
| 103 | if err != nil { |
| 104 | return 0, 0, fmt.Errorf("failed to resolve chat ID: %w", err) |
| 105 | } |
| 106 | msgID, err := strconv.Atoi(msgPart) |
| 107 | if err != nil { |
| 108 | return 0, 0, fmt.Errorf("failed to parse message ID: %w", err) |
| 109 | } |
| 110 | return chatID, msgID, nil |
| 111 | case 4: |
| 112 | // https://t.me/c/123456789/111/456 111: topic id |
| 113 | if paths[0] != "c" { |
| 114 | return 0, 0, fmt.Errorf("invalid message link format: %s", link) |
| 115 | } |
| 116 | chatID, err := resolveChatID(ctx, paths[1]) |
| 117 | if err != nil { |
| 118 | return 0, 0, fmt.Errorf("failed to resolve chat ID: %w", err) |
| 119 | } |
| 120 | msgID, err := strconv.Atoi(paths[3]) |
| 121 | if err != nil { |
| 122 | return 0, 0, fmt.Errorf("failed to parse message ID: %w", err) |
| 123 | } |
| 124 | return chatID, msgID, nil |
| 125 | } |
no test coverage detected