【问题标题】:Trying to Make a Guild Config - Discord.PY尝试制作公会配置 - Discord.PY
【发布时间】:2020-07-01 05:05:46
【问题描述】:

好的,我正在尝试为我的机器人构建一个全局配置。我已经实现了一个guilds.json 文件,它存储了它所在的每个公会的频道ID和公会ID。我想做的是制作一个配置命令,允许每个公会指定在他们的公会中允许哪些命令并使用guilds.json 文件以指定允许它们进入的通道。

如果有帮助,我正在使用 discord.py rewrite。

我有这个命令:

import discord
from discord.ext import commands
import json
import os
import sys
import discord.utils

class Config(commands.Cog):
    def __init__(self, client):
        self.client = client

    with open("./data/guilds.json") as f:
        json.load(f)

     # Here is a base for my config command.
    @commands.command(name="Config", aliases=["config", "setup", "Setup", "settings", "Settings"])
    @commands.guild_only()
    async def _config(self, ctx, guild):
        red = discord.Color.dark_red()
        cli = self.client.user
        response1 = ("...")
        css1 = str(f"""```css\n{response1}```""")
        for channel in guild.channels:
            if str(channel.id) not in "./data/guilds.json":
            return
        embed = discord.Embed(color=red)
        embed.set_author(name=cli.display_name, icon_url=cli.avatar_url)
        embed.add_field(name="First Time Config", value=css1, inline=False)
        embed.set_thumbnail(url=cli.avatar_url)
        embed.set_footer(text=guild.name, icon_url=guild.icon_url)
        await ctx.send(embed=embed)
        # some sort of code to create a guild json fil to store the config in here




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

我的问题是我不知道如何构建 setup 命令本身。

我希望它为每个公会创建一个单独的{guild_id}.json 文件,以便存储公会的配置。

命令需要是交互式的,需要用于设置命令、公告、自动回复、支持系统等的特定渠道。

--编辑--

这是我的主要bot.py 文件。这是我用来加载我的齿轮的。我也在对前缀命令进行更改,所以暂时忽略该部分...

import discord
from discord.ext import commands
import os
import json


with open("./data/config.json") as f:
    prefixes = json.load(f)
    default_prefix = "r?"


def prefix(client, message):
    id = message.guild.id
    return prefixes.get(id, default_prefix)


client = commands.Bot(command_prefix=prefix)
client.remove_command('help')

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

@client.event
async def on_ready():
    guilds = client.guilds
    data = {}
    cli = client.user
    gold = discord.Color.dark_gold()
    for guild in guilds:
        data[guild.id] = []
        for channel in guild.channels:
            data[guild.id].append(channel.id)
    with open("./data/guilds.json", "w") as file:
        json.dump(data, file, indent=4)
        print(f"A guild file has been created for {guild.name}:{guild.id}.")

@client.command(name="Prefix", aliases=["prefix", "setprefix"], hidden=True)
@commands.has_permissions(manage_guild=True)
async def _prefix(ctx, new_prefix):
    guild = ctx.guild
    msg = ctx.message
    prefixes[msg.guild.id] = new_prefix
    cli = client.user
    gold = discord.Color.dark_gold()
    with open("./data/config.json", "w") as f:
        json.dump(prefixes, f, indent=4)
        await msg.add_reaction(emoji="✅")


@_prefix.error
async def _prefix_error(ctx, error):
    guild = ctx.guild
    msg = ctx.message
    cli = client.user
    red = discord.Color.dark_red()
    e_1 = str("""```css\nPlease pass in all required arguments.```""")
    e_2 = str("""```css\nYou do not have permission to use this command.```""")
    if isinstance(error, commands.MissingRequiredArgument):
        embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
        embed.set_author(name="Command Failed", icon_url=cli.avatar_url)
        embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
        embed.set_thumbnail(url=cli.avatar_url)
        embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
        await msg.send(embed=embed)
    elif isinstance(error, commands.MissingPermissions):
        embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
        embed.set_author(name="Access denied", icon_url=cli.avatar_url)
        embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
        embed.set_thumbnail(url=cli.avatar_url)
        embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
        await msg.send(embed=embed)


