xia的小窩

一起來coding和碼字吧

0%

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

建立 data.py

套入mongo

1
pip install mongo

bot_id.json

1
2
3
4
{
"token":"Your Token",
"mongoclient":"剛剛複製過來的"
}

bot.py增加數據與查找

1
2
3
4
@bot.command()
async def check(ctx):
await ctx.send("請稍等大約4秒鐘左右")
re = checkdatabase(ctx.author, ctx.author.id)

這邊要注意的是,因為查詢需要時間,所以會有延遲的狀況
如果不在資料庫要先創建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#data.py
from pymongo import MongoClient
import pymongo
import json

with open('bot_id.json', "r", encoding = "utf8") as datafile:
jsondata = json.load(datafile)

#checkdatabase is exist ?
def checkdatabase(name, ID):
cluster = MongoClient(jsondata["mongoclient"])

db = cluster['discord_bot_database']
collection = db['data']

result = collection.find_one({str(name) : str(ID)})

if not result:

post = { str(name) : str(ID) , "wallet" : 0, "bank" : 0}

collection.insert_one(post)
return False

else:
return True

如果為非,則創建

1
2
3
4
5
6
7
8
9
10
11
#bot.py
if re == False:
await ctx.send("不在資料庫中,現在碼上創建")
else:
await ctx.send("已在資料庫中,正在讀取資料,請稍後")
w, b = viewbank(ctx.author, ctx.author.id)
em = discord.Embed(title = f"{ctx.author.name}'s 錢包", color = discord.Color.red())
em.set_thumbnail(url = ctx.author.avatar_url)
em.add_field(name = "Wallet", value = w)
em.add_field(name = "Bank", value = b)
await ctx.send(embed = em)

回到剛剛的部分,有了就給出wallet跟bank裡有的錢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#data.py
#view bank data
def viewbank(name, ID):
cluster = MongoClient(jsondata["mongoclient"])

db = cluster['discord_bot_database']
collection = db['data']

id = str(ID)
membername = str(name)

test = []
for i in collection.find({membername : id}):
test.append(i)

print("find $$ succeddful")
wallet = next(item for item in test if item[membername] == id)

nowwallet = wallet["wallet"]
nowbank = wallet["bank"]

print("$$ succeddful")
return nowwallet, nowbank

改寫一下beg功能

1
2
3
4
5
6
#beg money
@commands.command()
async def beg(self, ctx):
begnums = random.randint(1, 100)
begdata(ctx.author, ctx.author.id, begnums)
await ctx.send(f"你獲得了{begnums}$")

回到 data.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#beg $$調整
def begdata(name, ID, begnums):
cluster = MongoClient(jsondata["mongoclient"])

db = cluster['discord_bot_database']
collection = db['data']

try:
id = str(ID)
membername = str(name)

test = []
for i in collection.find({membername : id}):
test.append(i)

print("succeddful")
wallet = next(item for item in test if item[membername] == id)
nowwallet = wallet["wallet"]

myquery = { "wallet": nowwallet }
newvalues = { "$set": { "wallet": nowwallet + begnums } }

print("begdata succeddful")
collection.update_one(myquery, newvalues)
except:
checkdatabase(name, ID)
begdata(name, ID, begnums)

沒有的話先創建一個,有的話就直接執行

備註

2023-11-8,如果我那時候寫是沒問題的,那只要不是亂更動,那應該也不會有甚麼神奇的問題…
頂多就是連線會卡。