main.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. # nft collection api
  151. @app.get("/collection/{userid}")
  152. def collection(userid):
  153. # 連到ownership表單去找,並回傳json
  154. # db connect
  155. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  156. table1 = db['ownership']
  157. nft = {}
  158. i = 0
  159. if not table1.find_one(userid=userid):
  160. db.close()
  161. return "error: user don't have any nft"
  162. else:
  163. results = db.query("SELECT nftid, amount FROM arkcard.ownership WHERE userid IN (SELECT userid FROM arkcard.ownership WHERE userid = '"+userid+"');")
  164. for item in results:
  165. nft[i] = item
  166. i += 1
  167. db.close()
  168. return nft
  169. # receive handler
  170. @app.get("/receive/{userid}")
  171. def receive(userid):
  172. # 確定要傳送的對象,到user去找到它
  173. # db connect
  174. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  175. table = db['users']
  176. if not table.find_one(userid=userid):
  177. db.close()
  178. return "ERROR: User Not Found"
  179. else:
  180. result = table.find_one(userid=userid)
  181. db.close()
  182. return {"userid": result['userid'], "address": result['address']}
  183. # send handler
  184. @app.post("/send")
  185. async def receive(userModel : models.TransactionNft):
  186. # db connect
  187. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  188. table = db['users']
  189. table2 = db['nft']
  190. table3 = db['nftdrops']
  191. # input and find userid
  192. nftid = userModel.nftid
  193. address = userModel.address
  194. result = table.find_one(useraddress=address)
  195. # first confirm if the user exist
  196. if not result:
  197. db.close()
  198. return {'msg': 'user address not found'}
  199. else:
  200. userid = result['userid']
  201. # update nft owner
  202. if table3.find_one(nftid=nftid):
  203. data = dict(nftid=nftid, userid=userid)
  204. table3.update(data, ['nftid'])
  205. db.close()
  206. elif table2.find_one(id=nftid):
  207. data = dict(id=nftid, userid=userid)
  208. table2.update(data, ['id'])
  209. db.close()
  210. else:
  211. db.close()
  212. return {'msg': 'nft not found'}
  213. return {'msg': 'OK'}
  214. # shop handler
  215. @app.get("/shop/{userid}")
  216. def shop(userid):
  217. # db connect
  218. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  219. sql = 'SELECT DISTINCT(title), id, imgurl, userid FROM arkcard.nft WHERE id<1001 and userid IS NULL GROUP BY title LIMIT 5'
  220. result = db.query(sql)
  221. rows = {}
  222. i = 0
  223. for row in result:
  224. rows[i] = row
  225. i += 1
  226. return rows
  227. db.close()
  228. @app.post("/buy")
  229. async def buy(userModel : models.BuyNft):
  230. # db connect
  231. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  232. table2 = db['nft']
  233. # input
  234. nftid = userModel.nftid
  235. userid = userModel.userid
  236. if not table2.find_one(id=nftid):
  237. db.close()
  238. print("error: nft not found")
  239. return "該NFT商品不存在!如果有疑問,請洽網站的服務信箱!"
  240. else:
  241. user_obj = table2.find_one(id=nftid)
  242. user_obj['userid'] = userid
  243. table2.update(dict(user_obj), ['id'])
  244. db.close()
  245. return "您已購買成功!"
  246. @app.post("/event")
  247. async def nftdrops(userModel : models.NftDrops):
  248. # db connect
  249. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
  250. table3 = db['nftdrops']
  251. # input對應
  252. eventid = '1'
  253. nftid = '1001'
  254. nftid2 = '1002'
  255. userid = userModel.userid
  256. email = userModel.email
  257. now = dt.datetime.now()
  258. # 如果userid不在db, 寫入到一個空值nft
  259. if not table3.find_one(userid=userid):
  260. # 新增資料
  261. table3.insert(dict(eventid=eventid, nftid=nftid, userid=userid, email=email, time=now))
  262. table3.insert(dict(eventid=eventid, nftid=nftid2, userid=userid, email=email, time=now))
  263. db.close()
  264. return "新增成功"
  265. # 如果userid存在,回傳通知
  266. else:
  267. db.close()
  268. return "已有資料"
  269. if __name__ == '__main__':
  270. 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'))