<?php // get category model by category id, assume…
使用PHP Webhook方式打造Telegram Bot,获取telegram id, 获取telegram group id, PHP通过telegram bot给自己或群组发消息
准备
1. 本地测试需要有ssl才可以,可以通过免费版的ngrok来解决!
2. 所有使用前提,都是要先浏览器打开 https://api.telegram.org/bot(BOT_TOKEN)/setWebhook?url=https://yoursite.com/your_update.php 设置好webhook
3. webhook 和 getUpdate() 两种方式不能同时使用
1.创建机器人
使用浏览器访问 https://t.me/botfather 会自动跳转到 BotFather
的对话框,或者直接在手机 Telegram App 内搜索BotFather
。这个是管理你机器人的命令对话框。与它的对话都要以/
开头。有些指令。/help
,可以看到所有的可用指令
1. @BotFather
带有以下文本的消息:/newbot
如果您不知道如何通过用户名发送消息,请单击Telegram应用程序上的搜索字段,然后键入@BotFather
,您应该可以在其中发起对话。请注意不要将其发送给错误的联系人,因为某些用户的用户名与相似BotFather
。

2. @BotFather
回复:
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
3. 键入您的机器人想要的任何名称。
4. @BotFather
回复:
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
5. 输入您的机器人所需的用户名,至少5个字符,并且必须以结束bot。例如:telesample_bot
6. @BotFather
回复:
Done! Congratulations on your new bot. You will find it at telegram.me/telesample_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. Use this token to access the HTTP API: 123456789:AAG90e14-0f8-40183D-18491dDE For a description of the Bot API, see this page: https://core.telegram.org/bots/api
7. 记下上面提到的“令牌”。
(可选)设置漫游器隐私:
- 发送
/setprivacy
到@BotFather
。使用PHP Webhook方式打造Telegram Bot,获取telegram id, 获取telegram group id, PHP通过telegram bot给自己或群组发消息 @BotFather
回复:Choose a bot to change group messages settings.
- 键入(或选择)
@telesample_bot
(更改为您在上面的第5步中设置的用户名,但以开头@
) @BotFather
回复:'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username. 'Disable' - your bot will receive all messages that people send to groups. Current status is: ENABLED
- 键入(或选择)
Disable
,让您的漫游器接收发送到组的所有消息。 @BotFather
回复:Success! The new status is: DISABLED. /help
2. 轻松设置Telegram Bot WebHook
为了使Bot响应来自Telegram用户的请求,您需要手动请求对Bot API的更新,或者您可以注册一个WebHook以在更新可用后自动被调用。
后者是一种更好,更有效的解决方案。
话虽这么说,为Bot设置WebHook的最快和最简单的方法是向Bot API发出GET请求(足以在浏览器中打开URL)。
所有你需要做的就是通过以下网址调用setWebHook方法:
https://api.telegram.org/bot{my_bot_token}/setWebhook?url={url_to_send_updates_to}
用法
- my_bot_token是您在创建Bot时从BotFather获得的令牌
- url_to_send_updates_to是您为实现Bot行为而编写的代码的URL(必须为HTTPS)
例如:
https://api.telegram.org/botxxxxxx:xxxxxxxx?url=https://your-domain.com/bot.php
通过浏览器打开网址,你会看到:
{"ok":true,"result":true,"description":"Webhook was set"}
那么,您已经完成了。
现在,如果您转到以下网址(您必须用Bot令牌替换{my_bot_token})
https://api.telegram.org/bot{my_bot_token}/getWebhookInfo
您应该会看到以下内容:
{ "ok":true, "result": { "url":"https://your-domain.com/bot.php", "has_custom_certificate":false, "pending_update_count":0, "max_connections":40 } }
如果你想获取更多信息,也可以打开网址:
https://api.telegram.org/bot{my_bot_token}/getMe
您应该会看到以下内容:
{ "ok": true, "result": { "id": your-chat-id, "is_bot": true, "first_name": "your-first-name", "username": "your-username", "can_join_groups": true, "can_read_all_group_messages": true, "supports_inline_queries": false } }
更多操作,可以查看官网API: https://core.telegram.org/bots/api
3. 在Telegram中给自己的bot发消息进行验证
在你的webhook文件 https://your-domain.com/bot.php 写入测试代码:
<?php define('BOT_TOKEN', 'YOURBOT:TOKEN'); define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/'); // read incoming info and grab the chatID $content = file_get_contents("php://input"); $update = json_decode($content, true); $chatID = $update["message"]["chat"]["id"]; $got_message = $update["message"]["text"]; // compose reply $reply = $got_message; // send reply $sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply; file_get_contents($sendto);
用自己的telegram测试发信息给你的telegram bot,将会得到一样的回复!
4. 如何查找自己的 telegram ID 或者 群组 ID group id
您似乎必须通过机器人来获取此信息。搜索“userinfobot”并输入“ / start”。该漫游器会以您的句柄和ID进行响应。

