博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 比特币 教程 之一:创建机器人
阅读量:6290 次
发布时间:2019-06-22

本文共 7247 字,大约阅读时间需要 24 分钟。

Cover

是一个免费极速的点对点加密数字货币交易系统.
在本章中,你可以按教程在Mixin Messenger中创建一个bot来接收用户消息, 学到如何给机器人转比特币 或者 让机器人给你转比特币.

课程简介

创建一个接受消息的机器人

通过本教程,你将学会如何用Python创建一个机器人APP,让它能接受消息.

Python 3 安装:

本教程基于Python 3.7.2, 所以你需要安装Python 3.7.2 或 以上的版本.

on macOS

brew upgradebrew install python@3

on Ubuntu, 从第三方的APT源中安装.

sudo apt updatesudo apt install software-properties-commonsudo add-apt-repository ppa:deadsnakes/ppa

当出现下面的提示时,按"回车"继续.

Press [ENTER] to continue or Ctrl-c to cancel adding it.

重新更新一次apt源, 再安装python3.7, python3.7-venv

sudo apt updatesudo apt install python3.7 python3.7-venvsudo ln -s /usr/bin/python3.7 /usr/bin/python3

检查安装是否成功了,需要检查python3与python3-venv, 正确的提示如下:

$ python3 -VPython 3.7.2
root@n2:~ python3 -m venv -husage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]            [--upgrade] [--without-pip] [--prompt PROMPT]            ENV_DIR [ENV_DIR ...]Creates virtual Python environments in one or more target directories.positional arguments:  ENV_DIR               A directory to create the environment in.optional arguments:  -h, --help            show this help message and exit  --system-site-packages                        Give the virtual environment access to the system                        site-packages dir.  --symlinks            Try to use symlinks rather than copies, when symlinks                        are not the default for the platform.  --copies              Try to use copies rather than symlinks, even when                        symlinks are the default for the platform.  --clear               Delete the contents of the environment directory if it                        already exists, before environment creation.  --upgrade             Upgrade the environment directory to use this version                        of Python, assuming Python has been upgraded in-place.  --without-pip         Skips installing or upgrading pip in the virtual                        environment (pip is bootstrapped by default)  --prompt PROMPT       Provides an alternative prompt prefix for this                        environment.Once an environment has been created, you may wish to activate it, e.g. bysourcing an activate script in its bin directory

创建 mixin_labs-python-bot 项目

你首先需要创建项目目录,初始化"虚拟环境",然后安装需要的软件包.

mkdir mixin_labs-python-botcd mixin_labs-python-botpython3 -m venv ./

python3 -m venv 指令完成之后, 项目目录如下:

wenewzha:mixin_labs-python-bot wenewzhang$ lsbin        include        lib        pyvenv.cfg

当"虚拟环境"创建成功后,需要激活它, 通过执行bin目录下相应的activate文件完成.

wenewzha:mixin_labs-python-bot wenewzhang$ source ./bin/activate(mixin_labs-python-bot) wenewzha:mixin_labs-python-bot wenewzhang$

成功激活后,可以直接执行python或pip了,这时,不再需要输入他们的完整路径了.

在"虚拟环境"里安装必需的包

创建一个必需包的list

requirements.txt
cryptography==2.4.2pycparser==2.19pycryptodome==3.7.2PyJWT==1.7.1python-dateutil==2.7.5PyYAML==3.13requests==2.21.0websocket-client==0.54.0

通过pip升级pip包本身, 并安装必需包.

pip install --upgrade pippip install -r requirements.txt

下载 Mixin Network的python 3的API

wget https://github.com/includeleec/mixin-python3-sdk/raw/master/mixin_ws_api.pywget https://github.com/includeleec/mixin-python3-sdk/raw/master/mixin_api.pywget https://github.com/includeleec/mixin-python3-sdk/raw/master/mixin_config.py

你好,世界!

创建第一个机器人APP

按,到mixin.one创建一个APP[tutorial].

生成相应的参数

并且记下来

它们将用于mixin_config.py中.

mixin_network-keys

在项目目录下,创建mixin_config.py,将生成的参数,替换成你的!