client.run(str(os.environ.get('BOT_TOKEN')))

这是我的Events.py 文件,其中包含guilds.json 文件的代码:

import discord
from discord.ext import commands
from discord import Activity, ActivityType
from discord.utils import find
import os
import json
import random

class Events(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener(name="on_ready")
    async def _on_ready_1(self):
        cli = self.client.user
        data = {}
        for guild in self.client.guilds:
            data[guild.id] = []
        for channel in guild.channels:
                data[guild.id].append(channel.id)
        with open("./data/guilds.json", "w") as file:
            json.dump(data, file, indent=4)
        await self.client.change_presence(activity=discord.Streaming(name=f"r?help | in {len(self.client.guilds)} servers", url="https://www.twitch.tv/discord"))
        print(" ")
        print("License")
        print(" ")
        print("Copyright (c) Joshua Lewis")
        print(" ")
        print("Permission is hereby granted, free of charge, to any person obtaining a copy")
        print("of this software and associated documentation files (the Software), to deal")
        print("in the Software without restriction, including without limitation the rights")
        print("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell")
        print("copies of the Software, and to permit persons to whom the Software is")
        print("furnished to do so, subject to the following conditions:")
        print(" ")
        print("The above copyright notice and this permission notice shall be included in all")
        print("copies or substantial portions of the Software.")
        print(" ")
        print("THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR")
        print("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,")
        print("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE")
        print("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER")
        print("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,")
        print("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE")
        print("SOFTWARE.")
        print("Connecting to Discord API")
        print("...")
        print("......")
        print(".........")
        print(f"Logged in as : {cli.name}#{cli.discriminator}")
        print("Collecting list of connected guilds")
        print("...")
        print("......")
        print(".........")
        print("Connected Guilds:")
        print(f"{self.client.guilds}")
        print(f"A guild file has been created for {guild.name}:{guild.id}.")


    @commands.Cog.listener(name="on_guild_join")
    async def _on_guild_join_1(self, guild):           
        await guild.create_text_channel("????announcements-and-suggestions")
        await guild.create_text_channel("????log")
        cli = self.client.user
        gold = discord.Color.dark_gold()
        for channel in guild.channels:
            if str(channel.name) == "????announcements-and-suggestions":
                response1 = str(f"""```css\nHello {guild.name}! I am {self.client.user.display_name}. Thank you for inviting me. I hope we have a lot of fun.```""")
                response2 = str("""```css\nTo see what commands I have available type r?help.```""")
                response3 = str("""```css\nIf you want to see how to use my AutoResponder type gethelp.```""")
                embed = discord.Embed(color=gold)
                embed.set_author(name=cli.display_name, icon_url=cli.avatar_url)
                embed.add_field(name="Yo! I'm in!", value=response1, inline=False)
                embed.add_field(name="Check out my Commands", value=response2, inline=False)
                embed.add_field(name="I even have an Auto Responder", value=response3, inline=False)
                embed.set_thumbnail(url=cli.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await channel.send(embed=embed)
                print(f'{cli.display_name} has entered {guild.name}:{guild.id}')

    @commands.Cog.listener(name="on_message_delete")
    async def _on_message_delete_1(self, message):
        ctx = self.client.get_context
        guild = message.author.guild
        author = message.author
        ch = message.channel
        cli = self.client.user
        content = message.content
        orange = discord.Color.dark_orange()
        for channel in guild.channels:
            if str(channel.name) == "????log":
                msg_del = str(f"""```css\n{content}```""")
                aut_name = str(f"""```css\n{author.display_name}```""")
                ch_name = str(f"""```css\n{ch.name}```""")
                embed = discord.Embed(color=orange, timestamp=ctx.message.created_at)
                embed.set_author(name="Message Deleted", icon_url=cli.avatar_url)
                embed.add_field(name=f"Message", value=msg_del, inline=False)
                embed.add_field(name=f"Message Author", value=aut_name, inline=False)
                embed.add_field(name=f"Channel", value=ch_name, inline=False)
                embed.set_thumbnail(url=author.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                message.embed = (content)
                await channel.send(embed=embed)
                print(f'message: {content} by {author.display_name} was deleted in {ch.name}')



    @commands.Cog.listener(name="on_member_join")
    async def _on_member_join_1(self, ctx, member):
        guild = ctx.guild
        cli = self.client.user
        gold = discord.Color.dark_gold()
        user_join = str(f"""```css\n{member} has entered {guild.name}```""")
        for channel in guild.channels:
            if str(channel.name) == "????log":                
                embed = discord.Embed(color=gold)
                embed.set_author(name=cli.display_name, icon_url=cli.avatar_url)
                embed.add_field(name="Use Joined", value=user_join, inline=False)
                embed.set_thumbnail(url=cli.avatar_url)
                embed.set_image(url=member.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await channel.send(embed=embed)

    @commands.Cog.listener(name="on_member_remove")
    async def _on_member_remove_1(self, ctx, member):
        guild = ctx.guild
        cli = self.client.user
        red = discord.Color.dark_red()
        for channel in guild.channels:
            if str(channel.name) == "????log":                
                user_left = str(f"""```css\n{member} has left {guild.name}```""")
                embed = discord.Embed(color=red)
                embed.set_author(name=cli.display_name, icon_url=cli.avatar_url)
                embed.add_field(name="User Left", value=user_left, inline=False)
                embed.set_image(url=member.avatar_url)
                embed.set_thumbnail(url=cli.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await channel.send(embed=embed)




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

这就是我的guilds.json 的格式。我省略了实际的 ID。

{
    "GUILD ID": [
        CHANNEL_ID1,
        CHANNEL_ID2,
        CHANNEL_ID3        
    ]
}

以下是关于格式化{guild.id}.json 文件(如果可行)的基本想法:

{
  "Guild Prefix":  "CUSTOM PREFIX",
  "Announce Channel": "CHANNEL ID",
  "Logs Channel": "CHANNEL ID",
  "Levels Channel": "CHANNEL ID"
}

【问题讨论】:

  • 我正在实现一个与此类似的系统,最好的方法是使用命令扩展和 @check 装饰器。除此之外,这个问题的范围太广了,这个网站更多地是为了解决你在代码中遇到的具体问题
  • 那么我将如何使用检查装饰器来执行此操作?我一直在寻找一种方法来做到这一点,但在任何地方都没有提到如何做到这一点。官方文档对我没有任何意义。通过适当地展示它是如何完成的而不是解释每件事的含义,我会更好地理解它。
  • discordpy.readthedocs.io/en/latest/ext/commands/api.html#checks 就在这里。我不知道你是否使用命令,但它真的很有用
  • 我设法用我之前发布的这个问题的答案制作了guilds.josn 文件:stackoverflow.com/questions/62605586/…
  • 再说一次,这不是我想要的。我正在尝试构建一个公会设置命令,让人们指定使用哪些频道。而不是试图限制仅在一个公会中的频道。我将设置命令的少量内容编辑到我的主要帖子中。我需要构建一个公会设置命令,这样我就可以让命令运行,但是直到我有公会设置命令,检查是无用的。

标签: python-3.x discord.py-rewrite


【解决方案1】:

用于读取值和反序列化

use with open("filename", "r") as _data:
    data = _data
    user = data[user]

用于写入值和序列化

#serialization
data = {'people':[{'name': 'Scott', 'name2': 'billy', 'name3': 'jack'}]}
dumped = json.dumps(data, indent=4)

#writing into json file
use with open("filename", "w") as _data:
    _data.write(dumped)

如果带有filename 的 json 文件不存在,它将在项目文件夹中创建一个具有该名称的 JSON 文件。

所以你可以这样做......

#define guild
guild = ....

#then
use with open(f"{guild}.json", "w") as data:
    data.write(....)
    ...

希望它有效:)

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多