技術指南 | 用Python 支付接收比特幣中文教程(二)
在 上一篇教程中, 我們建立了自動回覆訊息的機器人,當用戶傳送訊息"Hello,World!"時,機器人會自動回覆同一條訊息!
第二課: 機器人接受比特幣並立即退還使用者
按本篇教程後學習後完成後,你的機器人將會接受使用者傳送過來的加密貨幣,然後立即轉回使用者。 完整程式碼如下:
from mixin_ws_api import MIXIN_WS_API from mixin_api import MIXIN_API import mixin_config import json import time from io import BytesIO import base64 import gzip try: import thread except ImportError: import _thread as thread def on_message(ws, message): inbuffer = BytesIO(message) f = gzip.GzipFile(mode="rb", fileobj=inbuffer) rdata_injson = f.read() rdata_obj = json.loads(rdata_injson) print("-------json object begin---------") print(rdata_obj) print("-------json object end---------") action = rdata_obj["action"] if rdata_obj["data"] is not None: print("data in message:",rdata_obj["data"]) if rdata_obj["data"] is not None and rdata_obj["data"]["category"] is not None: print(rdata_obj["data"]["category"]) if action == "CREATE_MESSAGE": data = rdata_obj["data"] msgid = data["message_id"] typeindata = data["type"] categoryindata = data["category"] userId = data["user_id"] conversationId = data["conversation_id"] dataindata = data["data"] created_at = data["created_at"] updated_at = data["updated_at"] realData = base64.b64decode(dataindata) MIXIN_WS_API.replayMessage(ws, msgid) print('userId', userId) print("created_at",created_at) if categoryindata == "PLAIN_TEXT": realData = realData.decode('utf-8') print("dataindata",realData) MIXIN_WS_API.sendUserText(ws, conversationId, userId, realData) elif categoryindata == "SYSTEM_ACCOUNT_SNAPSHOT": rdJs = json.loads(realData) if ( float(rdJs["amount"]) > 0 ): mixin_api.transferTo(userId, rdJs["asset_id"], rdJs["amount"], "") if __name__ == "__main__": mixin_api = MIXIN_API(mixin_config) mixin_ws = MIXIN_WS_API(on_message=on_message) mixin_ws.run() 複製程式碼
Hello Bitcoin!
在專案目錄下,執行 python app.pycd mixin_labs-python-bot source ./bin/activate (mixin_labs-python-bot) wenewzha:mixin_labs-python-bot wenewzhang$ python app.py ws open -------json object begin--------- {'id': 'fd6ce766-331a-11e9-92a9-20c9d08850cd', 'action': 'LIST_PENDING_MESSAGES'} -------json object end--------- 複製程式碼
開發者可以通過訊息面板,給機器人轉比特幣,當機器人收到比特幣後,馬上返還給使用者!
<figure> <figcaption></figcaption></figure>
事實上,使用者可以傳送任意的幣種給機器人,它都能馬上返還!
<figure> <figcaption></figcaption></figure>
原始碼解釋
elif categoryindata == "SYSTEM_ACCOUNT_SNAPSHOT": rdJs = json.loads(realData) if ( float(rdJs["amount"]) > 0 ): mixin_api.transferTo(userId, rdJs["asset_id"], rdJs["amount"], "") 複製程式碼
如果機器人收到幣,rdJs["amount"] 大於零;如果機器人支付幣給使用者,接收到的訊息是一樣的,唯一不同的是,rdJs["amount"]是一個負數. 最後一步,呼叫SDK的 mixin_api.transferTo 將幣返還使用者!
高階用法
coming soon!