Reputation: 223
I am currently attempting to make a bot that allows members to set specific keywords that the bot then checks for in the server (over a period of time). If the bot detects that keyword in a message (via another bot/webhook only) it alerts the user who set that keyword.
Basically what I wish to do is something like this scenario:
Member 1 --->
!setkeyword new link
(bot then sets the keywords for member 1 specifically as "new link")
!listkeywords
(bot returns the word/phrase "new link")
Member 2 --->
!setkeyword new shoe
(bot then sets the keywords for member 1 specifically as "new shoe")
!listkeywords
(bot returns the word/phrase "new shoe")
The best that I came to was using a dictionary and a list. The key to the dictionary was the user id of the member who sets the keyword and the list contains the keyword.
Variation 1: dictt = {}
@bot.command()
async def add(ctx,keyword):
listy = []
listy.append(keyword)
dictt[ctx.author.id] = listy
Variation 2:
dictt = {}
listy = []
@bot.command()
async def add(ctx,keyword):
listy.append(keyword)
dictt[ctx.author.id] = listy
Variation 1: This resulted in a new list being made every time a user messaged the bot. Meaning for each unique user only one keyword was in the list. So if a user tried to add multiple keywords only the most recent one was added to the list
Variation 2: This resulted in keywords from unique users being added to the same list, meaning each user could add multiple keywords but they weren't unique for each user.
How can I achieve each unique user having their own unique list and still being able to add multiple keywords to it?
Upvotes: 0
Views: 200
Reputation: 302
My advice would be a save file. Setting a variable would be destroyed at the shutdown or restart or crash...
filepath = os.path.dirname(os.path.realpath(__file__))
config = configparser.ConfigParser()
config.optionxform = str
try:
config.read(f'{filepath}/data/keywords.cfg')
user1 = config['User1'] #This might be an Idea if you have every user stored in vars
except Exception as error:
print(f" -- ERROR : File not detected.\n{error}")
quit()
#Or use it like this
@bot.command()
async def add(ctx,keyword):
keywordlist = config.items(ctx.message.user.id, raw=True)
keywordlist.append(keyword)
config[ctx.message.user.id] = dict(keywordlist)
@bot.command()
async def list(ctx):
keywordlist = config[ctx.message.user.id]
await ctx.send(keywordlist)
The file would look like that :
[123456789]
FirstKeyword
AnotherKeyWord[123789456]
Wow
Such
Code ...
Upvotes: 1
Reputation: 116
Have a global dict
and check if the user's id exists before appending, if not create a new list with the new word.
memory = {}
def add(id, word):
if id in memory.keys():
memory[id].append(word)
else:
memory[id] = [word]
Upvotes: 1