Inj3ct0r
Inj3ct0r

Reputation: 65

discord.py - Is possible save member commands?

Is possible to save member commands in a channel or file? When a member execute a bot command to send in channel:

member test executed !testcmd

Upvotes: 0

Views: 82

Answers (1)

Jabro
Jabro

Reputation: 538

Yes, both are possible. Here you have an example in where the logs are sent to a guild channel. Adapting the code to save them in a file should be easy.

The idea is quite simple, can be executed in 3 steps:

  1. Define the channel where you want the logs to be sent to
  2. Define a function to send the logs to the channel you chose
  3. At the end of each command, call the function defined in step 2
import discord
from discord.ext import commands

# Change intents if needed
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
TOKEN = "Your Token"

guild = None        # The guild you want your bot to send the logs to
channel = None      # The channel of the guild you want your bot to send the logs to
guild_id = 123456789
channel_id = 987654321

@bot.event
async def on_ready():
    global guild, channel, guild_id, channel_id
    await bot.wait_until_ready()
    guild = bot.get_guild(guild_id)
    channel = guild.get_channel(channel_id)
    print("Logged")

# For sending the logs 
async def command_logs(ctx : commands.Context):
    await channel.send(f"member **{ctx.author}** executed **{ctx.command.name}**")

@bot.command(name="test")
async def test(ctx : commands.Context):
    # Your command's code
    await ctx.send("Test")
    # ...

    # Send the logs at the end
    await command_logs(ctx)

bot.run(TOKEN)

Alternatively, you can use the @after_invoke command's decorator to call the function defined in step 2:

@bot.command(name="test")
async def test(ctx : commands.Context):
    # Your command's code
    await ctx.send("Test")
    # ...

@test.after_invoke
async def test_after_invoke(ctx : commands.Context):
    await command_logs(ctx)

Upvotes: 1

Related Questions