成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

基于Mixin Network的PHP比特幣開發(fā)教程 之一:創(chuàng)建機器人

Barrior / 2678人閱讀

摘要:英文原文是一個免費的極速的端對端加密數(shù)字貨幣交易系統(tǒng)在本章中,你可以按教程在中創(chuàng)建一個來接收用戶消息學(xué)到如何給機器人轉(zhuǎn)比特幣或者讓機器人給你轉(zhuǎn)比特幣資源匯總課程簡介創(chuàng)建一個接受消息的機器人機器人接受比特幣并立即退還用戶如何通過創(chuàng)建新帳號創(chuàng)建

英文原文

Mixin Network 是一個免費的 極速的端對端加密數(shù)字貨幣交易系統(tǒng).
在本章中,你可以按教程在Mixin Messenger中創(chuàng)建一個bot來接收用戶消息, 學(xué)到如何給機器人轉(zhuǎn)比特幣 或者 讓機器人給你轉(zhuǎn)比特幣.

Mixin network 資源匯總

課程簡介

創(chuàng)建一個接受消息的機器人

機器人接受比特幣并立即退還用戶

如何通過Mixin Network API創(chuàng)建新帳號

創(chuàng)建一個接受消息的機器人

通過本教程,你將學(xué)會如何用PHP創(chuàng)建一個機器人APP,讓它能接受消息.

PHP 環(huán)境安裝:

本教程的程序基于PHP 7開發(fā),所以你需要先安裝PHP7.2/PHP7.3與composer, 其中,composer是PHP的包管理系統(tǒng)!

on macOS
brew update
brew install [email protected]
php -r "copy("https://getcomposer.org/installer", "composer-setup.php");"
php -r "if (hash_file("sha384", "composer-setup.php") === "48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5") { echo "Installer verified"; } else { echo "Installer corrupt"; unlink("composer-setup.php"); } echo PHP_EOL;"
//將PHP安裝到/usr/local/opt/[email protected]/bin 目錄,并取一個簡單的各字:composer
php composer-setup.php --install-dir=/usr/local/opt/[email protected]/bin --filename=composer
php -r "unlink("composer-setup.php");"

如果之前你安裝過php 7.1 或者更舊的php版本,執(zhí)行brew unlink [email protected]刪除這些鏈接,然后再執(zhí)行brew link [email protected]將php 7.3鏈接到php.

wenewzha:mixin_labs-php-bot wenewzhang$ brew unlink [email protected]
Unlinking /usr/local/Cellar/php/7.1.23... 24 symlinks removed
wenewzha:mixin_labs-php-bot wenewzhang$ brew link [email protected]
Warning: [email protected] is keg-only and must be linked with --force

If you need to have this software first in your PATH instead consider running:
  echo "export PATH="/usr/local/opt/[email protected]/bin:$PATH"" >> ~/.bash_profile
  echo "export PATH="/usr/local/opt/[email protected]/sbin:$PATH"" >> ~/.bash_profile

之后,根據(jù)你的系統(tǒng)實際情況,看看php -v能不能執(zhí)行成功,如果不行,將默認(rèn)的PATH設(shè)置并保存到.bash_profile.

echo "export PATH="/usr/local/opt/[email protected]/bin:$PATH"" >> ~/.bash_profile
echo "export PATH="/usr/local/opt/[email protected]/sbin:$PATH"" >> ~/.bash_profile
source ~/.bash_profile
on Ubuntu
apt update
apt upgrade

//install php 7.2
apt-get install software-properties-common python-software-properties
add-apt-repository -y ppa:ondrej/php
apt-get update
apt-get install php7.2 php7.2-cli php7.2-common
//install composer
php -r "copy("https://getcomposer.org/installer", "composer-setup.php");"
php -r "if (hash_file("sha384", "composer-setup.php") === "48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5") { echo "Installer verified"; } else { echo "Installer corrupt"; unlink("composer-setup.php"); } echo PHP_EOL;"
//將PHP安裝到/usr/local/opt/[email protected]/bin 目錄,并取一個簡單的各字:composer
php composer-setup.php --install-dir=/usr/local/bin --filename=composer
php -r "unlink("composer-setup.php");"

