Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 9, 2022 10:51 pm GMT

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 discordfrom discord.ext import commandsclient = commands.Bot(command_prefix="!")@client.eventasync def on_ready():    print("started")

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.eventasync 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}
")#Don't forget to run the botclient.run("Your Token")

You can find the full code in here

Testing the code

Image description

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


Original Link: https://dev.to/oxy_oxide/discordpy-02-not-that-usual-log-bot-the-first-part-16a9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To