xia的小窩

一起來coding和碼字吧

0%

python-Discord-bot,從0開始到做出一個機器人系列-22

關於貨物沒進到口袋這檔事

回到剛才的函式,我們分為2部分,第一是如果存在,那amount的數字必須加上買的數量,第二是如果沒有,那就添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#cogs/money.py
# 使用try......except
try:
# 使用count確認位置
count = 0
# 預設為0先認定它不存在,如存在則改為1
exist = 0
for cargo in users[str(user.id)]["bag"]:
item = cargo["item"]
if item == itemName:
oldAmount = cargo["amount"]
newAmount = oldAmount + amount
users[str(user.id)]["bag"][count]["amount"] = newAmount
exist = 1
break
count += 1
if exist == 0:
beginexist = {"item":itemName, "amount":amount}
users[str(user.id)]["bag"].append(beginexist)

except:
beginexist = {"item" : itemName, "amount" : amount}
users[str(user.id)]["bag"] = [beginexist]

最後,記得寫回去json裡面

1
2
3
4
5
with open("bank.json", "w") as f:
json.dump(users, f)

await update_bank(user, cost*-1, "wallet")
return [True, "worked"]

這樣就能確認運作囉

關於Json檔

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"682809473085079625":
{
"wallet": 1054,
"bank": 0,
"bag":
[
{
"item": "watch", "amount": 10
}
]
}
}

這是到目前為止的格式
其實追根究柢來說,可以使用資料庫,但什麼是Json?

什麼是Json

JSON 是資料交換的格式。 是 Javascript Object Notation 的縮寫。 先學 Javascript 再學 JSON 會有幫助,因為它是 Javascript 衍生出的一項功能。 JSON 是根據 JavaScript 的物件實字 (object literal) 發展的。 –Json精要讀書紀錄

結構


畫面不清楚請點擊

為甚麼不用資料庫

第一是,容易解析,又可以有結構,純文字又方便傳輸,現在幾乎所有後端甚至JavaScript都支援Json格式

第二是,因為資料庫連接較慢,我每呼叫一次函式就會發起一次請求,一點點還好,量多就……望向線上版資料庫,個人沒試過MySQL,或許會比較快…?(本人使用MongoDB)