使用电报 API 和 PHP

Using telegram API with PHP

我正在尝试使用 Telegram API 制作带有 PHP 的在线广告应用程序,但我遇到的问题是我什至无法理解向电报网站发出请求。这是我根据 Telegram 的 API 和协议编写的简短代码:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Length" content="348">
    <meta http-equiv="Connection" content="keep-alive">
    <meta http-equiv="Host" content="149.154.167.40:80">
</head>

<body>
<?php
$url = '149.154.167.40';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);

$result = curl_exec($curl);

echo $result;

?>
</body>
</html>

有人知道如何让它发挥作用吗?

Telegram API 使用起来很痛苦,你必须应用各种加密魔法才能使用他们的 MTProto 协议,而且 PHP 可用的参考或示例很少。我建议您使用他们的新 Bot API. It is a service the created that abstracts all the MTProto interactions behind a simple HTTP layer. You first need to generate a bot using their Bot Father,然后使用 ID 与 API.

进行交互

正在接收新消息(轮询):

<?php

$bot_id = "<bot ID generated by BotFather>";

# Note: you want to change the offset based on the last update_id you received
$url = 'https://api.telegram.org/bot' . $bot_id . '/getUpdates?offset=0';
$result = file_get_contents($url);
$result = json_decode($result, true);

foreach ($result['result'] as $message) {
    var_dump($message);
}

正在发送消息:

# The chat_id variable will be provided in the getUpdates result
$url = 'https://api.telegram.org/bot' . $bot_id . '/sendMessage?text=message&chat_id=0';
$result = file_get_contents($url);
$result = json_decode($result, true);

var_dump($result['result']);

您也可以使用 webhook 而不是轮询更新。您可以在我链接的 API 文档中找到更多信息。

你可以使用这个库:

PHP 电报 MTProto 协议的实现(更好tg-cli) https://github.com/danog/MadelineProto

简单示例代码:

<?php

if (!file_exists('madeline.php')) {
    copy('https://phar.madelineproto.xyz/madeline.php', 'madeline.php');
}
include 'madeline.php';

$MadelineProto = new \danog\MadelineProto\API('session.madeline');
$MadelineProto->start();

$me = $MadelineProto->get_self();

\danog\MadelineProto\Logger::log($me);

if (!$me['bot']) {
    $MadelineProto->messages->sendMessage(['peer' => '@danogentili', 'message' => "Hi!\nThanks for creating MadelineProto! <3"]);
    $MadelineProto->channels->joinChannel(['channel' => '@MadelineProto']);

    try {
        $MadelineProto->messages->importChatInvite(['hash' => 'https://t.me/joinchat/Bgrajz6K-aJKu0IpGsLpBg']);
    } catch (\danog\MadelineProto\RPCErrorException $e) {
    }

    $MadelineProto->messages->sendMessage(['peer' => 'https://t.me/joinchat/Bgrajz6K-aJKu0IpGsLpBg', 'message' => 'Testing MadelineProto!']);
}
echo 'OK, done!'.PHP_EOL;