【问题标题】:How can you record information for a specific user in discord.py?如何在 discord.py 中记录特定用户的信息?
【发布时间】:2023-03-18 20:47:02
【问题描述】:

我正在设置一个机器人,如果满足特定条件,它会 ping 某人。例如,假设有人在聊天中说“苹果”,则该人想要被 ping。

我正在尝试建立一个系统,如果有人在聊天中键入“!ping apple”,只要聊天中出现“apple”一词,他们就会收到通知。但是,我想不出一种方法来根据用户自动将此信息存储在列表中。我希望能够做到以下几点:

  1. 用户说“!ping苹果”

  2. 机器人将“apple”附加到分配给该人的列表中。

  3. 如果聊天中说“苹果”,机器人会 ping 那个人。

有没有办法做到这一点(最好是有效的)?我尝试的一种策略是基于this post about renaming strings to variables (它采用用户的@,切断@ 和#xxxx,删除空格,然后将生成的字符串转换为包含列表的变量) 但是这可能会产生一堆错误,而且不是 Python 的。

一种可能有效的策略是说“!ping ”,但这似乎我会遇到同样的问题;有一个字符串而不是一个变量。

【问题讨论】:

    标签: python command user-input discord.py


    【解决方案1】:

    有多种方法可以做到这一点,但我个人会这样做:

    为了简单起见,我假设您使用的是内置的 ext.commands.cog 模块。如果您使用不同的内核,情况会略有不同。

    有一个配置要么内置到你的核心中,要么在你的 cog 本地。我将使用方法self.get_settings() 作为获取字典的方法。您还需要一个方法来保存设置,例如self.save_settings()

    @commands.command()
    async def ping(self, ctx: commands.Context, word: str):
       settings = self.get_settings()
       settings[word] = ctx.author.id  #gets the user id from the person
       self.save_settings(settings)
    

    那么你的听众会是这样的

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):
       settings = self.get_settings()
       if message.content in settings:
          await message.channel.send(f'<@{settings[message.content]}>')
    

    一个简单的设置管理器可以是:(你需要导入json btw)

    def get_settings():
       with open('settings.json', 'r') as file:
          return json.load(file)
    
    def save_settings(settings):
       with open('settings.json', 'r') as file:
          json.dump(settings, file)
    

    这是最简单的方法。

    编辑:设置管理器的实现

    【讨论】:

    • 我很困惑。当我尝试使用 get_settings() 时,我收到错误消息“AttributeError: 'ping' object has no attribute 'get_settings'”,我认为这是由于我使用不当造成的。顺便说一句,我想我正在使用 ext.commands.cog 模块;我之前编写了“从 discord.ext 导入命令”(然后将 @commands.command() 位放入一个类等)。
    • 对不起,如果我不清楚,您需要自己制作 get_settings() 函数。
    • 您还需要一个 save_settings() 函数。抱歉,我忘记添加了。
    • 老实说,如果您愿意,您不能创建这样的功能而只使用 json 的加载和转储。
    • 不过,这就是我感到困惑的部分;我将如何获取和保存特定用户的设置(即我应该如何处理 get_settings() 和 save_settings() )? JSON 有点接近我想要的,我不能使用键值对与另一个列表进行交叉引用。
    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 2021-04-12
    • 2010-09-06
    • 2020-09-13
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多