-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhome_of_cnb_robot.py
307 lines (260 loc) · 14 KB
/
home_of_cnb_robot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python
#coding: utf-8
import websocket
import requests
import json
import ssl
from mixin_api import MIXIN_API
import uuid
import zlib
import gzip
from cStringIO import StringIO
import base64
import mixin_config
import hashlib
import mixin_asset_list
import random
import datetime
import md5
try:
import thread
except ImportError:
import _thread as thread
import time
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from database_type import *
engine = create_engine('sqlite:///sqlalchemy_home_of_cnb.db')
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
# A DBSession() instance establishes all conversations with the database
# and represents a "staging zone" for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()
mixin_api_robot = MIXIN_API()
mixin_api_robot.appid = mixin_config.mixin_client_id
mixin_api_robot.secret = mixin_config.mixin_client_secret
mixin_api_robot.sessionid = mixin_config.mixin_pay_sessionid
mixin_api_robot.private_key = mixin_config.private_key
mixin_api_robot.asset_pin = mixin_config.mixin_pay_pin
mixin_api_robot.pin_token = mixin_config.mixin_pin_token
freeBonusTimeTable = {}
def writeMessage(websocketInstance, action, params):
Message = {"id":str(uuid.uuid1()), "action":action, "params":params}
Message_instring = json.dumps(Message)
fgz = StringIO()
gzip_obj = gzip.GzipFile(mode='wb', fileobj=fgz)
gzip_obj.write(Message_instring)
gzip_obj.close()
websocketInstance.send(fgz.getvalue(), opcode=websocket.ABNF.OPCODE_BINARY)
def sendUserAppButton(websocketInstance, in_conversation_id, to_user_id, realLink, text4Link, colorOfLink = "#d53120"):
btn = '[{"label":"' + text4Link + '","action":"' + realLink + '","color":"' + colorOfLink + '"}]'
params = {"conversation_id": in_conversation_id,"recipient_id":to_user_id,"message_id":str(uuid.uuid4()),"category":"APP_BUTTON_GROUP","data":base64.b64encode(btn)}
return writeMessage(websocketInstance, "CREATE_MESSAGE",params)
def sendUserContactCard(websocketInstance, in_conversation_id, to_user_id, to_share_userid):
btnJson = json.dumps({"user_id":to_share_userid})
params = {"conversation_id": in_conversation_id,"recipient_id":to_user_id,"message_id":str(uuid.uuid4()),"category":"PLAIN_CONTACT","data":base64.b64encode(btnJson)}
return writeMessage(websocketInstance, "CREATE_MESSAGE",params)
def sendUserText(websocketInstance, in_conversation_id, to_user_id, textContent):
params = {"conversation_id": in_conversation_id,"recipient_id":to_user_id ,"message_id":str(uuid.uuid4()),"category":"PLAIN_TEXT","data":base64.b64encode(textContent)}
return writeMessage(websocketInstance, "CREATE_MESSAGE",params)
def sendGroupText(websocketInstance, in_conversation_id, textContent):
params = {"conversation_id": in_conversation_id,"message_id":str(uuid.uuid4()),"category":"PLAIN_TEXT","data":base64.b64encode(textContent)}
return writeMessage(websocketInstance, "CREATE_MESSAGE",params)
def sendGroupPay(webSocketInstance, in_conversation_id, inAssetName, inAssetID, inPayAmount, linkColor = "#0CAAF5"):
payLink = "https://mixin.one/pay?recipient=" + mixin_config.mixin_client_id + "&asset=" + inAssetID + "&amount=" + str(inPayAmount) + '&trace=' + str(uuid.uuid1()) + '&memo=PRS2CNB'
btn = '[{"label":"' + inAssetName + '","action":"' + payLink + '","color":"' + linkColor + '"}]'
gameEntranceParams = {"conversation_id": in_conversation_id,"message_id":str(uuid.uuid4()),"category":"APP_BUTTON_GROUP","data":base64.b64encode(btn)}
writeMessage(webSocketInstance, "CREATE_MESSAGE",gameEntranceParams)
return
def sendUserSticker(websocketInstance, in_conversation_id, to_user_id, album_id, sticker_name):
realStickerObj = {}
realStickerObj['album_id'] = album_id
realStickerObj['name'] = sticker_name
btnJson = json.dumps(realStickerObj)
params = {"conversation_id": in_conversation_id,"recipient_id":to_user_id,"message_id":str(uuid.uuid4()),"category":"PLAIN_STICKER","data":base64.b64encode(btnJson)}
return writeMessage(websocketInstance, "CREATE_MESSAGE",params)
def sendUserPayAppButton(webSocketInstance, in_conversation_id, to_user_id, inAssetName, inAssetID, inPayAmount, linkColor = "#0CAAF5"):
payLink = "https://mixin.one/pay?recipient=" + mixin_config.mixin_client_id + "&asset=" + inAssetID + "&amount=" + str(inPayAmount) + '&trace=' + str(uuid.uuid1()) + '&memo=PRS2CNB'
btn = '[{"label":"' + inAssetName + '","action":"' + payLink + '","color":"' + linkColor + '"}]'
gameEntranceParams = {"conversation_id": in_conversation_id,"recipient_id":to_user_id,"message_id":str(uuid.uuid4()),"category":"APP_BUTTON_GROUP","data":base64.b64encode(btn)}
writeMessage(webSocketInstance, "CREATE_MESSAGE",gameEntranceParams)
def showReceipt(websocketInstance, inConversationID, reply_user_id, reply_snapShotID):
payLink = "https://mixin.one/snapshots/" + reply_snapShotID
shortSnapShort = reply_snapShotID[0:13] + "..."
btn = '[{"label":"Your receipt:' + shortSnapShort + '","action":"' + payLink + '","color":"#0CAAF5"}]'
params = {"conversation_id": inConversationID,"recipient_id":reply_user_id,"message_id":str(uuid.uuid4()),"category":"APP_BUTTON_GROUP","data":base64.b64encode(btn)}
writeMessage(websocketInstance, "CREATE_MESSAGE",params)
def replayMessage(websocketInstance, msgid):
parameter4IncomingMsg = {"message_id":msgid, "status":"READ"}
Message = {"id":str(uuid.uuid1()), "action":"ACKNOWLEDGE_MESSAGE_RECEIPT", "params":parameter4IncomingMsg}
Message_instring = json.dumps(Message)
fgz = StringIO()
gzip_obj = gzip.GzipFile(mode='wb', fileobj=fgz)
gzip_obj.write(Message_instring)
gzip_obj.close()
websocketInstance.send(fgz.getvalue(), opcode=websocket.ABNF.OPCODE_BINARY)
return
def buildConversationId(robot_id, user_id):
n = md5.new()
n.update(user_id)
n.update(robot_id)
result = n.digest()
result_6 = chr((ord(result[6]) & 0x0f) | 0x30)
result_8 = chr((ord(result[8]) & 0x3f) | 0x80)
result_new = result[:6] + result_6 + result[7] + result_8 + result[9:]
conver_id = uuid.UUID(bytes=result_new)
return str(conver_id)
def recordFreeBonus(in_user_id):
hashOfUserID = hashlib.sha256(in_user_id).hexdigest()
thisFreshMan = session.query(Freshman).filter_by(userid = hashOfUserID).first()
if thisFreshMan != None:
thisFreshMan.bonusCounter = thisFreshMan.bonusCounter + 1
session.commit()
else:
newFreshMan = Freshman()
newFreshMan.userid = hashOfUserID
newFreshMan.bonusCounter = 1
session.add(newFreshMan)
session.commit()
def notFreshMen(in_user_id):
hashOfUserID = hashlib.sha256(in_user_id).hexdigest()
thisFreshMan = session.query(Freshman).filter_by(userid = hashOfUserID).first()
return thisFreshMan != None and thisFreshMan.bonusCounter > 20
def on_message(ws, message):
inbuffer = StringIO(message)
f = gzip.GzipFile(mode="rb", fileobj=inbuffer)
rdata_injson = f.read()
print("recv msg:", rdata_injson)
rdata_obj = json.loads(rdata_injson)
action = rdata_obj["action"]
if action not in ["ACKNOWLEDGE_MESSAGE_RECEIPT" ,"CREATE_MESSAGE", "LIST_PENDING_MESSAGES"]:
print("unknow action")
return
if action == "ACKNOWLEDGE_MESSAGE_RECEIPT":
return
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)
print("msg b64 data decoded:", realData)
replayMessage(ws, msgid)
if 'error' in rdata_obj:
return
if categoryindata not in ["SYSTEM_ACCOUNT_SNAPSHOT", "PLAIN_TEXT", "SYSTEM_CONVERSATION", "PLAIN_STICKER", "PLAIN_IMAGE", "PLAIN_CONTACT"]:
print("unknow category")
return
if categoryindata == "PLAIN_IMAGE" or categoryindata == "SYSTEM_CONVERSATION":
sysConversationObj = json.loads(realData)
if sysConversationObj["action"] == "ADD":
sendGroupText(ws, conversationId, "hello")
if categoryindata == "SYSTEM_ACCOUNT_SNAPSHOT" and typeindata == "message":
realAssetObj = json.loads(realData)
counterUserId = realAssetObj["counter_user_id"]
asset_amount = realAssetObj["amount"]
#showReceipt(ws, conversationId, counterUserId, realAssetObj["snapshot_id"])
if realAssetObj["asset_id"] == mixin_asset_list.CNB_ASSET_ID:
if asset_amount == "1":
mixin_api_robot.transferTo(counterUserId, realAssetObj["asset_id"], "2", "pay 1 get 2")
return
else:
mixin_api_robot.transferTo(counterUserId, realAssetObj["asset_id"], asset_amount, "rollback")
#sendUserText(ws, counterUserId, counterUserId, str(realAssetObj))
return
if categoryindata == "PLAIN_STICKER":
realStickerObj = json.loads(realData)
sendUserText(ws, conversationId, userId, str(realStickerObj))
if categoryindata == "PLAIN_TEXT" and typeindata == "message":
realData = realData.lower()
if realData in ['?', '?', 'help', u'帮助'.encode('utf-8')]:
introductionContent = u"""本机器人代码 https://github.com/hxzqlh/mixin_client_demo 机器人可以理解区块链系列贴纸:向资本大鳄低头;买币是第一生产力;不玩了,不玩了,没钱了。输入 contact/sticker/link/paycnb/payeos/payprs/bonus 可获取各种例子""".encode('utf-8')
sendUserText(ws, conversationId, userId, introductionContent)
return
if 'sticker' == realData:
# TODO 买币是第一生产力
sticker_blockchain_album_id = "eb002790-ef9b-467d-93c6-6a1d63fa2bee"
sendUserSticker(ws, conversationId, userId, sticker_blockchain_album_id, 'productive')
return
if 'contact' == realData:
sendUserContactCard(ws, conversationId, userId, mixin_config.admin_uuid)
return
if 'link' == realData:
sendUserAppButton(ws, conversationId, userId, "http://hxzqlh.com", u"了解下我?".encode('utf-8'))
return
if 'paycnb' == realData:
sendUserPayAppButton(ws, conversationId, userId, u"付1CNB,得2CNB".encode('utf-8'),mixin_asset_list.CNB_ASSET_ID, 1, "#ff0033")
return
if 'payeos' == realData:
sendUserPayAppButton(ws, conversationId, userId, u"付0.001EOS并闪电退款".encode('utf-8'),mixin_asset_list.EOS_ASSET_ID, 0.001, "#ff0033")
return
if 'payprs' == realData:
sendUserPayAppButton(ws, conversationId, userId, u"付0.01PRS并闪电退款".encode('utf-8'),mixin_asset_list.PRS_ASSET_ID, 0.01, "#ff0033")
return
if 'bonus' == realData:
if notFreshMen(userId):
sendUserText(ws, conversationId, userId, u"新手期已过,没有奖励了".encode("utf-8"))
return
recordFreeBonus(userId)
now = datetime.datetime.now()
if userId in freeBonusTimeTable:
oldtime = freeBonusTimeTable[userId]
if (now - oldtime).total_seconds() < 60 * 10:
sendUserText(ws, conversationId, userId, u"点钞机过热,冷却中".encode('utf-8'))
return
freeBonusTimeTable[userId] = now
sendUserText(ws, conversationId, userId, u"与大佬做朋友就是好,10分钟以后再来一发".encode('utf-8'))
bonus = str(random.randint(10,100))
mixin_api_robot.transferTo(userId, mixin_asset_list.CNB_ASSET_ID, bonus, "you are rich")
if 'robot' == realData and userId == mixin_config.admin_uuid:
for eachNonZeroAsset in mixin_api_robot.listAssets():
sendUserText(ws, conversationId, userId, str(eachNonZeroAsset))
return
elif categoryindata == "PLAIN_TEXT":
print("PLAIN_TEXT but unkonw:")
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_data(ws, readableString, dataType, continueFlag):
return
def on_open(ws):
def run(*args):
print("ws open")
Message = {"id":str(uuid.uuid1()), "action":"LIST_PENDING_MESSAGES"}
Message_instring = json.dumps(Message)
fgz = StringIO()
gzip_obj = gzip.GzipFile(mode='wb', fileobj=fgz)
gzip_obj.write(Message_instring)
gzip_obj.close()
ws.send(fgz.getvalue(), opcode=websocket.ABNF.OPCODE_BINARY)
while True:
time.sleep(1)
thread.start_new_thread(run, ())
if __name__ == "__main__":
while True:
encoded = mixin_api_robot.genGETJwtToken('/', "", str(uuid.uuid4()))
#websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://blaze.mixin.one/",
on_message = on_message,
on_error = on_error,
on_close = on_close,
header = ["Authorization:Bearer " + encoded],
subprotocols = ["Mixin-Blaze-1"],
on_data = on_data)
ws.on_open = on_open
ws.run_forever()