最新的Composer在這兒Composer
請確保PHP與composer安裝在$PATH包含的目錄之內(nèi),直接運行php -vcomposer -V 就可以檢查出來,如果提示如下,表示安裝正確!

wenewzha:minecraft wenewzhang$ php -v
PHP 7.2.13 (cli) (built: Dec  7 2018 10:41:23) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.13, Copyright (c) 1999-2018, by Zend Technologies
wenewzha:minecraft wenewzhang$ composer -V
Composer version 1.8.0 2018-12-03 10:31:16

如果提示command not found,表示bash沒有在$PATH下找到php,請重復(fù)以上的安裝步驟!

wenewzha:mixin_network-nodejs-bot2 wenewzhang$ php -v
-bash: php: command not found
創(chuàng)建你的項目

到你的工作文檔中,創(chuàng)建一個目錄,并取一個名字,比如:mixin_labs-php-bot

mkdir mixin_labs-php-bot
cd mixin_labs-php-bot

轉(zhuǎn)到新創(chuàng)建的項目目錄下, 執(zhí)行 composer init, 依提示完成 composer.json的創(chuàng)建,

root@iZj6cbmqen2lqp7l48nfgkZ:~/mixin_labs-php-bot# composer init
 Welcome to the Composer config generator
This command will guide you through creating your composer.json config.
Package name (/) [user/mixin_labs-php-bot]:
Description []: PHP 7 bot for Mixin Messenger
Author [, n to skip]: JimmyZhang 
Minimum Stability []:
Package Type (e.g. library, project, metapackage, composer-plugin) []:
License []:
Define your dependencies.
Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
{
   "name": "user/mixin_labs-php-bot",
   "description": "PHP 7 bot for Mixin Messenger",
   "authors": [
       {
           "name": "JimmyZhang",
           "email": "[email protected]"
       }
   ],
   "require": {}
}
Do you confirm generation [yes]? yes

本教程引用了 mixin-sdk-php 與 Ratchet pawl, mixin-sdk-php 是一個Mixin Network PHP SDK , Ratchet pawl 是一個WebSocket客戶端.
打開composer.json, 在"require"增加兩行引用:

"require": {
    "exinone/mixin-sdk-php": "^1.1",
    "ratchet/pawl": "^0.3.3",
},

保存composer.json后,執(zhí)行 composer install 來下載:

composer install

下載完成后,目錄下會出現(xiàn)一個vendor的子目錄。

root@iZj6cbmqen2lqp7l48nfgkZ:~/mixin_labs-php-bot# ls
composer.json  composer.lock  vendor

如果你是git克隆的源代碼,直接執(zhí)行 composer install 來下載依賴包。

創(chuàng)建第一個機器人APP

按下面的提示,到mixin.one創(chuàng)建一個APPtutorial.

生成相應(yīng)的參數(shù)

記下這些生成的參數(shù)
它們將用于config.php中.


在項目目錄下,創(chuàng)建config.php,將生成的參數(shù),替換成你的!

