所以,我在緊急情況下為一個擁有 4k 成員的 RP 服務器制作了一個不和諧的機器人。我的目標是將律師資料庫存盤在一個 json 檔案中,該檔案將托管在我的一臺計算機上進行測驗。這是我的代碼:
import discord
import datetime
from typing_extensions import IntVar
from discord import member
from discord.embeds import Embed
import json
from discord.ext import commands
from discord.colour import Color
import asyncio
#Vars
lawyersdict = {}
prefix = "<"
client = commands.Bot(command_prefix=prefix)
#Misc Stuff
client.remove_command("help")
#Embeds-
#RegEmbed
regembed = discord.Embed (
colour = discord.colour.Color.from_rgb(64, 255, 0),
title = 'Success',
description = 'Successfully registered you in the database as a lawyer!'
)
regembed.set_author(name='GVRP. Co',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
regembed.timestamp = datetime.datetime.utcnow()
#Invalid
factembed = discord.Embed (
colour = discord.colour.Color.from_rgb(255, 64, 0),
title = 'Uh oh',
description = 'Seems like an error occured! Please try again.'
)
factembed.set_author(name='UselessFacts',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
factembed.timestamp = datetime.datetime.utcnow()
#CMDS-
#Register Command
@client.command(aliases=['reg'])
async def register(ctx):
if ctx.author == client.user:
return
else:
if isinstance(ctx.channel, discord.channel.DMChannel):
await ctx.send("Sorry, you cannot use this command in a DM for security reasons.")
else:
channel = await ctx.author.create_dm()
def check(m):
return m.content is not None and m.channel == channel
await channel.send(f"Hello {ctx.author.mention}! Please tell a little bit about yourself! You have 5 minutes. (To cancel the command, type 'cancel')")
await asyncio.sleep(0.3)
descmsg = await client.wait_for('message', check=check, timeout=300)
if descmsg.content == "cancel":
await channel.send(f"Cancelled command!")
else:
await channel.send(f"Almost there! You just need to enter the hiring price! You have 2 minutes. (between 450$ & 50,000$)")
await asyncio.sleep(0.3)
pricemsg = await client.wait_for('message', check=check, timeout=180)
if any(c.isalpha() for c in pricemsg.content):
if any(c.isalpha() for c in pricemsg.content):
await channel.send("Oops, you didnt typed a number! Make sure you didnt typed it without a coma! Please re-send the command.")
else:
def PrcCheck(num: int):
if num <= 50000 and num >= 450:
return True
else:
return False
if PrcCheck(int(pricemsg.content)):
desc = {
f"{str(ctx.author.id)}" : {
"Description" : f"{descmsg.content}",
"Price" : int(pricemsg.content),
"IsActive" : "true"
}
}
jsonobj = json.dumps(desc, indent=4, sort_keys= True)
with open('lawyers.json', mode='w') as outfile:
obj = json.load(json.dump(lawyersdict, outfile))
obj.append(desc)
obj.write(jsonobj, outfile)
await channel.send(embed=regembed)
else:
await channel.send(f"The price you entered is too low or too high! Price entered: ``{pricemsg.content}``. Please re-send the command.")
@client.event
async def on_ready():
print(f"Ready! Logged in as {client.user}")
client.run("Bot Token")
這是編譯器錯誤(Python 3.9):
Ignoring exception in command register:
Traceback (most recent call last):
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\theli\OneDrive\Bureau\Discord Bots\GVRP. Co UtilBot\launcher.py", line 82, in register
obj = json.load(json.dump(lawyersdict, outfile))
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'NoneType' object has no attribute 'read'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'read'
我試圖查看其他帖子,看看是否有解決方案。但這是 2015 年的帖子,并沒有解決我的問題。
我的目標是添加有關輸入資訊并輸入我的命令進行注冊的 Discord 用戶的詳細資訊。
感謝您閱讀這篇文章
uj5u.com熱心網友回復:
obj = json.load(json.dump(lawyersdict, outfile))
您正在使用 的結果json.dump()作為 的引數json.load()。
但json.dump()不回傳任何東西。所以你有效地呼叫了json.load(None).
uj5u.com熱心網友回復:
正如約翰戈登在上面所說的 dump return None 因此你不能加載它。
要繼續您的評論,那么是json.load(outfile)您需要做的,但只是稍后。該檔案是為 w(寫)打開的,并且它當前是一個打開的檔案,因此您可以立即執行此操作,但在 with 陳述句之后,通過io使用with背景關系或僅使用背景關系創建另一個打開呼叫open.
uj5u.com熱心網友回復:
沒關系,我只是發現了錯誤,看了一點之后,我重寫了代碼塊以進行追加!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/392968.html
上一篇:python:如何減少到單行:
