mero / telegram-handler
用于通过Telegram发送日志的Monolog处理器
0.3.2
2021-01-16 21:45 UTC
Requires
- php: >=5.6 || >=7.0 || >=8.0
- ext-curl: *
- monolog/monolog: ^1.20
Requires (Dev)
- phpunit/phpunit: ^5.6
- satooshi/php-coveralls: ~1.0
Suggests
- symfony/yaml: Needed to use HtmlFormatter feature
README
用于通过Telegram发送日志的Monolog处理器。
要求
- PHP 5.6 或更高版本
- cURL 扩展
使用composer安装
- 打开您的项目目录;
- 运行
composer require mero/telegram-handler
以将TelegramHandler
添加到您的项目vendor中; - 如果您需要使用
\Mero\Monolog\Formatter\HtmlFormatter
,请添加symfony/yaml
依赖项。
声明处理器对象
要声明此处理器,您需要知道要发送日志的bot令牌和聊天标识符(chat_id)。
// ... $handler = new \Mero\Monolog\Handler\TelegramHandler('<token>', <chat_id>, <log_level>); // ...
示例
<?php $log = new \Monolog\Logger('telegram_channel'); $handler = new \Mero\Monolog\Handler\TelegramHandler( '000000000:XXXXX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 111111111, \Monolog\Logger::DEBUG ); $handler->setFormatter(new \Mero\Monolog\Formatter\HtmlFormatter()); $handler->setTimeout(30); $log->pushHandler($handler); $log->debug('Message log');
上面的示例使用HtmlFormatter通过Telegram API。此功能在0.3.0版本中添加,您可以使用声明处理器格式化器使用 \Mero\Monolog\Formatter\HtmlFormatter
类。
您可以使用 setTimeout
方法(在 TelegramHandler
中实现)设置Telegram请求的超时时间。此功能在0.4.0版本中实现,此用法不是必需的。
创建一个机器人
要使用此处理器,您需要在Telegram中创建自己的机器人并接收Bot API访问令牌。为此,与 @BotFather 开始对话。
对话示例
在下面的示例中,我与 @BotFather 交谈,创建了一个名为 "Cronus Bot" 的机器人,用户名为 "@cronus_bot"。
Me: /newbot
---
@BotFather: Alright, a new bot. How are we going to call it? Please choose a name for your bot.
---
Me: Cronus Bot
---
@BotFather: Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example:
TetrisBot or tetris_bot.
---
Me: cronus_bot
---
@BotFather: Done! Congratulations on your new bot. You will find it at telegram.me/cronus_bot. You can now add a
description, about section and profile picture for your bot, see /help for a list of commands. By the way, when
you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure
the bot is fully operational before you do this.
Use this token to access the HTTP API:
000000000:XXXXX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
提供一个聊天标识符
为了获取将发送日志的chat_id,接收者用户首先需要与机器人进行对话。对话开始后,请执行以下请求以了解该对话的chat_id。
URL: https://api.telegram.org/bot_token_/getUpdates
示例
Request
-------
POST https://api.telegram.org/bot000000000:XXXXX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx/getUpdates
Response
--------
{
"ok": true,
"result": [
{
"update_id": 141444845,
"message": {
"message_id": 111,
"from": {
"id": 111111111,
"first_name": "Rafael",
"last_name": "Mello",
"username": "merorafael"
},
"chat": {
"id": 111111111,
"first_name": "Rafael",
"last_name": "Mello",
"username": "merorafael",
"type": "private"
},
"date": 1480701504,
"text": "test"
}
}
]
}
在上面的请求中,chat_id 由数字 "111111111" 表示。