config.php
return [
    "mixin_id"      => "7000101716",
    "client_id"     => "a1ce2967-a534-417d-bf12-c86571e4eefa",
    "client_secret" => "7339866727d24eeec1c4ebb6c634fd25a7b9057ee6d5939cca9b6b9fc15f4d1f",
    "pin"           => "512772",
    "pin_token"     => "abRdNq6soRALRG434IgR7WS/qP7LOcpfviqSfWfABdIKyZGLnWXFMrVCHpChIkBRGRAcsUguni0OoNsShddPVL3qoD5fxbF5dRUiRv14urH1Pmdl6zIZdCH159QMr5wLmmSHSGu2AihNkUHUo3bAJsrvOW0nke5y6R5YE/pNNfo=",
    "session_id"    => "51faabbf-48ff-4df2-898d-e9b318afae35",
    "private_key"   => <<

需要替換的參數(shù)包括: mixin_id, client_id, client_secret, and the pin, pin token, session_id, private key.

經(jīng)典的Hello world

在項目目錄下創(chuàng)建一個app.php文件,將下面的代碼拷進去:

 15
]);
$connector = new RatchetClientConnector($loop,$reactConnector);
class callTraitClass {
  use MixinSDKTrait;
  public $config;
  public function __construct()
  {
      $config = require(__DIR__."/config.php");
      $this->config        = $config;
  }
}
$callTrait = new callTraitClass();
$Token = $callTrait->getToken("GET", "/", "");
// $connector("ws://127.0.0.1:9000", ["protocol" => "Mixin-Blaze-1"], ["Origin" => "http://localhost",
$connector("wss://blaze.mixin.one", ["protocol" => "Mixin-Blaze-1"],[
                                    "Authorization" => "Bearer ".$Token
                                      ])
->then(function(RatchetClientWebSocket $conn) {
    $conn->on("message", function(RatchetRFC6455MessagingMessageInterface $msg) use ($conn) {
        $jsMsg = json_decode(gzdecode($msg));
        print_r($jsMsg);
        if ($jsMsg->action === "CREATE_MESSAGE" and property_exists($jsMsg,"data")) {
          echo "
Need reply server a receipt!
";
          $RspMsg = generateReceipt($jsMsg->data->message_id);
          $msg = new Frame(gzencode(json_encode($RspMsg)),true,Frame::OP_BINARY);
          $conn->send($msg);

          if ($jsMsg->data->category === "PLAIN_TEXT") {
                $msgData = sendPlainText($jsMsg->data->conversation_id,
                                          base64_decode($jsMsg->data->data));
                $msg = new Frame(gzencode(json_encode($msgData)),true,Frame::OP_BINARY);
                $conn->send($msg);
          } //end of PLAIN_TEXT
        } //end of CREATE_MESSAGE

    });
    $conn->on("close", function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})
";
    });
/*                   start listen for the incoming message          */
    $message = [
        "id"     => Uuid::uuid4()->toString(),
        "action" => "LIST_PENDING_MESSAGES",
    ];
    print_r(json_encode($message));
    $msg = new Frame(gzencode(json_encode($message)),true,Frame::OP_BINARY);
    $conn->send($msg);
    // $conn->send(gzencode($msg,1,FORCE_DEFLATE));
}, function(Exception $e) use ($loop) {
    echo "Could not connect: {$e->getMessage()}
";
    $loop->stop();
});

$loop->run();


function sendPlainText($conversation_id,$msgContent):Array {

   $msgParams = [
     "conversation_id" => $conversation_id,
     "category"        => "PLAIN_TEXT",
     "status"          => "SENT",
     "message_id"      => Uuid::uuid4()->toString(),
     "data"            => base64_encode($msgContent),//base64_encode("hello!"),
   ];
   $msgPayButton = [
     "id"     =>  Uuid::uuid4()->toString(),
     "action" =>  "CREATE_MESSAGE",
     "params" =>   $msgParams,
   ];
   return $msgPayButton;
}

function generateReceipt($msgID):Array {
  $IncomingMsg = ["message_id" => $msgID, "status" => "READ"];
  $RspMsg = ["id" => Uuid::uuid4()->toString(), "action" => "ACKNOWLEDGE_MESSAGE_RECEIPT",
              "params" => $IncomingMsg];
  return $RspMsg;
}

保存,并在終端里執(zhí)行app.php

php app.php

如果一切正常,提示如下:

wenewzha:mixin_labs-php-bot wenewzhang$ php app.php
a1ce2967-a534-417d-bf12-c86571e4eefa{"id":"4454b6c5-4a89-440c-bd22-7a79cf4954ca","action":"LIST_PENDING_MESSAGES"}stdClass Object
(
    [id] => 4454b6c5-4a89-440c-bd22-7a79cf4954ca
    [action] => LIST_PENDING_MESSAGES
)

