コードが適切に機能する場合は、誰かがチャットで何かを入力するたびに5つのエクスペリエンスが得られ、その情報が.json
ファイルですが、代わりに誰かがチャットに何かを入力すると、このエラーが発生します。
on_message users = json.dumps(f)
TypeError: Object of type TextIOWrapper is not JSON serializable
これが私が使用しているコードです:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import json
from json import dumps, loads, JSONEncoder, JSONDecoder
import os
client = commands.Bot(command_prefix='^')
os.chdir(r'C:\Users\quiny\Desktop\sauce')
@client.event
async def on_ready():
print ("Ready when you are xd")
print ("I am running on " + client.user.name)
print ("With the ID: " + client.user.id)
@client.event
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.dumps(f)
await update_data(users, member)
with open('users.json', 'w') as f:
json.loads("users, f")
@client.event
async def on_message(message):
with open('users.json', 'r') as f:
users = json.dumps(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message.channel)
with open('users.json', 'w') as f:
json.loads("users, f")
async def update_data(users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]['experience'] = 0
users[user.id]['level'] = 1
async def add_experience(users, user, exp):
users[user.id]['experience'] += exp
async def level_up(users, user, channel):
experience = users[user.id]['experience']
lvl_start = users[user.id]['level']
lvl_end = int(experience ** (1/4))
if lvl_start < lvl_end:
await client.send_message(channel, '{} has achieved a slightly higher
level of {}, yay'.format(user.mention, lvl_end))
users[user.id]['level'] = lvl_end
loads
および dumps
が逆方向にあり、 load
を使用する必要がありますおよび dump
代わりに(接尾辞s
は、これらの関数が文字列で機能することを意味します。) load
からファイルへ、dump
からファイルへ
users = {}
@client.event
async def on_message(message):
# No need to load the dictionary, our copy is the most correct
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message.channel)
with open('users.json', 'w') as f:
json.dump(users, f)
@client.event
async def on_ready():
print ("Ready when you are xd")
print ("I am running on " + client.user.name)
print ("With the ID: " + client.user.id)
# Load the json just once, when the bot starts
global users
with open('users.json') as f:
try:
users = json.load(f)
except:
users = {}