mixin_config.py
client_id= 'ed882a39-0b0c-4413-bbd9-221cdeee56bf'client_secret = '8d7ec7b9c8261b6c7bd6309210496ca4b72bce9efc7e49be14a428ce49ff7202'pay_pin = '599509'pay_session_id = 'bd53b6a4-e79a-49e5-ad04-36da518354f6'pin_token = "nVREh0/Ys9vzNFCQT2+PKcDN2OYAUSH8CidwHqDQLOCvokE7o6wtvLypjW9iks/RsnBM6N4SPF/P3bBW254YHGuDZXhitDEWOGkXs7v8BxMQxf+9454qTkMSpR9xbjAzgMXnSyHrNVoBtsc/Y+NvemB3VxPfsCOFHasiMqAa5DU="private_key = """-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQCnaoO1SdPxggEpAIUdM/8Ll4FOqlXK7vwURHr4FFi6hnQ1I79gpZSlJdzjr24WcIuNi6kVdXVIpyzZJGXS2I72dpGs5h1jKxL8AWIUVL2axZXqTJNic4wj6GJ4gDRP2U9I9gae+S/frM6KP8TioV0OcbmrlfrwI0OElLH3363y1wIDAQABAoGAduaGLi4F8cMkMculvqzcGY57jrQZBGyg6YANWb2Rmr+9LrR5yhkvLe9rJuXEKPm7k0a6SnxGVNguWPWpv4qAVVGAJ0eb8ETXTRO20HlKmcbxfFdDtHBDV3QufNa1h3mNEsqWDNCDdAm7p/EZwfG2F9+nmeXLfip7R1I72qbK0wkCQQDiJR6NEGVwbj8HK8kRpzY1D9lPqp1ZMrma5AFYGZIb5voTxLjRpYdxQJHi7CCdE1zgqJOXvA3jj/iof7bMIJY7AkEAvYSSC5H+fUKAjyjeCTGJBBKoPDsq+aALAYLWf77sGXE9BBmhhY0liwmbj8X6/qZtQ0yEzdT/OSdiYL86CcrgFQJBALz/sMzMSzrvqJVhrqWmTdOC72d5fA+0KRKeQ9FRbZ8MJyymWKA96zhncoVoOsmMCS9pNBC4BhONm4+XTTrEcUkCQQCoDWB8Bg/G/yuExtZtDJHVHL41+rmW9UYNJvoR+TjfLrzOX/QMuyapbfGVwhdZrDaDUN0KsG9JPRVNeQR8HnwpAkACrr9cNp1H1bytHG9a6L+5cVHkRhqqEYWVO41MhgZF5bIKx5OXCJB2VwY7fjFet2KxTHGfEZt/khjFNZzVX7lN-----END RSA PRIVATE KEY-----"""

需要替换的参数包括: client_id, client_secret, pay_pin, pin_token, pay_session_id, private key.

创建 app-mini.py 文件, 内容如下:

app-mini.py
from mixin_ws_api import MIXIN_WS_APIfrom mixin_api import MIXIN_APIimport mixin_configimport jsonimport timefrom io import BytesIOimport base64import gziptry:    import threadexcept ImportError:    import _thread as threaddef 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"]        realData = base64.b64decode(dataindata)        MIXIN_WS_API.replayMessage(ws, msgid)        if 'error' in rdata_obj:            return        if categoryindata == "PLAIN_TEXT":            realData = realData.decode('utf-8')            print("dataindata",realData)            MIXIN_WS_API.sendUserText(ws, conversationId, userId, realData)if __name__ == "__main__":    mixin_api = MIXIN_API(mixin_config)    mixin_ws = MIXIN_WS_API(on_message=on_message)    mixin_ws.run()

运行 app-mini.py, 记得要先激活“虚拟环境”哦!

(mixin_labs-python-bot) wenewzha:mixin_labs-python-bot wenewzhang$ python app-mini.py...

如果一切正常,将会有如下提示:

(mixin_labs-python-bot) wenewzha:mixin_labs-python-bot wenewzhang$ python app-mini.pyws open-------json object begin---------{'id': '1c798948-30eb-11e9-a20e-20c9d08850cd', 'action': 'LIST_PENDING_MESSAGES'}-------json object end---------

在手机安装 ,增加机器人为好友,(比如这个机器人是7000101639) 然后发送消息给它,效果如下!

echo message

源代码解释

WebSocket是建立在TCP基础之上的全双工通讯方式,我们需要建立一个loop循环来维持通迅。

if __name__ == "__main__":    mixin_api = MIXIN_API(mixin_config)    mixin_ws = MIXIN_WS_API(on_message=on_message)    mixin_ws.run()

每接收到一个消息,需要按消息编号(message_id)给服务器回复一个"已读"的消息,避免服务器在机器人重新登入后,再次发送处理过的消息!

MIXIN_WS_API.replayMessage(ws, msgid)

机器人程序完整回复用户的信息

if categoryindata == "PLAIN_TEXT":    realData = realData.decode('utf-8')    print("dataindata",realData)    MIXIN_WS_API.sendUserText(ws, conversationId, userId, realData)

Mixin Messenger支持的消息类型很多,具体可到下面链接查看: .

完成

现在你的机器人APP运行起来了,开始玩吧。

完整的代码

转载地址:http://ahkta.baihongyu.com/

你可能感兴趣的文章
sqoop数据迁移(基于Hadoop和关系数据库服务器之间传送数据)
查看>>
腾讯云下安装 nodejs + 实现 Nginx 反向代理
查看>>
Javascript 中的 Array 操作
查看>>
java中包容易出现的错误及权限问题
查看>>
AngularJS之初级Route【一】(六)
查看>>
服务器硬件问题整理的一点总结
查看>>
SAP S/4HANA Cloud: Revolutionizing the Next Generation of Cloud ERP
查看>>
Mellanox公司计划利用系统芯片提升存储产品速度
查看>>
白帽子守护网络安全,高薪酬成大学生就业首选!
查看>>
ARM想将芯片装进人类大脑 降低能耗是一大挑战
查看>>
Oracle数据库的备份方法
查看>>
Selenium 自动登录考勤系统
查看>>
关于如何以编程的方式执行TestNG
查看>>
智能照明造福千家万户 家居智能不再是梦
查看>>
物联网如何跳出“看起来很美”?
查看>>
浅谈MySQL 数据库性能优化
查看>>
《UNIX/Linux 系统管理技术手册(第四版)》——1.10 其他的权威文档
查看>>
灵动空间 创享生活
查看>>
《UNIX网络编程 卷1:套接字联网API(第3版)》——8.6 UDP回射客户程序:dg_cli函数...
查看>>
不要将时间浪费到编写完美代码上
查看>>