在手機安裝 Mixin Messenger,增加機器人為好友,(比如這個機器人是7000101639) 然后發(fā)送消息給它,效果如下!

源代碼解釋

WebSocket是建立在TCP基礎(chǔ)之上的全雙工通訊方式,我們需要建立一個loop循環(huán)來維持通迅。

$loop = ReactEventLoopFactory::create();
$reactConnector = new ReactSocketConnector($loop, [
    "timeout" => 15
]);
$connector = new RatchetClientConnector($loop,$reactConnector);

機器人APP通過Mixin Messenger服務(wù)器來接收用戶發(fā)過來的消息,連接服務(wù)器,需要Token來驗證用戶的身份,
詳細資料可參考如下鏈接:
Token認(rèn)證, 接收服務(wù)器消息

mixin-sdk-php 實現(xiàn)了令牌Token的生成(getToken), 調(diào)用代碼如下:

class callTraitClass {
  use MixinSDKTrait;
  public $config;
  public function __construct()
  {
      $config = require(__DIR__."/config.php");
      $this->config        = $config;
  }
}
$callTrait = new callTraitClass();
$Token = $callTrait->getToken("GET", "/", "");

連接到服務(wù)器,注意協(xié)議類型與Token:

$connector("wss://blaze.mixin.one", ["protocol" => "Mixin-Blaze-1"],[
                                    "Authorization" => "Bearer ".$Token
                                      ])

向服務(wù)器發(fā)送"LIST_PENDING_MESSAGES",這樣服務(wù)器才會將收到的消息發(fā)送給機器人APP.

/*                   start listen for the incoming message          */
    $message = [
        "id"     => Uuid::uuid4()->toString(),
        "action" => "LIST_PENDING_MESSAGES",
    ];
    print_r(json_encode($message));
    $msg = new Frame(gzencode(json_encode($message)),true,Frame::OP_BINARY);
    $conn->send($msg);

增加偵聽 onMessage 接收并分析消息:

->then(function(RatchetClientWebSocket $conn) {
    $conn->on("message", function(RatchetRFC6455MessagingMessageInterface $msg) use ($conn) {
        $jsMsg = json_decode(gzdecode($msg));
        print_r($jsMsg);
        if ($jsMsg->action === "CREATE_MESSAGE" and property_exists($jsMsg,"data")) {
          echo "
Need reply server a receipt!
";
          $RspMsg = generateReceipt($jsMsg->data->message_id);
          $msg = new Frame(gzencode(json_encode($RspMsg)),true,Frame::OP_BINARY);
          $conn->send($msg);

          if ($jsMsg->data->category === "PLAIN_TEXT") {
                $msgData = sendPlainText($jsMsg->data->conversation_id,
                                          base64_decode($jsMsg->data->data));
                $msg = new Frame(gzencode(json_encode($msgData)),true,Frame::OP_BINARY);
                $conn->send($msg);
          } //end of PLAIN_TEXT
        } //end of CREATE_MESSAGE

    });
    $conn->on("close", function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})
";
    });                                      

Mixin Messenger支持的消息類型很多,具體可到下面鏈接查看: WebSocket消息類型.

每接收到一個消息,需要按消息編號(message_id)給服務(wù)器回復(fù)一個"已讀"的消息,避免服務(wù)器在機器人重新登入后,再次發(fā)送處理過的消息!

echo "
Need reply server a receipt!
";
$RspMsg = generateReceipt($jsMsg->data->message_id);
$msg = new Frame(gzencode(json_encode($RspMsg)),true,Frame::OP_BINARY);
$conn->send($msg);

