Browse Source

Merge branch 'master' of http://git.choozmo.com:3000/choozmo/ArkCard-Linebot into master

jeter20131220 3 years ago
parent
commit
d32b44b45b
1 changed files with 103 additions and 31 deletions
  1. 103 31
      main.py

+ 103 - 31
main.py

@@ -2,12 +2,16 @@ import uvicorn
 import fastapi
 from fastapi.middleware.cors import CORSMiddleware
 from linebot import LineBotApi, WebhookHandler
-from linebot.models import ( 
+from linebot.models import (
     MessageEvent, TextMessage, TextSendMessage, FollowEvent, TemplateSendMessage, ButtonsTemplate, URITemplateAction,
-    )
+)
 import dataset
 import requests
 import json
+import qrcode
+from PIL import Image
+import base64, io
+from random import randrange
 
 app = fastapi.FastAPI()
 
@@ -19,7 +23,6 @@ app.add_middleware(
     allow_headers=["*"],
 )
 
-
 # bot config
 line_bot_api = LineBotApi("SJT7VPT4RMQFLcS27jQBy3FcC24gtDrkcwJWZ5Xzqesr5T78LOKudHEJzt0k3b2S7n4KPwf27J7DVz2c8NQ4plSaaQylEeB1cYrfejaE/RPG/lCIQBYe4iBTzo26s4i2PcmT89837per/lTyvhVIKAdB04t89/1O/w1cDnyilFU=")
 handler = WebhookHandler("411ae3ef7e766739ed2c2c27b249d010")
@@ -42,41 +45,98 @@ def collection(userid):
     xname = userid
     sql = 'SELECT a.* FROM nft a INNER JOIN ( SELECT userid FROM users WHERE userid="'+xname+'" ) b ON b.userid = a.userid'
     result = db.query(sql)
-    rows={}
+    rows = {}
     i = 0
     for row in result:
-        rows[i]=row
-        i+=1
+        rows[i] = row
+        i += 1
     return rows
 
+# receive handler
+@app.get("/receive/{userid}")
+def receive(userid):
+    if not table.find_one(userid=userid):
+        return "ERROR: User Not Found"
+    else:
+        return {"base":(table.find_one(userid=userid))['base']}
+
+# TODO send handler 發送nft
+# @app.get("/collection/{userid}/{hash}")
+# def blockchain():
 
+# TODO post blockchain api 上鏈nft
+# @app.get("/collection/{userid}/{art}")
+# def blockchain():
+
+# TODO get transaction update 取得交易結果
+# @app.get("/collection/{userid}")
+# def blockchain():
 
 # follow event
 @handler.add(FollowEvent)
 def handle_follow(event):
     # get user id when follow
     real_user_id = event.source.user_id
-    rand_num = '_test_000_000_002'
-    user_id = event.source.user_id+rand_num
-
-    # create user account
-    url = 'https://nft-api-staging.joyso.io/api/v1/accounts'
-    headers = {'Authorization': 'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl'}
-    # setup for temp use (unique id)
-    data = 'uid='+user_id
-    r = requests.post(url=url, headers=headers, data=data)
-    # extract the account address
-    dict_str = json.loads(r.text)
-    user_account = dict_str['account']
-    user_address = user_account['address']
-    # write in sql
-    data = dict(userid=real_user_id, useraddress=user_address)
-    table.insert(data)
-    print(" Follow event: "+event.source.user_id)
-    line_bot_api.reply_message(
-        event.reply_token,
-        TextSendMessage(text='歡迎加入好友'))
-                                  
+    rand_num = randrange(999999)
+    user_id = event.source.user_id + rand_num
+    result = table.find_one(userid=real_user_id)
+
+    if result:
+        print(real_user_id)
+        line_bot_api.reply_message(
+            event.reply_token,
+            TextSendMessage(text='很高興再見到您!'))
+    else:
+        print("n")
+        # create user account
+        url = 'https://nft-api-staging.joyso.io/api/v1/accounts'
+        headers = {'Authorization': 'Basic bmZ0OmMxOTEzOWMzYjM3YjdjZWU3ZmY3OTFiZGU3NzdjZWNl'}
+        # setup for temp use (unique id)
+        data = 'uid=' + user_id
+        r = requests.post(url=url, headers=headers, data=data)
+        # extract the account address
+        dict_str = json.loads(r.text)
+        user_account = dict_str['account']
+        user_address = user_account['address']
+
+        # generate qr code from user id
+        qr = qrcode.QRCode(
+            version=1,
+            box_size=10,
+            border=5)
+        qr.add_data(user_address)
+        qr.make(fit=True)
+
+        img_qr = qr.make_image(fill='black', back_color='white')
+        filename = "qrcode/" + real_user_id + '.png'
+        img_save = img_qr.save(filename)
+
+        # open file
+        im = Image.open(filename)
+
+        # convert
+        imgByteArr = io.BytesIO()
+        im.save(imgByteArr, format='PNG')
+
+        # decode to ascii
+        x = imgByteArr.getvalue()
+        base64.b64encode(x).decode('ascii')
+        encode = base64.b64encode(x).decode('ascii')
+
+        # add to db
+        data = dict(base64=encode)
+        result = data['base64']
+        # table.update(dict(userid=userid, base=result), ['userid'])
+
+        # write in sql
+        data = dict(userid=real_user_id, useraddress=user_address, base=result)
+        table.insert(data)
+
+        print(" Follow event: " + event.source.user_id)
+        line_bot_api.reply_message(
+            event.reply_token,
+            TextSendMessage(text='歡迎加入好友'))
+
 # message handler
 @handler.add(MessageEvent, message=TextMessage)
 def message(event):
@@ -94,16 +154,28 @@ def message(event):
                 alt_text="Receive",
                 template=button_template_message))
 
-    elif '我要接收' in  event.message.text:
-        user_id = event.source.user_id
-        print(" message event: "+user_id)
+    elif '我要接收' in event.message.text:
         button_template_message = ButtonsTemplate(
             title=' ',
             text='點擊並打開接收頁面,即可分享接收地址給對方!',
             actions=[
                 URITemplateAction(
                     label='打開接收頁面',
-                    uri='http://q.ptt.cx/a1/index-line.html?userid=' + event.source.user_id),])
+                    uri='http://ark.cards/receive/' + event.source.user_id),])
+        line_bot_api.reply_message(
+            event.reply_token,
+            TemplateSendMessage(
+                alt_text="Receive",
+                template=button_template_message))
+
+    elif '我的NFT收藏' in event.message.text:
+        button_template_message = ButtonsTemplate(
+            title=' ',
+            text='點擊並打開收藏頁面,就可以查看所有的收藏品哦!',
+            actions=[
+                URITemplateAction(
+                    label='打開我的NFT收藏頁面',
+                    uri='http://ark.cards/collection/' + event.source.user_id),])
         line_bot_api.reply_message(
             event.reply_token,
             TemplateSendMessage(