You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在PHP中查找含视频或图片的Telegram嵌入HTML代码及在浏览器等环境使用Telegram Core API

Let me break down both questions for you clearly, based on my experience working with Telegram's APIs and embedding systems:

1. How to Find Telegram Embedded HTML Code with Videos or Images in a PHP Environment

Extracting or generating Telegram's embedded HTML for media depends on pulling content from public Telegram links or processing existing HTML. Here's a practical, step-by-step approach:

  • Step 1: Fetch the Telegram Share Page HTML
    Public Telegram channel/post links (like https://t.me/c/CHANNEL_ID/MESSAGE_ID) serve a web page with embedded media. Use PHP's file_get_contents or cURL to grab this page—make sure to set a valid User-Agent to avoid being blocked by Telegram's anti-scraping measures.

    Example code:

    $telegramUrl = 'https://t.me/c/123456/789';
    $context = stream_context_create([
        'http' => [
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36\r\n"
        ]
    ]);
    
    try {
        $pageHtml = file_get_contents($telegramUrl, false, $context);
        if (!$pageHtml) throw new Exception("Failed to fetch Telegram page");
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
        exit;
    }
    
  • Step 2: Parse HTML to Extract Media Embeds
    Use PHP's DOMDocument to parse the fetched HTML and filter out media elements. Telegram hosts media on cdn.telesco.pe, so we can use that to target valid images and videos.

    Example for extracting image embeds:

    $dom = new DOMDocument();
    libxml_use_internal_errors(true); // Suppress HTML parsing warnings
    $dom->loadHTML($pageHtml);
    libxml_clear_errors();
    
    // Extract and generate image embed code
    $imageElements = $dom->getElementsByTagName('img');
    foreach ($imageElements as $img) {
        $src = $img->getAttribute('src');
        if (str_contains($src, 'cdn.telesco.pe')) {
            $embeddedImg = '<img src="' . htmlspecialchars($src) . '" alt="Telegram Media" style="max-width: 100%;">';
            echo $embeddedImg;
        }
    }
    

    Example for extracting video embeds:

    // Extract and generate video embed code
    $videoElements = $dom->getElementsByTagName('video');
    foreach ($videoElements as $video) {
        $source = $video->getElementsByTagName('source')->item(0);
        if ($source && str_contains($source->getAttribute('src'), 'cdn.telesco.pe')) {
            $embeddedVideo = '<video controls style="max-width: 100%;">
                                <source src="' . htmlspecialchars($source->getAttribute('src')) . '" type="' . $source->getAttribute('type') . '">
                              </video>';
            echo $embeddedVideo;
        }
    }
    
  • Important Notes

    • This only works for public Telegram content. Private channels/posts require authentication, which adds complexity and isn't recommended due to Telegram's terms of service.
    • Avoid aggressive scraping—Telegram may block your IP if you make too many requests in a short time.
2. Using Telegram Core API (MTProto) in Browsers & Non-Native Environments

Telegram's Core API (MTProto) is a binary protocol built for native apps, but you can use it in non-native environments like browsers with a couple of workarounds. Here are the most reliable methods:

Method 1: Use a JavaScript MTProto Library

Libraries like telegram-mtproto-js wrap MTProto in WebSocket/HTTP tunnels, making it usable in browsers. Here's how to set it up:

  1. Register a Telegram App
    First, get your api_id and api_hash by registering a Telegram application via their official developer portal (you’ll need a Telegram account to complete this).

  2. Implement the Client
    You can install the library via npm, or include it via a CDN. Here's a basic login workflow example:

    // Install via npm first: npm install telegram-mtproto
    const { MTProto } = require('telegram-mtproto');
    
    const apiConfig = {
      layer: 158, // Use the latest layer (check Telegram's docs for updates)
      initConnection: 0x69796de9,
      api_id: YOUR_API_ID, // Replace with your registered API ID
      api_hash: 'YOUR_API_HASH', // Replace with your registered API hash
    };
    
    const serverConfig = {
      dev: false, // Set to true if using Telegram's test servers
    };
    
    const client = new MTProto({ api: apiConfig, server: serverConfig });
    
    // Request a verification code for the user's phone number
    async function requestVerificationCode(phoneNumber) {
      try {
        const response = await client('auth.sendCode', {
          phone_number: phoneNumber,
          settings: { _: 'codeSettings' },
        });
        return response.phone_code_hash; // Save this for the sign-in step
      } catch (error) {
        console.error('Error requesting verification code:', error);
      }
    }
    
    // Sign in using the verification code
    async function signInUser(phoneNumber, code, codeHash) {
      try {
        const user = await client('auth.signIn', {
          phone_number: phoneNumber,
          phone_code_hash: codeHash,
          phone_code: code,
        });
        console.log('Successfully logged in:', user);
      } catch (error) {
        console.error('Sign-in failed:', error);
      }
    }
    
  • Caveats
    • Browsers don't support raw TCP connections, so the library uses WebSockets or HTTP polling. Ensure your hosting supports WebSockets if deploying this.
    • Cross-origin issues may arise if your frontend is hosted on a different domain—most libraries handle this via their own proxy endpoints, but test thoroughly.

For a more stable and secure setup, build a backend service (using PHP, Python, Node.js, etc.) that interacts with the MTProto API, then have your browser frontend communicate with this backend via HTTP/REST.

Example workflow:

  1. Frontend sends a request to your backend (e.g., POST /api/telegram/get-messages).
  2. Backend uses a server-side MTProto library (like mtproto-php for PHP) to call the Telegram Core API.
  3. Backend returns formatted, easy-to-use data to the frontend.
  • Why This is Better
    • No CORS or WebSocket limitations to worry about.
    • You can handle rate limiting, caching, and authentication logic on the backend.
    • Your api_id and api_hash stay secure—never expose them directly in frontend code!

内容的提问来源于stack exchange,提问作者Ehsan Jeihani

火山引擎 最新活动