iqbalfarhan08 / telegramtools
简单的Telegram机器人功能
Requires
- php: >=7.2
This package is auto-updated.
Last update: 2024-09-24 05:20:58 UTC
README
安装
本包包含sendMessage和sendPhoto函数,用于Telegram机器人。本包适用于Laravel 8及以上版本。
安装包
在终端中运行以下命令来安装此包:
composer require iqbalfarhan08/telegramtools
发布配置文件
在您的终端中运行以下publish config函数:
php artisan vendor:publish --provider="Iqbalfarhan08\Telegramtools\TelegramToolServiceProvider"
执行此命令后,您的配置文件夹中将会出现一个新的名为"telegramtools.php"的文件,其中包含可以按需更改的配置文件。
环境配置
将此密钥添加到.env文件中,以配置您的机器人:
TELEGRAM_BOT_TOKEN="TELEGRAM_BOT_KAMU"
TELEGRAM_DEFAULT_CHAT_ID="CHAT_ID"
TELEGRAM_WEBHOOK_URL="WEBHOOK URL"
使用方法
使用Telegramtools
Telegramtools是一个trait,您可以在创建的类中使用use TelegramTrait
use Iqbalfarhan08\Telegramtools\Trait\TelegramTrait;
class YourController extends Controller
{
use TelegramTrait
...
}
设置Telegram Chat Id
在发送文本或图片消息之前,设置chat id。chat id可以是个人或群组的。chat id是数字,您可以从Telegram中的许多机器人获取,然后通过以下方式设置您的chat id:
$this->setChatId("CHATID");
发送文本消息
您可以使用以下方法发送文本消息:
$text = "hallo gais apkabs?";
$this->setChatId($chat_id);
return $this->sendMessage($text);
第一个参数sendMessage是必需的(必须填写)且为字符串。
发送图片消息
您可以使用以下方法发送图片消息:
$photo = "https://cdn-icons-png.flaticon.com/512/282/282100.png";
$caption = "gambar link";
$this->setChatId($chat_id);
return $this->sendPhoto($photo, $caption);
sendPhoto方法有两个参数:
- $photo:必需的(必须填写)且为字符串。
- $caption:可选的(不必填写)且为字符串。
接收来自Telegram的帖子
设置webhook
您可以在web.php或api.php中创建一个独立的路由来设置webhook。
// file api.php
Route::get('telegram/setWebhook', [API\TelegramController::class, 'setWebhook']);
// file API\TelegramController.php
use TelegramTrait;
// dengan url
public function setWebhook(){
$url = "https://https://domain.com/api/telegram/";
$this->setWebHook($url);
}
// atau tanpa url
public function setWebhook(){
$this->setWebHook();
}
然后访问该路由: https://domain.com/api/telegram/setWebhook。
如果不输入$url webhook,它将被设置为.env文件中TELEGRAM_WEBHOOK_URL的值。
创建用于执行Telegram帖子的控制器
创建一个用于Telegram操作的控制器。例如,创建文件API\TelegramController,运行
php artisan make:controller API/TelegramController
然后创建index函数作为post的目的地。不要忘记创建Telegram webhook的路由。
// file api.php
// webhook https://domain.com/api/telegram
Route::post('telegram', [API\TelegramController::class, 'index']);
// file API TelegramController.php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Traits\TelegramTrait;
use Illuminate\Http\Request;
class TelegramController extends Controller
{
use TelegramTrait;
public function index()
{
$req = json_decode(file_get_contents("php://input"), TRUE);
$chat_id = $req['message']['chat']['id'];
$this->setChatId($chat_id);
return $this->sendMessage("silakan ini dia Telegram ID kamu <b>{$chat_id}</b>");
}
public function resetWebhook()
{
return $this->setWebhook();
}
}
结尾
这还是一个初始版本,可能会对包进行优化。