如何获取电报群组的ID?
上面我们通过userinfobot这个机器人获取个人的chat_id, 使得机器人可以发消息给个人,群组则没办法通过这种方式获取其ID。
通过下面的步骤可以获得群组ID:
- 在群里发送任意消息
- 打开这个网址 https://api.telegram.org/bot<替换成你机器人的token, 包括尖括号>/getUpdates, 页面会输出一段JSON
- 查找 id: -xxx 的一段值,这里的 -xxx 就是群组ID,机器人下发消息的时候的chat_id字段使用这个即可发送消息到群组了
至此我们已经可以通过程序触发电报机器人下发消息给个人或群组了,只需要在你后台程序合适的地方触发即可,或者设立定时任务来触发下发消息或报表。
除了发送文本消息,还可以发送图片,语音,视频,动画,文件等等。
5. API 操作
大概可以用到的函数:
// 向telegram bot指定域名 public function setWebhook() { $url = 'https://api.telegram.org/bot' . $this->token . '/setWebhook'; $data = [ 'url' => $this->callback. '?token=' . md5($this->token), ]; $result = $this->curl_post($url, $data); } # 这里token就是创建机器人时得到的token,callback为你自己的回调路径通过post发送给bot,$result返回信息会告诉你回调路径是否设置成功 // 接收bot回调信息 public function receive() { $input = file_get_contents('php://input'); $input = json_decode($input, true); } #设置成功后每当bot接收到信息就会回调到receive方法,根据$input接收到的数据进行逻辑处理 // 删除回调 public function deleteWebhook() { $url = 'https://api.telegram.org/bot' . $this->token . '/deleteWebhook'; $data = [ 'url' => $this->callback. '?token=' . md5($this->token), ]; $result = $this->curl_post($url, $data); } // 查看当前回调信息 public function getWebhookInfo() { $url = 'https://api.telegram.org/bot' . $this->token . '/getWebhookInfo'; $data = [ 'url' => $this->callback. '?token=' . md5($this->token), ]; $result = $this->curl_post($url, $data); } // post public function curl_post($url, $data) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); $result = curl_exec($curl); curl_close($curl); return $result; } # 回复用户信息,可以在前面$input中拿到消息的chatid // 回复用户信息 public function sendMessage($chatId, $text) { $url = 'https://api.telegram.org/bot' . $this->token . '/sendMessage'; $param = "?chat_id=".$chatId."&text=".$text; $data = [ 'chat_id' => $chatId, 'text' => $text, ]; $result = $this->curl_post($url, $data); $result = json_decode($result, true); if ($result['ok'] == true) { return true; } else { $this->writeLog("error"); return false; } }
如果你不使用PHP,可以通过CURL来测试下发消息,CURL代码如下:
curl -X POST “https://api.telegram.org/bot<token>/sendMessage" -d "chat_id=-xxx&text=Justcode"
你也可以使用php库:TelegramBotPHP 或者 php-telegram-bot
git clone https://github.com/Eleirbag89/TelegramBotPHP.git
所有使用前提,都是要先浏览器打开 https://api.telegram.org/bot(BOT_TOKEN)/setWebhook?url=https://yoursite.com/your_update.php 设置好webhook
使用:
主动发信息,需要打开send.php
<?php include 'TelegramBotPHP/Telegram.php'; $telegram = new Telegram('your-taken'); $chat_id = $telegram->ChatID(); $content = array('chat_id' => $chat_id, 'text' => 'Are you OK? Hello, Thank You!'); $telegram->sendMessage($content);
接收信息或者信息交互,需要打开bot.php 或者 update.php ,也就是 注册 webhook 的页面
<?php include 'TelegramBotPHP/Telegram.php'; $telegram = new Telegram('your-token'); $result = $telegram->getData(); $text = $result['message'] ['text']; $chat_id = $result['message'] ['chat']['id']; $content = array('chat_id' => $chat_id, 'text' => 'Test'); $telegram->sendMessage($content);
发图片:
// Load a local file to upload. If is already on Telegram's Servers just pass the resource id $img = curl_file_create('test.png','image/png'); $content = array('chat_id' => $chat_id, 'photo' => $img ); $telegram->sendPhoto($content);
下载文件:
$file = $telegram->getFile($file_id); $telegram->downloadFile($file['result']['file_path'], './my_downloaded_file_on_local_server.png');
如果要使用getUpdates而不是WebHook,则需要serveUpdate
在for循环内调用该函数。
$telegram = new Telegram('YOUR TELEGRAM TOKEN HERE'); $req = $telegram->getUpdates(); for ($i = 0; $i < $telegram-> UpdateCount(); $i++) { // You NEED to call serveUpdate before accessing the values of message in Telegram Class $telegram->serveUpdate($i); $text = $telegram->Text(); $chat_id = $telegram->ChatID(); if ($text == '/start') { $reply = 'Working'; $content = array('chat_id' => $chat_id, 'text' => $reply); $telegram->sendMessage($content); } // DO OTHER STUFF }
本文:使用PHP Webhook方式打造Telegram Bot,获取telegram id, 获取telegram group id, PHP通过telegram bot给自己或群组发消息