smoqadam/php-telegram-bot

tg bot api的包装类

v1.0 2017-10-11 07:04 UTC

This package is auto-updated.

Last update: 2024-09-19 12:01:14 UTC


README

Scrutinizer Code Quality Codacy Badge

php-telegram-bot

Telegram Bot API的包装类

安装

创建composer.json文件

{
    "require": {
        "smoqadam/php-telegram-bot": "v1.0"
    }
}

$ composer install

如何使用

Smoqadam\Telegram是Telegram bot API的包装类。在实例化Telegram对象后,您可以在接收到的更新上注册回调,并相应地作出回应。

注册回调:使用以下函数

  • cmd(),所有常规消息
  • inlineQuery()

API方法:可用的方法几乎与官方Telegram API相同(目前包装器不原生处理游戏和消息更新)

  • sendMessage()getMe()forwardMessage()sendPhoto()sendVideo()sendSticker()sendLocation()sendDocument()sendAudio()sendChatAction()getUserProfilePhotos()answerInlineQuery()

获取当前更新:当前更新存储在Telegram::result属性中(它是一个对象)。

内联结果辅助器:为了方便创建内联机器人,在InlineQuery\Result命名空间下有一些辅助类。

  • 文章

键盘辅助器:键盘也是如此;命名空间是Keyboard

  • Standard,经典键盘
  • Remove,移除自定义键盘并显示字母键盘
  • Inline,内联键盘

使用键盘:使用辅助器使用键盘非常简单,在实例化键盘(StandardInline)后,您使用

  • addButton()
  • addRow()

注意:这些方法是链式的。

示例

使用长轮询

<?php

require 'vendor/autoload.php';

use Smoqadam\Telegram;

$tg = new Telegram('API_TOKEN');

$tg->cmd('\/name:<<[a-zA-Z]{0,}>>', function ($args) use ($tg){
	$tg->sendMessage("my username is @".$args , $tg->getChatId());
});


$tg->cmd('\/number: <<:num>>' , function($args) use($tg){
	$tg->sendMessage("your number is : ".$args , $tg->getChatId());
});


$tg->cmd('Hello',function () use ($tg){
	$tg->sendChatAction(Telegram::ACTION_TYPING);
	$image = 'urltoqrcode.png';
	$tg->sendPhoto($image);
});

$tg->run();

使用webHooks

如果您想使用webHooks,您必须首先调用setWebhook方法或使用自己的数据打开以下URL

https://api.telegram.org/API_TOKEN/setWebhook?url=https://yourdomain.com/index.php

请更改API_TOKEN和url参数

<?php
require 'vendor/autoload.php';

$message = file_get_contents('php://input');

use Smoqadam\Telegram;

$tg = new Telegram('API_TOKEN');

$tg->cmd('\/name:<<[a-zA-Z]{0,}>>', function ($args) use ($tg){
		$tg->sendMessage("my username is @".$args , $tg->getChatId());
});


$tg->cmd('\/number: <<:num>>' , function($args) use($tg){
	$tg->sendMessage("your number is : ".$args , $tg->getChatId());
});


$tg->cmd('Hello',function () use ($tg){
	$tg->sendChatAction(Telegram::ACTION_TYPING);
	$image = 'urltoqrcode.png';
	$tg->sendPhoto($image);
});

$tg->process(json_decode($message, true));

现在当您在Telegram机器人页面发送/number 123时,机器人将回答您你的数字是123

您可以在正则表达式中的<<>>之间设置参数

运行机器人

$ php index.php