简体   繁体   中英

How to save a user's message and save it to a file

I'm new with discord bots and I wanted to make a command where you could set a description in a server so it would show up when you use a user info command , but I haven't found how to save the text of the set description command to a file and show it later in the user info command.

Anyone knows? Thank you <3

try this discord bot I made here: (change last line of code to your bot token) You can type the command into a text channel the bot can access: /desc My name is Jimmy, I like pizza.

Then try /userinfo @Jimmy-- Or another user of which you want to see their description.

It doesn't support emojis unfortunately, but it should work good enough.

Before starting the app, you need to make a folder called "userdescriptions" in the same directory as your python script.

Hope this helps give you an idea on how to save files, read files and integrate them with discord (:

import discord
import os

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.content.startswith("/desc"):
        if (message.content[5:].lstrip().replace(" ", "") == "" or message.content[5:].lstrip() == "delete" or message.content[5:].lstrip() == "remove"):
            if (os.path.exists(os.path.join(os.getcwd(), "userdescriptions", str(message.author.id) + ".desc.txt"))):
                os.remove(os.path.join(os.getcwd(), "userdescriptions", str(message.author.id) + ".desc.txt"))

                await message.author.send("Your user description has been removed.")
            else:
                await message.author.send("Unable to remove your user description, because you don't have one.")
        else:
            with open(os.path.join(os.getcwd(), "userdescriptions", str(message.author.id) + ".desc.txt"), "w") as descriptionFile:
                descriptionFile.write(message.content[5:].lstrip())

            await message.author.send("Your user description has been uploaded.")
    if message.content.startswith("/userinfo <@"):
        userId = int(message.content.split(" ")[1][2:-1])

        descriptionPath = os.path.join(os.getcwd(), "userdescriptions", str(userId) + ".desc.txt")

        if (os.path.exists(descriptionPath)):
            with open(descriptionPath) as descriptionFile:
                await message.channel.send("User Description: ```" + descriptionFile.read() + "```")
        else:
            await message.author.send("That user does not have a description.")

client.run("DISCORD BOT TOKEN")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM