Random Account
Random Account

Reputation: 15

discord.py trying to set up a moderation log channel

So I'm trying to set up a log channel where it will post a message in that whenever someone gets kicked. At the moment I'm storing it in a json file, but i cant get it tow work. Does anyone have the code? Here's mine:

with open('log_channels.json', 'r') as f:
      log_channels = json.load(f)

@client.command()
@commands.has_permissions(administrator = True)
async def modlog(ctx, channel = None):
  log_channels[str(ctx.guild.id)] = channel.split()
  with open('log_channels.json', 'w') as f:
    json.dump(log_channels, f)
  await ctx.send(f'Mod log set to {channel}')

@client.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason = None):
 await member.kick(reason = reason)
 await ctx.send(embed=discord.Embed(title=f'{member} has been kicked.', color= 0xFF8633))
 guild = ctx.guild
 log_channels.get((guild.id) ('0'))
 print (log_channels)
 channel = client.get_channel(log_channels)
 await channel.send(f"test")

Upvotes: 0

Views: 475

Answers (1)

MrSpaar
MrSpaar

Reputation: 3994

Your error comes from this line:

log_channels.get((guild.id) ('0'))

And more precisely, from (guild.id) ('0'), which is equivalent to 123456789012345678('0') and is impossible.

What you probably meant to do is this:

@client.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason = None):
    await member.kick(reason = reason)
    await ctx.send(embed=discord.Embed(title=f'{member} has been kicked.', color= 0xFF8633))

    channel_id = log_channels.get(str(ctx.guild.id), '0')
    channel = client.get_channel(channel_id)

    await channel.send(f"test")

NB: json dict keys must be strings, so you need to get str(ctx.guild.id).
Also, if log_channel equals '0', channel will be None and channel.send() will raise an error.

What I would recommend doing is this:

@client.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason = None):
    await member.kick(reason = reason)
    await ctx.send(embed=discord.Embed(title=f'{member} has been kicked.', color= 0xFF8633))

    if str(ctx.guild.id) in logs_channels:
        channel = client.get_channel(log_channels[str(ctx.guild.id)])
        await channel.send(f"test")
    else:
        # Not mandatory, you can remove the else statement if you want
        print('No log channel')

Upvotes: 1

Related Questions