function generateReceipt($msgID):Array {
  $IncomingMsg = ["message_id" => $msgID, "status" => "READ"];
  $RspMsg = ["id" => Uuid::uuid4()->toString(), "action" => "ACKNOWLEDGE_MESSAGE_RECEIPT",
              "params" => $IncomingMsg];
  return $RspMsg;
}
完成

現(xiàn)在你的機器人APP運行起來了,你打算如何改造你的機器人呢?

完整的代碼在這兒

下一課機器人接收與處理加密貨幣

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/24575.html

相關(guān)文章

  • 基于Mixin NetworkPHP比特開發(fā)教程 之一創(chuàng)建器人

    摘要:英文原文是一個免費的極速的端對端加密數(shù)字貨幣交易系統(tǒng)在本章中,你可以按教程在中創(chuàng)建一個來接收用戶消息學(xué)到如何給機器人轉(zhuǎn)比特幣或者讓機器人給你轉(zhuǎn)比特幣資源匯總課程簡介創(chuàng)建一個接受消息的機器人機器人接受比特幣并立即退還用戶如何通過創(chuàng)建新帳號創(chuàng)建 英文原文 Mixin Network 是一個免費的 極速的端對端加密數(shù)字貨幣交易系統(tǒng).在本章中,你可以按教程在Mixin Messenger中創(chuàng)建...

    Gemini 評論0 收藏0
  • 基于Mixin NetworkPHP比特開發(fā)教程: 器人接受比特并立即退還用戶

    摘要:如果機器人收到幣,大于零如果機器人支付幣給用戶,接收到的消息是一樣的,唯一不同的是是一個負(fù)數(shù)最后一步,調(diào)用將幣還給用戶完整的代碼在這兒 showImg(https://segmentfault.com/img/remote/1460000018419614?w=1200&h=659); 在 上一篇教程中, 我們創(chuàng)建了自動回復(fù)消息的機器人,當(dāng)用戶發(fā)送消息Hello,World!時,機器人...

    import. 評論0 收藏0
  • 基于Mixin NetworkPHP比特開發(fā)教程: 器人接受比特并立即退還用戶

    摘要:如果機器人收到幣,大于零如果機器人支付幣給用戶,接收到的消息是一樣的,唯一不同的是是一個負(fù)數(shù)最后一步,調(diào)用將幣還給用戶完整的代碼在這兒 showImg(https://segmentfault.com/img/remote/1460000018419614?w=1200&h=659); 在 上一篇教程中, 我們創(chuàng)建了自動回復(fù)消息的機器人,當(dāng)用戶發(fā)送消息Hello,World!時,機器人...

    winterdawn 評論0 收藏0
  • 基于Mixin NetworkPHP比特開發(fā)教程: 創(chuàng)建比特錢包

    摘要:我們已經(jīng)創(chuàng)建過一個回復(fù)消息的機器人和一個能自動支付比特幣的機器人通過本教程的學(xué)習(xí),你可以學(xué)到如下內(nèi)容如何創(chuàng)建一個比特幣錢包如何讀取比特幣錢包的余額如何支付比特幣并即時確認(rèn)如何將的比特幣提現(xiàn)到你的冷錢包或第三方交易所前期準(zhǔn)備你要有一個賬戶。 showImg(https://github.com/wenewzhang/mixin_labs-php-bot/raw/master/Bitcoi...

    DangoSky 評論0 收藏0
  • 基于Mixin NetworkPHP比特開發(fā)教程: 創(chuàng)建比特錢包

    摘要:我們已經(jīng)創(chuàng)建過一個回復(fù)消息的機器人和一個能自動支付比特幣的機器人通過本教程的學(xué)習(xí),你可以學(xué)到如下內(nèi)容如何創(chuàng)建一個比特幣錢包如何讀取比特幣錢包的余額如何支付比特幣并即時確認(rèn)如何將的比特幣提現(xiàn)到你的冷錢包或第三方交易所前期準(zhǔn)備你要有一個賬戶。 showImg(https://github.com/wenewzhang/mixin_labs-php-bot/raw/master/Bitcoi...

    kycool 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<