gramjs icon indicating copy to clipboard operation
gramjs copied to clipboard

Extract hyperlink from message

Open Dashi321 opened this issue 1 year ago • 4 comments

I couldn't find the way to extract a link from a hyperlink within a text from a message that was sent in a channel.

Dashi321 avatar May 10 '24 21:05 Dashi321

See Message entities

polRk avatar May 12 '24 12:05 polRk

You can parse the message to HTML and then extract links using regexp or the Cheerio DOM parser. Example:

import {HTMLParser} from 'telegram/extensions/html';
import * as cherrio from 'cheerio';


const html = HTMLParser.unparse(message, entities);

const $ = cherrio.load(html);
// => Work with DOM like jQuery to extract your links
// => $("a:contains('Your Anchor')").attr("href");

nghiepdev avatar May 13 '24 17:05 nghiepdev

switch (history.className) {
    case "messages.ChannelMessages":
        for (const message of history.messages) {
            switch (message.className) {
                case "Message":
                    for (const entity of message.entities || []) {
                        switch (entity.className) {
                            case "MessageEntityUrl":
                                const url = message.rawText.slice(entity.offset, entity.offset + entity.length)
                                console.log(url)
                                break
                        }
                    }
            }
        }
}

polRk avatar May 13 '24 18:05 polRk

You can parse the message to HTML and then extract links using regexp or the Cheerio DOM parser. Example:

import {HTMLParser} from 'telegram/extensions/html';
import * as cherrio from 'cheerio';


const html = HTMLParser.unparse(message, entities);

const $ = cherrio.load(html);
// => Work with DOM like jQuery to extract your links
// => $("a:contains('Your Anchor')").attr("href");

Exactly what I needed to get the full message. Thanks!

mcfriend99 avatar Jul 29 '24 10:07 mcfriend99