首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >试图制作一个行会Config - Discord.PY

试图制作一个行会Config - Discord.PY
EN

Stack Overflow用户
提问于 2020-07-01 05:05:46
回答 1查看 3.2K关注 0票数 1

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

如果有帮助的话,我正在使用discord.py重写。

对于我的命令,我有以下几点:

代码语言:javascript
运行
复制
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))

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

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

该命令需要具有交互性,并且需要设置命令、通知、自动响应、支持系统等的特定通道。

-编辑--

这是我的主要bot.py文件。这就是我用来装齿轮的东西。我也在修改前缀命令,所以暂时忽略这部分.

代码语言:javascript
运行
复制
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文件的代码:

代码语言:javascript
运行
复制
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。

代码语言:javascript
运行
复制
{
    "GUILD ID": [
        CHANNEL_ID1,
        CHANNEL_ID2,
        CHANNEL_ID3        
    ]
}

下面是我对如何格式化{guild.id}.json文件的基本想法,如果它能工作的话:

代码语言:javascript
运行
复制
{
  "Guild Prefix":  "CUSTOM PREFIX",
  "Announce Channel": "CHANNEL ID",
  "Logs Channel": "CHANNEL ID",
  "Levels Channel": "CHANNEL ID"
}
EN

回答 1

Stack Overflow用户

发布于 2020-11-09 11:48:49

用于读取值和反序列化

与open一起使用(“filename”,"r")作为_data: data = _data user = datauser

用于写入值和序列化

#序列化数据= {'people':{'name':'Scott','name2':'billy','name3':‘jack’} dumped = json.dumps( data,indent=4) #写入json文件,并使用_data(“filename”,"w")作为_data:_data.write(倒置)

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

这样你就可以像..。

代码语言:javascript
运行
复制
#define guild
guild = ....

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

希望能奏效:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62670054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档