Search code examples
pythondiscorddiscord.py

I want to create this command for my discord bot that stores a list of messages that a bunch of users say then have a command to randomly choose them


For more detail I would like to create a command for my bot that takes in messages stores it somewhere like in a new file or something like that and have a new command send a message from that new file. I am wondering if I should use json or make a .txt file.

My Code:

@bot.event
async def on_message(message):
    if message.author.bot:
        return

    if message.content == "echo":
        echomessage = (message.content)
        await message.channel.send(f"{echomessage} has been added to a list of messages")

    await bot.process_commands(message)

@bot.command()
async def echo(ctx):
    await ctx.send(f"{ctx.author.mention} {echomessage[random.randint(0, len(echomessage) - 1)]}")

I know that I have a event I would like to make it a command at some point but if I cant then imma just keep it as it.

Thanks for anyone who takes a shot at helping me! I really appriciate it.


Solution

  • You can simply save it to a file and randomly pick one.

    Using readlines, simply write each word to use into its own line, and a random one will be picked automatically.

    @bot.command()
    async def addword(ctx, *, word: str):
        with open('words.txt', 'a') as f:
            f.write(f'{word}\n')
    
    @bot.command()
    @commands.cooldown(5, 20.0, commands.BucketType.guild)  # Highly recommended, io is precious. You can also keep this file permanently opened and store it in your client at startup.
    async def echo(ctx):
        with open('words.txt') as f:
            await ctx.send(random.choice(f.readlines()))