MENU

Telegram 机器人推送代码

April 20, 2019 • 已被 320 位童鞋围观过 • 代码分享

Telegram机器人 官方给出的API接口 很全,看教程写了一个主动推送消息的接口,试了试 感觉不错。
写篇教程啊首先要创建一个bot。
访问 https://telegram.me/botfather 或者 @botfather
它会提示你用telegram打开。然后你就打开了botfarther的聊天对话框。输入

/newbot

回车发送。botfarther会反馈
...... 一下略过 没什么技术含量 找到

Use this token to access the HTTP API:
12345678:xxxxxxxxx

获取到token

想发到群或者频道 需要把机器人添加到群或者频道 个人直接给他对话
然后访问

https://api.telegram.org/bot12345678:xxxxxxxxx/getUpdates
//需要注意前面有个bot !!!!!!!!
//是 bot12345678:xxxxxxxxx 而不是 12345678:xxxxxxxxx

获取JSON值 找到ID 这个过程不累述了。
然后剩下的就简单了。
直接访问

$token="bot123456:xxxxxxx";
$text=urlencode("你好啊,我是机器人");
$reply_markup='{"type": "InlineKeyboardMarkup","inline_keyboard": [[{"text": "点击访问网站","url": "https://yooer.me/telegram-%E6%9C%BA%E5%99%A8%E4%BA%BA%E6%8E%A8%E9%80%81%E4%BB%A3%E7%A0%81.html"}]]}';
$chat_id="";//群ID 或者用户ID
$url="https://api.telegram.org/bot".$token."/sendMessage?parse_mode=HTML&disable_web_page_preview=1&chat_id=".$chat_id."&text=".$text."&reply_markup=".urlencode($reply_markup);

注意几点 $text 和 $reply_markup 需要urlencode();
如果不需要连接地址的话 不带就可以了。
parse_mode 支持 参数有两个 parse_mode=HTML,parse_mode=Markdown
HTML支持

<b>bold</b>, <strong>bold</strong>
<i>italic</i>, <em>italic</em>
<a href="http://yooer.me/">阳Home</a>
<a href="tg://user?id=123456789">inline mention of a user</a>
<code>inline fixed-width code</code>
<pre>pre-formatted fixed-width code block</pre>

Markdown支持

*bold text*
_italic text_
[inline URL](http://www.example.com/)
[inline mention of a user](tg://user?id=123456789)
`inline fixed-width code`
```block_language
pre-formatted fixed-width code block

text 字段里面可以写网址的
disable_web_page_preview=1 TG的web 预览 0开启 1关闭

[download id=218]

Last Modified: September 28, 2023