xia的小窩

一起來coding和碼字吧

0%

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

提款

接下來,寫個提款功能

1
2
3
4
# cogs/money.py
@commands.command()
async def withdraw(self, ctx, amount = None):
pass

一樣,先打開account

1
await open_account(ctx.author)

再來,提款必須要有一個數字,如果沒有,就return回去

1
2
3
if amount == None:
await ctx.send("請輸入數字")
return

然後,再寫一個函式

1
2
async def update_bank(user, change = 0, mode = "wallet"):
pass

然後……

1
2
users = await get_bank_data()
users[str(user.id)][mode] += change

接著寫入json

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

然後回傳一個變數

1
2
bal = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]    
return bal

回到上面,這個變數是你個人的銀行有多少錢

1
bal = await update_bank(ctx.author)
1
amount = int(amount)

以及,可添加台詞(? 之類的

1
2
3
4
5
6
7
8
9
if amount > bal[1]:
await ctx.send("你沒這麼多錢拉幹")
return
if amount > 200:
await ctx.send("要小於200喔")
return
if amount< 0:
await ctx.send("北七喔,錢有負的喔")
return

最後別忘了回傳阿

1
2
3
4
await update_bank(ctx.author, amount)
await update_bank(ctx.author, -1*amount, "bank")

await ctx.send(f"你提款了 { amount } 塊錢!!!")

存款

依照上面那個部分稍微修改一下

1
2
3
4
# cogs/money.py
@commands.command()
async def deposit(ctx, amount = None):
pass

只要改一個部分……

1
2
await update_bank(ctx.author, -1 * amount)
await update_bank(ctx.author, amount, "bank")

對,就這樣XD

匯款

接下來寫個匯款系統

1
2
3
4
5
# cogs/money.py
@commands.command()
async def send(ctx, member:discord.Member, amount = None):
await open_account(ctx.author)
await open_account(member)

前面幾乎一樣

1
2
3
4
if amount == None:
await ctx.send("請輸入數字")
return
bal = await update_bank(ctx.author)

比較不一樣的地方可以自己取捨

1
2
3
4
5
6
7
8
9
if amount == "all":
amount = bal[0]
amount = int(amount)
if amount > bal[1]:
await ctx.send("你沒這麼多錢拉幹")
return
if amount< 0:
await ctx.send("北七喔,錢有負的喔")
return

一樣,打開get_bank_data()

1
2
await update_bank(ctx.author, -1 * amount, "bank")
await update_bank(member, amount, "bank")

接著加上,文字敘述

1
2
3
member = str(member)
member = member.split("#")[0]
await ctx.send(f"你給了{ member } { amount } 塊錢!!!")

2.0部分更改

一樣,沒什麼要更改的,如果有的話那應該是要讓程式休息一下或是增加key鍵。
其實最理想的狀況應該是

1
server.id(伺服器名稱)

從這個server.id這個資料夾去提取各個群組用的data。
所以…這部分也就加點判斷和間隔方式,可以使用asyncio做到。