简体   繁体   中英

How can I define a log-channel?

I am trying to read a channel ID from a JSON. With this you should be able to determine a channel, a kind of log, where the bot messages should be sent. However, I unfortunately have no idea how to get this ID for a single guild from the JSON.

My approaches:

async def logchannel():
    with open("src/logchannel.json", "r") as f:
        lchannel = json.load(f)

        return lchannel

(Says at the top of the class)

    @commands.command(hidden=True)
    @commands.guild_only()
    @commands.has_permissions(manage_messages=True)
    async def setlog(self, ctx, channel: str):
        """Changes the log channel"""
        with open('src/logchannel.json', 'r', encoding='utf-8') as fp:
            log_channel = json.load(fp)

        try:
            log_channel[f"{ctx.channel.id}"] = channel
        except KeyError:
            new = {ctx.channel.id: channel}
            log_channel.update(new)

        await ctx.send(f "Channel set to: `{channel}`")

        with open('src/logchannel.json', 'w', encoding='utf-8') as fpp:
            json.dump(log_channel, fpp, indent=2)

Should then be the specified channel/always update itself.

    @commands.command()
    async def cdel(self, ctx, channel: discord.TextChannel):
        with open('src/logchannel.json', 'r', encoding='utf-8') as fp:
            log_channel = json.load(fp)
        await channel.delete()
        await log_channel.send(f "**Successfully deleted channel `{channel}`!**")

Which gives me the obvious error AttributeError: 'dict' object has no attribute 'send' . I probably have the error there, but don't see it/it doesn't work at all the way I want.

To put it in a nutshell: I want the user to be able to choose his log-channel the bot sends like all the ban messages etc. The user itself can always change the channel by command. The only problem I now have is that the bot gives me the error above as I am not requestion the channel in the right way out of the JSON.

EDIT: This is how my JSON file looks like:

{
  "811573570831384638": "811578547751616532",
  "811623743959990295": "811573570831384638"
}

First number is the channel ID the command was executed in and the second key is the defined mod-log channel.

json.load(fp) gets you the whole json file as dictionary . You should get the channel id from it.

@commands.command(hidden=True)
@commands.guild_only()
@commands.has_permissions(manage_messages=True)
async def setlog(self, ctx, channel: discord.TextChannel):
    """Changes the log channel"""
    with open('src/logchannel.json', 'r', encoding='utf-8') as fp:
        log_channel = json.load(fp)

    try:
        log_channel[str(ctx.guild.id)] = channel.id
    except KeyError:
        new = {str(ctx.guild.id): channel.id}
        log_channel.update(new)

    await ctx.send(f"Channel set to: `{channel}`")

    with open('src/logchannel.json', 'w', encoding='utf-8') as fpp:
        json.dump(log_channel, fpp, indent=2)

With a little bit edit in your code, you can use this command to change log channel. You just have to mention the channel you want to make the new log channel. It will save the id of the guild where the command is used and the mentioned channel as key and value.


When you want to send a message to this channel, you have to use guild.get_channel() or discord.utils.get() . Because you need a discord.TextChannel instance in order to send message to this channel.

@commands.command()
async def cdel(self, ctx, channel: discord.TextChannel):
    with open('src/logchannel.json', 'r', encoding='utf-8') as fp:
        log_channel = json.load(fp)
    await channel.delete()
    log_c = ctx.guild.get_channel(log_channel[str(ctx.guild.id)])
    # Or you can use:
    # log_c = discord.utils.get(ctx.guild.text_channels, id=log_channel[str(ctx.guild.id)])
    await log_c.send(f"**Successfully deleted channel `{channel}`!**")

If you want to update the log channel ID when the current log channel is deleted, you can use the on_guild_channel_delete event to check it.

@client.event
async def on_guild_channel_delete(channel):
    with open('src/logchannel.json', 'r', encoding='utf-8') as fp:
        log_channel = json.load(fp)
    if channel.id in log_channel.values():
        values = list(log_channel.values())
        keys = list(log_channel.keys())
        log_channel[keys[values.index(channel.id)]] = <channel id>
        with open('src/logchannel.json', 'w', encoding='utf-8') as fpp:
            json.dump(log_channel, fpp, indent=2)

You have to put a backup channel id between <channel id> in case of you delete the log channel. So if you delete the log channel, it will automatically changes it with this backup id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM