เนื่องจากบทควาที่แล้วเรื่องให้ Google อ่าน Blog ให้ก็เลยเห็นว่าไหนๆแล้ว ก็ให้มันอัพขึ้น Google Storage แล้วส่ง Line Notification ให้ด้วยเลยละกัน จะได้ฟังบนมือถือได้
เตรียมตัวก่อนเริ่ม
1. ให้เตรียมไฟล์ที่ต้องการจะอัพโหลดขึ้น Google Storage นะครับ หรือจะดูจากบทความ Python : ให้ google อ่าน blog ให้ฟังกัน ก็ได้ครับ โดยตัวอย่างจะใช้ Code จากบทความที่แล้วนะครับ
2. จากนั้นให้ทำการ pip install ดังนี้ครับ
1. ให้เตรียมไฟล์ที่ต้องการจะอัพโหลดขึ้น Google Storage นะครับ หรือจะดูจากบทความ Python : ให้ google อ่าน blog ให้ฟังกัน ก็ได้ครับ โดยตัวอย่างจะใช้ Code จากบทความที่แล้วนะครับ
2. จากนั้นให้ทำการ pip install ดังนี้ครับ
- pip install google-cloud-storage
- pip install firebase
- pip install firebase_admin
4. แล้วให้ทำการไปที่ console.firebase.google.com และทำการ Copy link Storage ที่เราต้องการใช้งานครับ ดังภาพ
เท่านี้เราก็พร้อมที่จะเขียนโค้ดต่อละครับ
มาเริ่มกันครับ
1. ให้ทำการเพิ่ม
1. ให้ทำการเพิ่ม
from firebase_admin import credentials, initialize_app, storage
2. จากนั้นให้ทำการโหลด JSON file ที่เรา Download มานะครับ และเชื่อมต่อ firebase storage ด้วยคำสั่ง
cred = credentials.Certificate("your.json")
# ให้ทำการตัด gs:// ออกนะครับ
initialize_app(cred, {'storageBucket': 'yourproject.appspot.com'})
3. จะเป็นส่วนในการติดต่อกับ Line Notification นะครับ ให้ทำการเอา Token ของ Line มา จากนั้นก็ทำการประการศตัวแปรเพื่อรอเรียกใช้
url = 'https://notify-api.line.me/api/notify'
token = 'your token'
headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer '+token}
4. จากนั้นให้เราเพิ่มคำสั่ง ต่อท้าย tts.save(filePath) นะครับ
data = []
for elem in elems:
....
tts.save(filePath)
# ทำการติดต่อกับ firebase storage และนำไฟล์จากเครื่อง upload ไปที่ firebase storage
bucket = storage.bucket()
blob = bucket.blob('unity/' + fileName + ".mp3")
blob.upload_from_filename(filePath)
# กำหนดให้เป็น public
blob.make_public()
print("your file url", blob.public_url)
# กำหนดข้อความที่ต้องการส่ง Line Notification และเก็บลงใน data list
msg = title + '\n' + 'https://blogs.unity3d.com' + link + '\n' + blob.public_url + '\n'
data.append(msg)
# จากนั้นกำหนดว่า ถ้ามีการอัพไฟล์ 5 ไฟล์แล้วให้ทำการส่ง Notification แล้วทำการ reset data list
if(len(data) == 5):
r = requests.post(url, headers=headers, data = {'message': data})
data = []
# กรณีที่ไฟล์ที่มันไม่ถึง 5 ก็ให้ส่ง Line Notification ที่เหลือ
r = requests.post(url, headers=headers, data = {'message': data})
เท่านี้เราก็สามารถรันเพื่อให้ Upload file ขึ้น firebase storage และส่ง Line Notification ได้แล้วครับ
หวังว่าจะมีประโยชน์ไม่มากก็น้อยนะครับ
ขอบคุณครับ
หวังว่าจะมีประโยชน์ไม่มากก็น้อยนะครับ
ขอบคุณครับ