discord.py 在 cogs 中使用 JSON?

时间:2021-04-25 04:59:30

标签: python json discord.py

我最近一直在研究一个 Discord 机器人,我所有的命令都在一个 py 文件中。我目前正在尝试为我的机器人实现 cogs,因为我的计划是让它 24/7 并且公开运行,所以如果出现问题,我可以轻松修复它而无需关闭整个机器人(并使脚本本身更干净)和组织)。我对使用 JSON 和 cogs 比较陌生,因此非常感谢任何帮助。

注意 1:我不想传递绝对路径,因为我将在 VPS 上托管此机器人。
注意 2:我的 reports.json 文件在 \cogs 文件夹中,而不是在 \CogTest 文件夹中。

尝试运行它会引发此错误:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\test\CogTest\cogs\warns.py", line 14, in <module>
    class Warns(commands.Cog):
  File "C:\Users\User\Desktop\test\CogTest\cogs\warns.py", line 20, in Warns
    with open('reports.json', encoding='utf-8') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'reports.json'

这是我的警告类示例:

# Imports

import discord
import random
import asyncio
import json
import datetime
from discord.ext import commands
from discord import Permissions
from discord import Intents
from discord.ext.commands import has_permissions
from discord.ext.commands import MissingPermissions
from discord.ext.commands import BucketType

# Class 

class Warns(commands.Cog):

    def __init__(self, client):
        self.client = client

# Bot is online

    @commands.Cog.listener()
    async def on_ready(self):
        print('test running')

# Warn Command

    with open('reports.json', encoding='utf-8') as f:
        try:
            report = json.load(f)
        except ValueError:
            report = {}
            report ['users'] = []


    @commands.command(pass_context=True)
    @commands.has_permissions(ban_members=True)
    async def warn(self, ctx, user:discord.User,*reason:str):
        author = ctx.author
        if user == ctx.author:
            await ctx.send(f"{ctx.message.author.mention}, you can't warn yourself!", delete_after=10.0)
            return
        if not reason:
            await ctx.send(f'{ctx.message.author.mention}, please provide a reason for warning!', delete_after=10.0)
            return
        reason = ' '.join(reason)
        await ctx.send(f'{user.mention} has been warned by **{author.name}**. Reason: ``{reason}``')
        await user.send(f'You have been warned in **{ctx.guild.name}** by **{author.name}**. Reason: ``{reason}``')
        for current_user in report['users']:
            if current_user['name'] == user.name:
                current_user['reasons'].append(reason)
                break
        else:
            report['users'].append({
            'name':user.name,
            'reasons': [reason,]
            })
        with open('reports.json', 'w+') as f:
            json.dump(report,f)

# Warn Error 

    @warn.error
    async def warn_error(self, ctx, error):
        if isinstance(error, MissingPermissions):
            await ctx.send(f"{ctx.message.author.mention}, you don't seem to have the permission to run this command!", delete_after=10.0)
        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(f"{ctx.message.author.mention}, please provide the member's username that you want to warn!", delete_after=10.0)
        if isinstance(error, commands.BadArgument):
            await ctx.send(f"{ctx.message.author.mention}, I couldn't find that member. Are you sure you provided the correct member?", delete_after=10.0)


def setup(client):
    client.add_cog(Warns(client))

这是主要的加载/卸载代码,如果您愿意,可以检查它是否有任何问题

# Imports 

import discord
import random
import asyncio
import json
import datetime
import os
from discord import Permissions
from discord import Intents
from discord.ext import commands
from discord.ext.commands import has_permissions
from discord.ext.commands import MissingPermissions
from discord.ext.commands import BucketType
from os import listdir


client = commands.Bot(command_prefix = "y!")

# Load / Unload

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')

client.run('token here')

0 个答案:

没有答案