iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
自我挑戰組

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

開始花錢囉......?

先查看包包

  • 包包check
# cogs/money.py
# 略
@bot.command()
async def bag(ctx):
    await open_account(ctx.author)
    user = ctx.author    
    users = await get_bank_data()
  • 這邊要分2種情況,包包裡有東西跟沒東西
try:
    bag = users[str(user.id)]["bag"]
except:
    bag = []
  • 再來,就簡單了
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

建立起買東西的式子

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
  • 在沒輸入好的情況下要返回錯誤
if name == None:
    return [False, 1]
  • 再來,計算皮包裡的錢夠不夠
cost = price * amount
    
users = await get_bank_data()
bal = await update_bank(user)
    
if bal[0] < cost :
    return [False , 2] 
  • 寫到這邊,應該可以開始處理command了
@commands.command()
# amount = 1為默認
async def buy(self, ctx, item, amount = 1):
    pass
  • 再來,我們可以接收先前的返回值了
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檔,發現啥麼都沒出現......

上一篇
提款、存款、匯款一次到位
下一篇
嗚咕,東西沒進到口袋裡 -- 探討Json
系列文
Discord-bot,從0開始到做出一個機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言