PHP code example of dueros / bot-sdk

1. Go to this page and download the library: Download dueros/bot-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dueros / bot-sdk example snippets


use \Baidu\Duer\Botsdk\Card\TextCard;

$this->addIntentHandler('remind', function(){
    $remindTime = $this->getSlot('remind_time');
   
    if($remindTime) {
        $card = new TextCard('创建中');
        return [
            'card' => $card,
        ];
    }
});

/**
 * 或者,可以不通过匿名函数,还支持传入成员函数名
 */

$this->addIntentHandler('remind', 'create');

//定义一个成员函数
public function create(){
    $remindTime = $this->getSlot('remind_time');
    return [...];
}

use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\BodyTemplate1;

$bodyTemplate = new BodyTemplate1();
//设置模版token
$bodyTemplate->setToken('token');
//设置模版背景图片
$bodyTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//设置模版标题
$bodyTemplate->setTitle('托尔斯泰的格言');
//设置模版plain类型的文本
$bodyTemplate->setPlainTextContent('拖尔斯泰-理想的书籍是智慧的钥匙'); 
//定义RenderTemplate指令
$directive = new RenderTemplate($bodyTemplate);
return [
    'directives' => [$directive],
    'outputSpeech' => '这是BodyTemplate1模板',
];

use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\BodyTemplate2;

$bodyTemplate = new BodyTemplate2();
//设置模版token
$bodyTemplate->setToken('token');
//设置模版展示图片
$bodyTemplate->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//or 图片设置宽和高
$bodyTemplate->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg', 200, 200);
//设置模版背景图片
$bodyTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//设置模版标题
$bodyTemplate->setTitle('托尔斯泰的格言');
//设置模版plain类型的文本结构
$bodyTemplate->setPlainContent('拖尔斯泰-理想的书籍是智慧的钥匙'); 
//定义RenderTemplate指令
$directive = new RenderTemplate($bodyTemplate);
return [
    'directives' => [$directive],
    'outputSpeech' => '这是BodyTemplate2模板',
];


use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\BodyTemplate3;

$bodyTemplate = new BodyTemplate3();
//设置模版token
$bodyTemplate->setToken('token');
//设置模版展示图片
$bodyTemplate->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//or 图片设置宽和高
$bodyTemplate->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg', 200, 200);

//设置模版背景图片
$bodyTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//设置模版标题
$bodyTemplate->setTitle('托尔斯泰的格言');
//设置模版plain类型的文本结构
$bodyTemplate->setPlainContent('拖尔斯泰-理想的书籍是智慧的钥匙');  
//定义RenderTemplate指令
$directive = new RenderTemplate($bodyTemplate);
return [
    'directives' => [$directive],
    'outputSpeech' => '这是BodyTemplate3模板',
];


use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\BodyTemplate4;

$bodyTemplate = new BodyTemplate4();
//设置模版token
$bodyTemplate->setToken('token');
//设置模版展示图片
$bodyTemplate->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//or 图片设置宽和高
$bodyTemplate->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg', 200, 200);

//设置模版背景图片
$bodyTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//设置模版标题
$bodyTemplate->setTitle('托尔斯泰的格言');
//设置模版plain类型的文本结构
$bodyTemplate->setPlainContent('拖尔斯泰-理想的书籍是智慧的钥匙'); 
//定义RenderTemplate指令
$directive = new RenderTemplate($bodyTemplate);
return [
    'directives' => [$directive],
    'outputSpeech' => '这是BodyTemplate4模板',
];


use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\BodyTemplate5;

