How to store server and user ids in json file with discord.py

十年热恋 提交于 2020-08-10 20:31:02

问题


Yo, so I'm trying to give the bot I'm building more useful configuration per server. But I use channel name right now because I don't know how to automatically get all server and channel ids and store them in a json. My question is, how would i use json to implement a guild config and make the bot automatically fill out the ids of each guild and channel it is in so as to code my bot to use that to set up the channels the bot uses?

My bot is built using discord.py rewrite if it helps.

--EDIT--

Here is bot.py file with the functions I'm using for my config.json in it.

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

with open("./data/config.json", "r") as configjsonFile:
    configData = json.load(configjsonFile)
    TOKEN = configData["DISCORD_TOKEN"]

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.command(name="Prefix", aliases=["prefix", "setprefix"], hidden=True)
@commands.has_permissions(manage_guild=True)
async def _prefix(ctx, new_prefix):
    msg = ctx.message
    guild = ctx.guild
    prefixes[msg.guild.id] = new_prefix
    gold = discord.Color.dark_gold()
    with open("./data/config.json", "w") as f:
        json.dump(prefixes, f, indent=4)
        c_prefix = (f"""```css\n{new_prefix}```""")
        for channel in guild.channels:
            if str(channel.name) == "💼log":
                embed = discord.Embed(color=gold, timestamp=msg.created_at)
                embed.set_author(name="Prefix Changed", icon_url=client.user.avatar_url)
                embed.add_field(name="New Prefix", value=c_prefix, inline=False)
                embed.set_thumbnail(url=client.user.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await msg.add_reaction(emoji="✅")
                await channel.send(embed=embed)


@_prefix.error
async def _prefix_error(ctx, error):
    guild = ctx.guild
    msg = ctx.message
    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, timestamp=msg.created_at)
        embed.set_author(name="Command Failed", icon_url=self.client.user.avatar_url)
        embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
        embed.set_thumbnail(url=client.user.avatar_url)
        embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
        await msg.add_reaction(emoji="⚠")
        await msg.author.send(embed=embed)
    elif isinstance(error, commands.MissingPermissions):
        embed = discord.Embed(color=red, timestamp=msg.created_at)
        embed.set_author(name="Access denied", icon_url=self.client.user.avatar_url)
        embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
        embed.set_thumbnail(url=client.user.avatar_url)
        embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
        await msg.add_reaction(emoji="⛔")
        await msg.author.send(embed=embed)


client.run(TOKEN)

I'm wanting to add the function to this if possible.

This is my config.json if it helps

{
    "DISCORD_TOKEN": "DISCORD BOT TOKEN",
    "OWNER ID": "DISCORD ID",
    "DEV ID": "DISCORD ID",
    "API KEYS": {
        "API 1 TOKEN": "API TOKEN",
        "API 1 SECRET": "API SECRET",
        "API 2 TOKEN": "API TOKEN",
        "API 2 SECRET": "API SECRET",
        "API 3 TOKEN": "API TOKEN",
        "API 3 SECRET": "API SECRET",
        "API 4 TOKEN": "API TOKEN",
        "API 4 SECRET": "API SECRET"
    },
    "383742083955032064": "r?"
}

The API Token parts are not being used rn, they are being reserved for a future update.

---EDIT---

Thanks so much for the answer provided by Smoliarick

This is my slightly edited version if anyone else wants to use it. Editing it into the main post so people will be able to see it easier =)

@client.event
async def on_ready():
    guilds = client.guilds
    data = {}
    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)

回答1:


Try this solution (minimal example). In result you will have json file where key is guild.id and value is list of channel.id in this guild:

@bot.event
async def on_ready():
    guilds = bot.guilds
    data = {}
    for guild in guilds:
        data[guild.id] = []
        for channel in guild.channels:
            data[guild.id].append(channel.id)
    with open("result.json", "w") as file:
        json.dump(data, file)

result.json:

{"guild_id1": [channel_id1, channel_id2, channel_id3, channel_id4, channel_id5]}


来源:https://stackoverflow.com/questions/62605586/how-to-store-server-and-user-ids-in-json-file-with-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!