main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import uvicorn
  2. import fastapi
  3. from fastapi.middleware.cors import CORSMiddleware
  4. from fastapi.responses import HTMLResponse
  5. from linebot import LineBotApi, WebhookHandler
  6. from linebot.models import (
  7. MessageEvent, TextMessage, TextSendMessage, FollowEvent, TemplateSendMessage, ButtonsTemplate, URITemplateAction,
  8. )
  9. import dataset
  10. import requests
  11. import json
  12. import qrcode
  13. # from PIL import Image
  14. # import base64, io
  15. from random import randrange
  16. import models
  17. import datetime as dt
  18. app = fastapi.FastAPI()
  19. app.add_middleware(
  20. CORSMiddleware,
  21. allow_origins=['*'],
  22. allow_credentials=True,
  23. allow_methods=["*"],
  24. allow_headers=["*"],
  25. )
  26. # bot config
  27. line_bot_api = LineBotApi("SJT7VPT4RMQFLcS27jQBy3FcC24gtDrkcwJWZ5Xzqesr5T78LOKudHEJzt0k3b2S7n4KPwf27J7DVz2c8NQ4plSaaQylEeB1cYrfejaE/RPG/lCIQBYe4iBTzo26s4i2PcmT89837per/lTyvhVIKAdB04t89/1O/w1cDnyilFU=")
  28. handler = WebhookHandler("411ae3ef7e766739ed2c2c27b249d010")
  29. # callback event
  30. @app.post("/callback")
  31. async def callback(request: fastapi.Request):
  32. signature = request.headers['X-Line-Signature']
  33. body = await request.body()
  34. handler.handle(body.decode('utf-8'), signature)
  35. return 'OK'
  36. # follow event
  37. @handler.add(FollowEvent)
  38. def handle_follow(event):
  39. # get user id when follow
  40. real_user_id = event.source.user_id
  41. # db connect and search
  42. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  43. table = db['users']
  44. result1 = table.find_one(userid=real_user_id)
  45. # 都存在db的話
  46. if result1:
  47. db.close()
  48. line_bot_api.reply_message(
  49. event.reply_token,
  50. TextSendMessage(text='很高興再見到您!'))
  51. # 建立全新使用者
  52. else:
  53. # create user account api
  54. url = 'https://nft-api-staging.joyso.io/api/v1/accounts'
  55. headers = {'Authorization': 'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl'}
  56. # setup for temp use (unique id)
  57. rand_num = str(randrange(99999))
  58. user_id = event.source.user_id + rand_num
  59. data = 'uid=' + user_id
  60. r = requests.post(url=url, headers=headers, data=data)
  61. # extract the account address
  62. dict_str = json.loads(r.text)
  63. user_account = dict_str['account']
  64. user_address = user_account['address']
  65. # generate qr code from user id
  66. qr = qrcode.QRCode(
  67. version=1,
  68. box_size=10,
  69. border=5)
  70. qr.add_data(user_address)
  71. qr.make(fit=True)
  72. img_qr = qr.make_image(fill='black', back_color='white')
  73. filename = "/var/www/ArkCard-Linebot/ArkCard-web/qrcode/" + real_user_id + '.png'
  74. img_save = img_qr.save(filename)
  75. # add to db
  76. data = dict(userid=real_user_id, useraddress=user_address)
  77. table.insert(data)
  78. db.close()
  79. line_bot_api.reply_message(
  80. event.reply_token,
  81. TextSendMessage(text='歡迎加入好友'))
  82. # message handler
  83. @handler.add(MessageEvent, message=TextMessage)
  84. def message(event):
  85. if '我要發送' in event.message.text:
  86. button_template_message = ButtonsTemplate(
  87. title=' ',
  88. text='點擊並打開收藏的NFT,可以選擇想要發送的NFT給對方!',
  89. actions=[
  90. URITemplateAction(
  91. label='打開發送頁',
  92. uri='https://ark.cards/collect.html?' + event.source.user_id),])
  93. line_bot_api.reply_message(
  94. event.reply_token,
  95. TemplateSendMessage(
  96. alt_text="Receive",
  97. template=button_template_message))
  98. elif '我要接收' in event.message.text:
  99. button_template_message = ButtonsTemplate(
  100. title=' ',
  101. text='點擊並打開接收頁面,即可分享接收地址給對方!',
  102. actions=[
  103. URITemplateAction(
  104. label='打開接收頁',
  105. uri='https://ark.cards/qr-code.html?' + event.source.user_id),])
  106. line_bot_api.reply_message(
  107. event.reply_token,
  108. TemplateSendMessage(
  109. alt_text="Receive",
  110. template=button_template_message))
  111. elif 'NFT商店' in event.message.text:
  112. button_template_message = ButtonsTemplate(
  113. title=' ',
  114. text='點擊並打開NFT商品頁,就可以購買您所想要的NFT商品哦!',
  115. actions=[
  116. URITemplateAction(
  117. label='打開NFT商品頁',
  118. uri='https://ark.cards/shop.html?' + event.source.user_id),])
  119. line_bot_api.reply_message(
  120. event.reply_token,
  121. TemplateSendMessage(
  122. alt_text="Receive",
  123. template=button_template_message))
  124. elif 'NFT收藏' in event.message.text:
  125. button_template_message = ButtonsTemplate(
  126. title=' ',
  127. text='點擊並打開收藏的NFT,可以查看收到的NFT!',
  128. actions=[
  129. URITemplateAction(
  130. label='打開收藏頁',
  131. uri='https://ark.cards/collect.html?' + event.source.user_id), ])
  132. line_bot_api.reply_message(
  133. event.reply_token,
  134. TemplateSendMessage(
  135. alt_text="Receive",
  136. template=button_template_message))
  137. else:
  138. button_template_message = ButtonsTemplate(
  139. title=' ',
  140. text='更多的服務內容,歡迎請上我們的官網!',
  141. actions=[
  142. URITemplateAction(
  143. label='ArkCard的官網',
  144. uri='https://ark.cards'),])
  145. line_bot_api.reply_message(
  146. event.reply_token,
  147. TemplateSendMessage(
  148. alt_text="Receive",
  149. template=button_template_message))
  150. @app.post("/push/")
  151. def push_text(user, message):
  152. line_bot_api.push_message(user, TextSendMessage(text=message))
  153. # nft collection api
  154. @app.get("/collection/{userid}")
  155. def collection(userid):
  156. # db connect
  157. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  158. table3 = db['nftdrops']
  159. table2 = db['nft']
  160. nftdrops = {}
  161. nft = {}
  162. nfts_all = {}
  163. i = 0
  164. j = 0
  165. if not table3.find_one(userid=userid) and not table2.find_one(userid=userid):
  166. db.close()
  167. return "error: user don't have any nft"
  168. else:
  169. results1 = table3.find(userid=userid)
  170. for item in results1:
  171. nft_id = item['nftid']
  172. nftdrops[i] = table2.find_one(id=nft_id)
  173. i += 1
  174. results2 = table2.find(userid=userid)
  175. for item in results2:
  176. nft[j] = item
  177. j += 1
  178. nfts_all[0] = nftdrops
  179. nfts_all[1] = nft
  180. return nfts_all
  181. db.close()
  182. # receive handler
  183. @app.get("/receive/{userid}")
  184. def receive(userid):
  185. # db connect
  186. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  187. table = db['users']
  188. table.find_one(userid=userid)
  189. if not table.find_one(userid=userid):
  190. db.close()
  191. return "ERROR: User Not Found"
  192. else:
  193. result = table.find_one(userid=userid)
  194. return {"userid": result['userid'], "useraddress": result['useraddress']}
  195. db.close()
  196. # send handler
  197. @app.post("/send")
  198. async def receive(userModel : models.TransactionNft):
  199. # db connect
  200. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  201. table = db['users']
  202. table2 = db['nft']
  203. table3 = db['nftdrops']
  204. # input and find userid
  205. nftid = userModel.nftid
  206. address = userModel.address
  207. result = table.find_one(useraddress=address)
  208. # first confirm if the user exist
  209. if not result:
  210. db.close()
  211. return {'msg': 'user address not found'}
  212. else:
  213. userid = result['userid']
  214. # update nft owner
  215. if table3.find_one(nftid=nftid):
  216. data = dict(nftid=nftid, userid=userid)
  217. table3.update(data, ['nftid'])
  218. # push訊息
  219. result3 = table2.find_one(id=nftid)
  220. title = result3['title']
  221. message = "您的NFT : " + title + ", 已劃轉成功!"
  222. push_text(userid, message)
  223. db.close()
  224. elif table2.find_one(id=nftid):
  225. result3 = table2.find_one(id=nftid)
  226. pre_own = result3['userid']
  227. data = dict(id=nftid, userid=userid)
  228. table2.update(data, ['id'])
  229. # push訊息
  230. title = result3['title']
  231. fr = "您的NFT : " + title + ", 已發送成功!"
  232. to = "您的NFT : "+title+", 已收到!"
  233. push_text(userid, to)
  234. push_text(pre_own, fr)
  235. db.close()
  236. else:
  237. db.close()
  238. return {'msg': 'nft not found'}
  239. return {'msg': 'OK'}
  240. # shop handler
  241. @app.get("/shop/{userid}")
  242. def shop(userid):
  243. # db connect
  244. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  245. sql = 'SELECT DISTINCT(title), id, imgurl, userid FROM arkcard.nft WHERE id<1001 and userid IS NULL GROUP BY title LIMIT 5'
  246. result = db.query(sql)
  247. rows = {}
  248. i = 0
  249. for row in result:
  250. rows[i] = row
  251. i += 1
  252. return rows
  253. db.close()
  254. @app.post("/buy")
  255. async def buy(userModel: models.BuyNft):
  256. # db connect
  257. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  258. table2 = db['nft']
  259. # input
  260. nftid = userModel.nftid
  261. userid = userModel.userid
  262. if not table2.find_one(id=nftid):
  263. db.close()
  264. print("error: nft not found")
  265. return "該NFT商品不存在!如果有疑問,請洽網站的服務信箱!"
  266. else:
  267. user_obj = table2.find_one(id=nftid)
  268. user_obj['userid'] = userid
  269. table2.update(dict(user_obj), ['id'])
  270. # push訊息
  271. result3 = table2.find_one(id=nftid)
  272. title = result3['title']
  273. message = "您的NFT : " + title + ", 已購買成功!"
  274. push_text(userid, message)
  275. db.close()
  276. return "您已購買成功!"
  277. @app.post("/event")
  278. async def nftdrops(userModel : models.NftDrops):
  279. # db connect
  280. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  281. table3 = db['nftdrops']
  282. # input對應
  283. eventid = '1'
  284. nftid = '1001'
  285. nftid2 = '1002'
  286. userid = userModel.userid
  287. email = userModel.email
  288. now = dt.datetime.now()
  289. # 如果userid不在db, 寫入到一個空值nft
  290. if not table3.find_one(userid=userid):
  291. # 新增資料
  292. table3.insert(dict(eventid=eventid, nftid=nftid, userid=userid, email=email, time=now))
  293. table3.insert(dict(eventid=eventid, nftid=nftid2, userid=userid, email=email, time=now))
  294. db.close()
  295. return "新增成功"
  296. # 如果userid存在,回傳通知
  297. else:
  298. db.close()
  299. return "已有資料"
  300. if __name__ == '__main__':
  301. uvicorn.run("main:app", host="0.0.0.0", port=8228, reload=True,ssl_context=('/etc/letsencrypt/live/ark.cards/fullchain.pem', '/etc/letsencrypt/live/ark.cards/privkey.pem'))