xia的小窩

一起來coding和碼字吧

0%

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

創建你的錢包

一樣,對比前面的match檔,現在新增一個bank的json檔案
回到bot檔,現在我們必須撰寫2個部分,一個是讀取,一個是確認你的這個key是否存在……

1
2
3
4
5
6
7
8
# cogs/includebanksystem.py
async def open_account(user):
pass

# 省略

async def get_bank_data():
pass

前者必須確認key,後者只須要做read的這個部分即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
# 省略
with open("bank.json", "w") as f:
json.dump(users, f)

return True

async def get_bank_data():
with open("bank.json", "r")as f:
users = json.load(f)
return users

回到我們剛才省略的部分,原始資料一律用0

1
2
3
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0

bank檔

1
2
3
{

}

顯示出你的錢包

一樣,先打開你的json,然後依照欄位做處理

1
2
3
4
5
6
7
8
# 略
@commands.command()
async def money(self, ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet = users[str(user.id)]["wallet"]
bank = users[str(user.id)]["bank"]

將資料拿出來後,使用先前的方法,做元素添加
這邊比較不一樣的是,user.avatar_url(這個東西就是自己的頭像 XD)

1
2
3
4
5
em = discord.Embed(title = f"{ctx.author.name}'s 錢包", color = discord.Color.red())
em.set_thumbnail(url = user.avatar_url)
em.add_field(name = "Wallet", value = wallet)
em.add_field(name = "Bank", value = bank)
await ctx.send(embed = em)

示意圖

貨物上架

在bot最上放以json的格式,輸入你想要的貨物

1
2
3
4
5
6
7
8
# 略
shop = [
{"name": "Watch", "price": 8},
{"name": "Laptop", "price": 87},
{"name": "PC", "price": 870},
{"name": "PS5", "price": 690},
{"name": "Cat", "price": 1000}
]

回到下方,寫出函式

1
2
3
@commands.command()
async def market(self, ctx):
pass

利用for……in……迴圈

1
2
3
4
5
6
7
8
em = discord.Embed(title = "market", color = 0x6345)
em.set_thumbnail(url = "https://www.formula-ai.com/wp-content/uploads/2020/09/python_or_java_meme.jpg")

for item in shop:
name = item["name"]
price = item["price"]
em.add_field(name = name, value = f"${price}")
await ctx.send(embed = em)

示意圖

2.0部分更改

具體來說這個問題和之前一樣,有些地方就不贅述了,直接說哪裡要改就好了。
user.avatar_url要改成user.avatar.url
照著慣例都會是
icon_url = self.bot.user.avatar.url
其他沒什麼問題。

至於取名,不要在乎那些細節,以前寫的嘛…
不好意思捏