Home > front end >  discord.py add different str object to different users
discord.py add different str object to different users

Time:05-11

So I'm trying to make a command that adds the name of a song to an user. I just don't understand how I should do that. I tried looking on the dictionary documentations but I couldn't find anywhere how I could append a variable to a certain person. This is my current code altough I think it's completely wrong:

@commands.command()
    async def quote(self, ctx):
        await ctx.send("add your quote")
        msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
        quote = msg.content
        with open('quotes.json', 'r') as f:
            quotes = json.load(f)
        quotes.append(quote)
        with open('quotes.json', 'w') as f:
            json.dump(quotes, f)
        await ctx.send("quote added!")

CodePudding user response:

If you're trying to make it so users can request multiple songs in a queue type fashion I'd create a dictionary, make the key the user id and set the value to an empty list, then append to that list your song of choice.

On the other hand if you prefer one song per user just set the value to the song for the user's id as the key.

This would typically use just casual key assignment for dictionarys.

Example how this would work (assume this is inside your command):

songs = {};

# This code if you'd like multiple songs per user.
songs[ctx.author.id] = [];
songs[ctx.author.id].append("SONG VALUE HERE");

# This code if you'd like one.
songs[ctx.author.id] = "SONG VALUE HERE";

CodePudding user response:

You can use this with a dictionary and track them by ID. Be careful with this, as JSON does not allow you to use integers as keys to anything. Only strings are allowed.

    @commands.command()
    async def quote(self, ctx):
        await ctx.send("add your quote")
        msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
        quote = msg.content
        with open('quotes.json', 'r') as f:
            quotes = json.load(f)

        strid = str(msg.author.id)  # this is necessary for json
        if strid not in quotes.keys():
            quotes[strid] = []
        quotes[strid].append('My quote, or put whatever you need to add in here')

        with open('quotes.json', 'w') as f:
            json.dump(quotes, f)
        await ctx.send("quote added!")

As a sidenote, it's a bad idea to open the file and close it multiple times. Instead, you can try a construct like this, and then you will be spared from opening the file so much:

client = commands.Bot(...)
with open('quotes.json', 'r'):
    client.quotes_data = json.load(f)

@tasks.loop(minutes=3.0)  # adjust this at your liking, or execute it manually
async def save_all():
    with open('quotes.json', 'w'):
        json.dump(client.quotes_data, f)
save_all.start()
  • Related