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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
mohafarag11 profile image
moha farag

Cool

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more