我正在使用discord.py库来制造一个不和谐的机器人,就像一张数字试卷。但是,我需要添加一个论点(或主题),使机器人为该主题发送特定的试卷,就像q!testpaper english将发送英语试卷一样。
这是我现在的代码,它在Cog中
from discord.ext import commands
class MyCog(commands.Cog):
@commands.command()
async def testpaper(self, ctx):
testpaper = open("./testpaper.txt", "r").read()
await ctx.send(f'Good luck taking the test!')
await ctx.author.send(testpaper)发布于 2020-07-29 09:21:33
要获得其他参数,只需在函数调用中传递它们。使用只使用关键字的表示法来匹配函数调用后传递的整个字符串(了解更多的这里)。
您还忘了在打开文件"./testpaper.txt"之后关闭它。这就是为什么在Python中打开文件的最好方法是使用with open(...) as ...语法。
我建议使用JSON文件来存储测试。下面是一个示例:
testpaper.json
{
"english": "PUT TESTPAPER HERE",
"math": "PUT OTHER TESTPAPER HERE",
...
}然后访问一个特定的测试文件:
import discord, json
from discord.ext import commands
class MyCog(commands.Cog):
@commands.command()
async def testpaper(self, ctx, *, subject=None):
if not subject:
await ctx.send("Error: please input subject!")
return
subject = subject.lower() # Lower-case only
with open("./testpaper.json") as f:
content = json.load(f)
try:
paper = content[subject]
except KeyError:
await ctx.send("No paper named " + subject)
return
await ctx.send(f"Good luck taking the test!")
await ctx.author.send(paper)https://stackoverflow.com/questions/63146719
复制相似问题