xia的小窩

一起來coding和碼字吧

0%

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

先查看包包

包包check

1
2
3
4
5
6
7
# cogs/money.py
# 略
@bot.command()
async def bag(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()

這邊要分2種情況,包包裡有東西跟沒東西

1
2
3
4
try:
bag = users[str(user.id)]["bag"]
except:
bag = []

再來,就簡單了

1
2
3
4
5
6
7
8
9
em = discord.Embed(title = "Bag", color = 0xFF5733)
em.set_thumbnail(url = user.avatar_url)
for item in bag:
name = item["item"]
amount = item["amount"]

em.add_field(name = name, value = amount)

await ctx.send(embed = em)

一樣是用迭代的方式XD

建立起買東西的式子

1
2
3
4
5
6
7
8
9
async def buySomething(user, itemName, amount):
name = None
itemName = itemName.lower()
for item in shop:
Item_Name = item["name"].lower()
if Item_Name == itemName:
name = Item_Name
price = item["price"]
break

在沒輸入好的情況下要返回錯誤

1
2
if name == None:
return [False, 1]

再來,計算皮包裡的錢夠不夠

1
2
3
4
5
6
7
cost = price * amount

users = await get_bank_data()
bal = await update_bank(user)

if bal[0] < cost :
return [False , 2]

寫到這邊,應該可以開始處理command了

1
2
3
4
@commands.command()
# amount = 1為默認
async def buy(self, ctx, item, amount = 1):
pass

再來,我們可以接收先前的返回值了

1
2
3
4
5
6
7
8
9
10
11
12
13
await open_account(ctx.author)

res = await buy_this(ctx.author, item, amount)

if res[0] == False :
if res[1] == 1 :
await ctx.send("沒有這個東西喔")
return
if res[1] == 2 :
await ctx.send(f"你的錢包裡沒有足夠的錢去買 {item}")
return

await ctx.send(f"你買到了 {amount} x{item}")

到這邊應該是沒有什麼問題,這時候你點開json檔,發現啥麼都沒出現……

2.0部分更改

這裡沒有