iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
自我挑戰組

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

將MongoDB加進discord-bot

  • 分享至 

  • xImage
  •  

建立 data.py

  • 套入
pip install mongo

bot_id.json

{
    "token":"Your Token",
    "mongoclient":"剛剛複製過來的"
}

bot.py增加數據與查找

@bot.command()
async def check(ctx):
    await ctx.send("請稍等大約4秒鐘左右")
    re = checkdatabase(ctx.author, ctx.author.id)
  • 這邊要注意的是,因為查詢需要時間,所以會有延遲的狀況
  • 如果不在資料庫要先創建
#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
  • 如果為非,則創建
#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裡有的錢
#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功能

#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
#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)
  • 沒有的話先創建一個,有的話就直接執行

上一篇
使用MongoDB -- 資料庫簡易上手
下一篇
將機器人部屬到網路上去
系列文
Discord-bot,從0開始到做出一個機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言