簡體   English   中英

discord.py ,在 .json 中正確存儲用戶 ID 和數字

[英]discord.py , storing user id and numbers in .json properly

你好,我正在嘗試創建一個計數器/統計系統。 它存儲了用戶說了多少次特定單詞,也許很快會更多,但現在我只是嘗試開始。 到目前為止,我整個星期天都在用這個。 我 5 天前開始使用 python,這是我第一次嘗試編碼,請解釋一下,友好且樂於助人。

我的問題是我只能為每個用戶存儲一個單詞計數器。 我在創建命令以獲取統計信息時遇到問題。

bot.py:

def load_stats():
    with open('stats.json', 'r') as f:
        stats = json.load(f)
    return stats

def save_stats(stats):
    with open('stats.json', 'w') as f:
        json.dump(stats, f, indent=4))

log_data = {}

@bot.listen()
async def on_message(message):
    if any(x in message.content.lower() for x in ["bye", "cya", "bb", "gn8", "cya later"]):
        await loging.meslog_green(bot, message, 'bye')
        log_data = load_stats()
        authorid = str(message.author.id)
        author = str(message.author)
        if authorid {'bye'} in log_data:
            log_data[str(message.author.id)]['bye'] += 1
            save_stats(log_data)
        else:
            log_data[str(message.author.id)] = {}
            log_data[str(message.author.id)]['bye'] = 1
            save_stats(log_data)
    
    if any(x in message.content.lower() for x in ["hello", "hey", "hi", "greetings", "good morning", "good afternoon"]):
        await loging.meslog_green(bot, message, 'hey')
        log_data = load_stats()
        authorid = str(message.author.id)
        author = str(message.author)
        if authorid {'hey'} in log_data:
            log_data[str(message.author.id)]['hey'] += 1
            save_stats(log_data)
        else:
            log_data[str(message.author.id)] = {}
            log_data[str(message.author.id)]['hey'] = 1
            save_stats(log_data)

@bot.command(name='hey')
async def hey(ctx):
    stats = load_stats()
    await ctx.reply(f'you said {stats[ctx.author.id]["hey"]} times stats ', delete_after=10.0)'
    await loging.comlog_green(bot, ctx, 'hey')

stats.json :

{
    "448827301235084672": {
        "hey": 2
    }
}

如果我正確解釋了您的問題並且您只需要更好地格式化您的文件,您可以使用indent選項。

如果indent是一個非負整數,那么 JSON 數組元素和對象成員將使用該縮進級別進行漂亮的打印。 縮進級別 0 只會插入換行符。 None是最緊湊的表示。

例如,使用

def save_stats(stats):
    with open('stats.json', 'w') as f:
        json.dump(stats, f, indent=4)

將導致

{
    "448827123485084672": {
        "hey": 2
    },
    "884530123033089076": {
        "hey": 1
    }
}

您不需要修改 load 方法,因為縮進實際上並沒有改變 json 數據的含義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM