Skip to content

Commit

Permalink
feat(tg): support channel comment link
Browse files Browse the repository at this point in the history
  • Loading branch information
iyear committed Oct 7, 2023
1 parent e37cde3 commit 3c1f718
Showing 1 changed file with 45 additions and 25 deletions.
70 changes: 45 additions & 25 deletions pkg/utils/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strconv"
"strings"

"github.com/go-faster/errors"
"github.com/gotd/td/telegram/peers"
"github.com/gotd/td/telegram/query"
"github.com/gotd/td/tg"
Expand All @@ -18,58 +19,77 @@ var Telegram telegram

// ParseMessageLink return dialog id, msg id, error
func (t telegram) ParseMessageLink(ctx context.Context, manager *peers.Manager, s string) (peers.Peer, int, error) {
parse := func(from, msg string) (peers.Peer, int, error) {
ch, err := t.GetInputPeer(ctx, manager, from)
if err != nil {
return nil, 0, errors.Wrap(err, "input peer")
}

m, err := strconv.Atoi(msg)
if err != nil {
return nil, 0, errors.Wrap(err, "parse message id")
}

return ch, m, nil
}

u, err := url.Parse(s)
if err != nil {
return nil, 0, err
}

paths := strings.Split(strings.TrimPrefix(u.Path, "/"), "/")

from, msg := "", ""
// https://t.me/opencfdchannel/4434?comment=360409
if c := u.Query().Get("comment"); c != "" {
peer, err := t.GetInputPeer(ctx, manager, paths[0])
if err != nil {
return nil, 0, errors.Wrap(err, "input peer")
}

ch, ok := peer.(peers.Channel)
if !ok || !ch.IsBroadcast() {
return nil, 0, errors.New("not channel")
}

raw, err := ch.FullRaw(ctx)
if err != nil {
return nil, 0, errors.Wrap(err, "full raw")
}

linked, ok := raw.GetLinkedChatID()
if !ok {
return nil, 0, errors.New("no linked chat")
}

return parse(strconv.FormatInt(linked, 10), c)
}

switch len(paths) {
case 2:
// https://t.me/telegram/193

from = paths[0]
msg = paths[1]
// https://t.me/myhostloc/1485524?thread=1485523
return parse(paths[0], paths[1])
case 3:
// https://t.me/c/1697797156/151
// https://t.me/iFreeKnow/45662/55005

if paths[0] == "c" {
from = paths[1]
msg = paths[2]
break
return parse(paths[1], paths[2])
}

// "45662" means topic id, we don't need it
from = paths[0]
msg = paths[2]
return parse(paths[0], paths[2])
case 4:
// https://t.me/c/1492447836/251015/251021

if paths[0] != "c" {
return nil, 0, fmt.Errorf("invalid message link")
}

// "251015" means topic id, we don't need it
from = paths[1]
msg = paths[3]
return parse(paths[1], paths[3])
default:
return nil, 0, fmt.Errorf("invalid message link: %s", s)
}

ch, err := t.GetInputPeer(ctx, manager, from)
if err != nil {
return nil, 0, err
}

msgid, err := strconv.Atoi(msg)
if err != nil {
return nil, 0, err
}

return ch, msgid, nil
}

func (t telegram) GetInputPeer(ctx context.Context, manager *peers.Manager, from string) (peers.Peer, error) {
Expand Down

0 comments on commit 3c1f718

Please sign in to comment.