$bodyTemplate = new BodyTemplate5();
//设置模版token
$bodyTemplate->setToken('token');
//模版图片数组添加一张图片
$bodyTemplate->addImages('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//设置模版背景图片
$bodyTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
/设置模版标题
$bodyTemplate->setTitle('托尔斯泰的格言');
//定义RenderTemplate指令
$directive = new RenderTemplate($bodyTemplate);
return [
    'directives' => [$directive],
    'outputSpeech' => '这是BodyTemplate5模板',
];


use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\ListTemplate1;
use \Baidu\Duer\Botsdk\Directive\Display\Template\ListTemplateItem;

$listTemplate = new ListTemplate1();
//设置模板token
$listTemplate->setToken('token');
//设置模板背景图
$listTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//设置模版标题
$listTemplate->setTitle('托尔斯泰的格言');

//设置模版列表数组listItems其中一项,即列表的一个元素
$listTemplateItem = new ListTemplateItem();
$listTemplateItem->setToken('token');
$listTemplateItem->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//or 图片设置宽和高
$listTemplateItem->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg', 200, 200);

$listTemplateItem->setPlainPrimaryText('一级标题');
$listTemplateItem->setPlainSecondaryText('二级标题');

//把listTemplateItem添加到模版listItems
$listTemplate->addItem($listTemplateItem);
//定义RenderTemplate指令
$directive = new RenderTemplate($listTemplate);
return [
    'directives' => [$directive],
    'outputSpeech' => '这是ListTemplate1模板',
];


use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\ListTemplate2;
use \Baidu\Duer\Botsdk\Directive\Display\Template\ListTemplateItem;

$listTemplate = new ListTemplate2();
//设置模板token
$listTemplate->setToken('token');
//设置模板背景图
$listTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
//设置模版标题
$listTemplate->setTitle('托尔斯泰的格言');

//设置列表数组listItems其中一项,即列表的一个元素
$listTemplateItem = new ListTemplateItem();
$listTemplateItem->setToken('token');
$listTemplateItem->setImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
$listTemplateItem->setPlainPrimaryText('一级标题');  
$listTemplateItem->setPlainSecondaryText('二级标题'); 
$listTemplateItem->setPlainTertiaryText('三级标题');

//把listTemplateItem添加到模版listItems
$listTemplate->addItem($listTemplateItem);
//定义RenderTemplate指令
$directive = new RenderTemplate($listTemplate);
return [
    'directives' => [$directive],
    'outputSpeech' => '这是ListTemplate2模板',
];


use \Baidu\Duer\Botsdk\Directive\Display\RenderTemplate;
use \Baidu\Duer\Botsdk\Directive\Display\Template\BodyTemplate1;

$this->addEventListener('Display.ElementSelected', function($event){
    $token = $event['token'];
    $bodyTemplate = new BodyTemplate1();
    //设置模版token
    $bodyTemplate->setToken('token');
    //设置模版背景图片
    $bodyTemplate->setBackGroundImage('https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg');
    //设置模版标题
    $bodyTemplate->setTitle('托尔斯泰的格言');
    //设置模版plain类型的文本
    $bodyTemplate->setPlainTextContent('拖尔斯泰-理想的书籍是智慧的钥匙'); 
    //定义RenderTemplate指令
    $directive = new RenderTemplate($bodyTemplate);
    return [
        'directives' => [$directive],
        'outputSpeech' => '点击后展现',
    ];
});


use \Baidu\Duer\Botsdk\Card\TextCard;
$card = new TextCard('content');

//or
$card = new TextCard();
//设置content
$card->setContent('Content');
//设置链接
$card->setAnchor('http://www.baidu.com');
$card->setAnchor('http://www.baidu.com', 'showtext');
//设置cueWords
$card->addCueWords('hint1');
$card->addCueWords(['hint1', 'hint2']);

return [
    'card' => $card,
];


use \Baidu\Duer\Botsdk\Card\ListCard;
use \Baidu\Duer\Botsdk\Card\ListCardItem;

$card = new ListCard();
$item = new ListCardItem();
$item->setTitle('title')
    ->setContent('content')
    ->setUrl('http://www')
    ->setImage('http://www.png');

$card->addItem($item);
$card->addItem($item);

return [
    'card' => $card,
];


use \Baidu\Duer\Botsdk\Card\StandardCard;
$this->addEventListener('Screen.LinkClicked', function($event){
    $url = $event['url'];
    $token = $event['token'];

    $card = new StandardCard();
    $card->setTitle('title');
    $card->setContent('content');

    return [
        'card' => $card,
    ];
});


$card = new ImageCard();
$card->addItem('http://src.image', 'http://thumbnail.image');

use \Baidu\Duer\Botsdk\Directive\AudioPlayer\Play;

$directive = new Play('http://www.music', Play::REPLACE_ALL); 
return [
    'directives' => [$directive],
    'outputSpeech' => '正在为你播放歌曲',
];

use \Baidu\Duer\Botsdk\Directive\AudioPlayer\Play;
use \Baidu\Duer\Botsdk\Directive\AudioPlayer\PlayerInfo;
use \Baidu\Duer\Botsdk\Directive\AudioPlayer\Control\PlayPauseButton;
use \Baidu\Duer\Botsdk\Directive\AudioPlayer\Control\NextButoon;
use \Baidu\Duer\Botsdk\Directive\AudioPlayer\Control\PreviousButton;
//创建音频播放指令
$directive = new Play('http://www.music', Play::REPLACE_ALL);

//音频播放器的主界面
$playerInfo = new PlayerInfo();

//创建暂停按钮
$playpause = new PlayPauseButton();
$previous = new PreviousButton();
$controls = array(
    $playpause, 
    $previous
);

//设置PlayerInfo的Controls内容
$playerInfo->setControls($controls);

//也可以使用addControl,增加一个control
$playerInfo->addControl(new NextButoon());

$playerInfo->setTitle('周杰伦');
$playerInfo->setTitleSubtext1('七里香');

//设置Play指令的PlayerInfo
$directive->setPlayerInfo($playerInfo);
return [
    'directives' => [$directive],
    'outputSpeech' => '周杰伦,七里香',
];

use \Baidu\Duer\Botsdk\Directive\AudioPlayer\Stop;

$directive = new Stop(); 
return [
    'directives' => [$directive],
    'outputSpeech' => '已经停止播放',
];

use \Baidu\Duer\Botsdk\Directive\AudioPlayer\Play;

$this->addEventListener('AudioPlayer.PlaybackNearlyFinished', function($event){
    $token = $event['token'];
    $directive = new Play('http://www.audio', Play::ENQUEUE); 
    return [
        'directives' => [$directive],
    ];
});

use \Baidu\Duer\Botsdk\Directive\VideoPlayer\Play;

$directive = new Play('http://www.video', Play::REPLACE_ALL); 
return [
    'directives' => [$directive],
    'outputSpeech' => '正在为你播放视频',
];

use \Baidu\Duer\Botsdk\Directive\VideoPlayer\Stop;

$directive = new Stop(); 
return [
    'directives' => [$directive],
    'outputSpeech' => '已经停止播放',
];

use \Baidu\Duer\Botsdk\Directive\VideoPlayer\Play;

$this->addEventListener('VideoPlayer.PlaybackNearlyFinished', function($event){
    $token = $event['token'];
    $offsetInMilliseconds = $event['offsetInMilliseconds'];
    $directive = new Play('http://www.video', Play::ENQUEUE); 
    return [
        'directives' => [$directive],
    ];

});

$screenContext = $this->request->getScreenContext();

use \Baidu\Duer\Botsdk\Directive\Display\Hint;
use \Baidu\Duer\Botsdk\Card\TextCard;

$directive = new Hint(['hint1', 'hint2']);
return [
    'card' => new TextCard('测试Hint指令'),
    'directives' => [$directive],
];

$bot = new Bot();

header("Content-Type: application/json");
print $bot->run();


return [
    'outputSpeech' => '请问你要干啥呢',
    //或者ssml
    'outputSpeech' => '<speak>请问你要干啥呢</speak>',
];

return [
    'reprompt' => 'hello,请问你要干啥呢',
    //或者ssml
    'reprompt' => '<speak>hello,请问你要干啥呢</speak>',
];

$this->addLaunchHandler(function(){
    return [
        'outputSpeech' => '<speak>欢迎光临</speak>' 
    ];

});


$this->addSessionEndedHandler(function(){
    // clear status
    // 清空状态,结束会话。 
    return null; 
});


//提醒意图而且有提醒时间slot
$this->addIntentHandler('remind', function(){
    $remindTime = $this->getSlot('remind_time');
    if($remindTime) {
        return [/*设置闹钟指令*/];
    }

    //当前面条件不满足(没有提醒时间),会执行这个handler
    $this->nlu->ask('remind_time');
    $card = new TextCard('要几点的闹钟呢?');
    return [
        'card' => $card,
        'outputSpeech' => '要几点的闹钟呢?',
    ];
});

//监听events
$this->addEventListener('Alerts.SetAlertSucceeded', function($event){
    //do sth. eg. set alert status 
    $card = new TextCard('闹钟创建成功');
    return [
        'card' => $card
    ];
});

$this->addEventListener('AudioPlayer.PlaybackNearlyFinished', function($event){
    $offset = $event['offsetInMilliSeconds'];
    //todo sth,比如:返回一个播放enqueue
    //
    $directive = new Play('ENQUEUE'); 
    $directive->setUrl('http://wwww');
    return [
        'directives' => [$directive],
	];
});

//slot
getSlot('slot name');
setSlot('slot name', 'slot value');// 如果没有找到对应的slot,会自动新增一个slot

//session
getSessionAttribute('key');
setSessionAttribute('key', 'value');
//or
setSessionAttribute('key.key1', 'value');
getSessionAttribute('key.key1');

//清空session
clearSession();

$this->addDefaultEventListener(function($event){
    $this->waitAnswer();  //不结束回话,即shouldEndSession为false。
    $this->setExpectSpeech(false);  //端关闭麦克风,不继续监听
});

class YourIntercept extends \Baidu\Duer\Botsdk\Intercept{
    public function preprocess($bot) {
        //$bot: 你的bot实例化对象
    }

    public function postprocess($bot, $result) {
        //maybe format $result
        return $result;
    }
}


return [
    'nlu' => [
        'name' => 'personal_income_tax.inquiry',
        'slots' => [
            [
                'name' => 'monthlysalary',
                'value' => '121212',
            ],
            [
                'name' => 'compute_type',
                'value' => '个税',
            ],
        ]
    ],
    'session' => [],
];

//可以在构造函数中执行
$this->log = new Baidu\Duer\Botsdk\Log([
    //日志存储路径
    'path' => 'log/', 
    //日志打印最低输出级别
    'level' => Baidu\Duer\Botsdk\Log::NOTICE,
]);

//标记开始,search_t 是对应的字段名
$this->log->markStart('search_t');
$res = \Utils::curl(['url'=>$url, 'timeout'=>2000]);
//标记结束
$this->log->markEnd('search_t');

//记录这次请求的query
$this->log->setField('query', $this->request->getQuery());

//获取某个字段的值,比如,获取统计的时间
$this->log->getField('search_t');

//test fatal log
$this->log->fatal("this is a fatal log");

//$privateKey为私钥内容,0代表你的Bot在DBP平台debug环境,1或者其他整数代表online环境
$this->botMonitor->setEnvironmentInfo($privateKey, 0);
//环境信息配置完成后,你需要打开BotMonitor数据采集上报开关(默认是开启的,你可以根据自己需求打开或者关闭),true代表打开,false代表关闭
$this->botMonitor->setMonitorEnabled(true);
javascript
t extends Baidu\Duer\Botsdk\Bot{
    /**
     * $postData可以不传,由于DuerOS对bot是post请求,sdk默认自动获取
     */
    public function __construct($postData = []) {
       parent::__construct($postData); 

       // 开启校验请求参数签名
       // php 得支持open ssl扩展
       $this->certificate->enableVerifyRequestSign();
    }
}
json
use \Baidu\Duer\Botsdk\Card\StandardCard;
$card = new StandardCard();

$card->setTitle('title');
$card->setContent('content');
$card->setImage('http://www...');
$card->setAnchor('http://www.baidu.com');

return [
    'card' => $card,
];

shell
php -S 0.0.0.0:8000 index.php
javascript
//打车意图,但是没有提供目的地
$this->addIntentHandler('rent_car.book', function(){
    $endPoint = $this->getSlot('destination');
    if(!$this->endPoint) {
        //询问slot: destination
        $this->nlu->ask('destination');
    
        $card = new TextCard('打车去哪呢');
        return [
            'card' => $card
        ];
    }
});
javascript
$this->addIntentHandler('your intent name', function(){
    if(!$this->request->isDialogStateCompleted()) {
        // 如果使用了delegate 就不再需要使用setConfirmSlot/setConfirmIntent,否则返回的directive会被后set的覆盖。
        return $this->setDelegate();
    }

    //do sth else
});
javascript
$this->addIntentHandler('your intent name', function(){
    if($this->getSlot('money') > 10000000000) {
        $this->setConfirmSlot('money');
        return [
            'outputSpeech' => '你确认充话费:10000000000',
        ];
    }

    //do sth else
});
javascript
$this->addIntentHandler('your intent name', function(){
    $money = $this->getSlot('money');
    $phone = $this->getSlot('phone');
    if($money && $phone) {
        $this->setConfirmIntent();
        return [
            'outputSpeech' => "你确认充话费:$money,充值手机:$phone",
        ];
    }

    //do sth else
});
javascript
public function __construct($postData = []) {
    parent::__construct($postData);
    $this->addIntercept(new Baidu\Duer\Botsdk\Plugins\LoginIntercept());
    //...
}