DEV Community

Hamza Hesham
Hamza Hesham

Posted on

4 2

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.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (1)

Collapse
 
mohafarag11 profile image
moha farag

Cool

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

World's Largest Hackathon: Building Conversational Video Agents with Tavus and Bolt

With Tavus + Bolt, you can easily build real-time conversational AI apps that see, hear, and speak, just like humans. You won’t want to miss it!.

Tune in to the full event

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️