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")
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")
You can find the full code in here
Top comments (1)
Cool