在Telegram上面创建机器人,并且实现用PHP对接TG的机器人API达到推送消息。
TG相当于咋们国内的QQ了,是外国人常用的聊天软件,在TG里面可以自由的创建BOT,并且对接上。
在这里说说Telegram的Bot api,首先我们要有一个机器人
打开@botfather:https://telegram.me/botfather
然后在输入框里面输入 /newbot
botfather会反馈:Alright, a new bot. How are we going to call it? Please choose a name for your bot.
然后输入要创建的机器人名字。比如:ityinhucombot
它会反馈:Good. Now let's choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.
在输入一遍机器人名字:ityinhucombot
然后会反馈一段信息:
可以看到创建成功,第一个箭头是你机器人的链接,第二个相当于是API的密钥就是 api token
这里生成了api token,一定要把它记下来,以后api请求都会用到
输入/token
可以重新生成一个token。/revoke
可以撤销一个token
我们打开我们的机器人窗口,给他发个 /hello
然后访问:https://api.telegram.org/botxxx:xxx/getUpdates
这里的xxx:xxx填写你的api token
然后会出现json数据
{
"ok" : true,
"result" : [{
"update_id" : xxx,
"message" : {
"message_id" : 4,
"from" : {
"id" : xxx,
"first_name" : "david",
"last_name" : "huang",
"username" : "davidhuang"
},
"chat" : {
"id" : -xxx,
"title" : "bot",
"type" : "group",
"all_members_are_administrators" : true
},
"date" : xxx,
"text" : "/hello @ityinhubot",
"entities" : [{
"type" : "bot_command",
"offset" : 0,
"length" : 6
}
]
}
},
]
}
好,这个我们看到有个ID,这个ID就是我们TG的id,机器人给你推送消息的时候就会用到这个ID。
推送消息的api格式:
https://api.telegram.org/bot[bot_api_key]/sendMessage?chat_id=[tgid]&text=[text]
PHP调用代码:
<?php
$bot_api_key = 'CHANGE HERE';
function send_get($urlstring){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlstring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
curl_close($ch); return $result;
}
$text = @"银狐笔记";
$tgid = @$_GET["tgid"];
if($text){
$url = "https://api.telegram.org/bot$bot_api_key/sendMessage?chat_id=$tgid&text=$text";
echo send_get($url);
}else{
echo "Please Input";
}
?>
很简单吧,我想各位应该都看懂了,如果机器人没法给你发消息的话,请先给TG机器人发个消息这样才能给你发。