DEV Community

Hamza Hesham
Hamza Hesham

Posted on

Discord.py | 02 Not that usual log bot the first part!

Hello, Today we're going to create a discord bot that logs the messages in any server in a text file.
Before going any further please read the first part.

The code

The code is very simple as usual.
As usual let's start by importing discord.py module and defining the client(bot).

#No need to explain this piece of code just read the first part.
import discord
from discord.ext import commands


client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
    print("started")

Enter fullscreen mode Exit fullscreen mode

Then, We are going to use the on_message event.
This event listens to the messages sent in all the servers that the bot is in then executes some code.


@client.event
async def on_message(message):
    if message == "":
        return
    else:
        id = str(message.author)
        #Sorts the message time of creation
        # %d : day of the month (01 to 31)
        # %m : month
        # %Y : year including the century
        # %H : Hour (00 to 23)
        # %M : minute
        # %S : second 

        time = str(message.created_at.strftime("%d-%m-%Y %H:%M:%S"))
        mss = str(message.content)
        #Opening the file in appending mode.
        data = open("data.txt","a")
        #writing the message into the file 
        data.write(f"({time}) {id} : {mss}\n")
#Don't forget to run the bot
client.run("Your Token")
Enter fullscreen mode Exit fullscreen mode

You can find the full code in here

Testing the code

Image description

Image description
Thanks for reading, See you in the next part.

Top comments (1)

Collapse
 
mohafarag11 profile image
moha farag

Cool