通过Discord机器人为每个人设置唯一的关键字

时间:2019-01-21 04:33:55

标签: python python-3.6 discord.py-rewrite

我目前正在尝试制作一个机器人,该机器人允许成员设置特定的关键字,然后由该机器人在服务器中检查(一段时间)。如果漫游器(仅通过另一个漫游器/ webhook)在消息中检测到该关键字,它将提醒设置该关键字的用户。

基本上我想做的就是这种情况:

成员1 --->

!setkeyword新链接

(然后漫游器将成员1的关键字专门设置为“新链接”)

!listkeywords

(机器人返回单词/短语“新链接”)


成员2 --->

!setkeyword新鞋

(然后,漫游器将成员1的关键字专门设置为“新鞋”)

!listkeywords

(机器人返回单词/词组“ new shoe”)

我遇到的最好的事情是使用字典和列表。字典的关键字是设置关键字的成员的用户ID,列表中包含关键字。

变化1:     dictt = {}

@bot.command()
async def add(ctx,keyword):
    listy = []
    listy.append(keyword)
    dictt[ctx.author.id] = listy

变化2:

 dictt = {}
 listy = []
 @bot.command()
 async def add(ctx,keyword):

    listy.append(keyword)
    dictt[ctx.author.id] = listy

变化1:每次用户向机器人发送消息时,都会产生一个新列表。对于每个唯一用户而言,列表中只有一个关键字。因此,如果用户尝试添加多个关键字,则只会将最新关键字添加到列表中

变化2:这导致来自唯一身份用户的关键字被添加到同一列表中,这意味着每个用户可以添加多个关键字,但并不是每个用户都唯一。

如何使每个唯一用户拥有自己的唯一列表,并且仍然能够向其中添加多个关键字?

2 个答案:

答案 0 :(得分:1)

拥有一个全局dict,并在追加之前检查用户ID是否存在,如果没有,请使用新单词创建新列表。

memory = {}

def add(id, word):
    if id in memory.keys():
        memory[id].append(word)
    else:
        memory[id] = [word]

答案 1 :(得分:1)

我的建议是保存文件。设置变量将在关机,重新启动或崩溃时被破坏...

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)

文件如下所示:

  

[123456789]
  FirstKeyword
  另一个关键字

     

[123789456]
  哇
  这样的
  代码...