【问题标题】:Per server prefixs每个服务器前缀
【发布时间】:2019-01-25 17:03:34
【问题描述】:

我想知道如何让我的机器人连接到的每台服务器都设置自己的前缀。我正在使用带有 Commands ext 的异步版本的 dpy。 我假设您会将前缀和服务器名称存储在 .json 文件中,但我不知道您将如何编写它们或检查文件。

谢谢

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    您可以使用动态命令前缀来做到这一点。编写一个函数或协程,接受 BotMessage 并为该消息输出适当的前缀。假设您有一个 JSON 的服务器 ID 前缀:

    { 
      "1234": "!",
      "5678": "?"
    }
    

    您可以将该 json 加载到字典中,然后在该字典中查找服务器 ID。下面我还包括一个默认前缀,但您也可以为没有特定前缀的服务器提出 CommandError 或其他内容。

    from discord import commands
    import json
    
    with open("prefixes.json") as f:
        prefixes = json.load(f)
    default_prefix = "!"
    
    def prefix(bot, message):
        id = message.guild.id
        return prefixes.get(id, default_prefix)
    
    bot = commands.Bot(command_prefix=prefix)
    
    ...
    

    【讨论】:

    • 使用它会给我这个错误:C:\Users\Tims Laptop>"C:\Users\Tim\Desktop\Nami Bot\Bot\Nami.py" Traceback (most recent call last): File "C:\Users\Tims Laptop\Desktop\Nami Bot\Bot\Nami.py", line 16, in <module> prefixes = json.load("prefixes.json") File "C:\Users\Tim\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 296, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read' Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x04480FF0>
    • 我的错误。尝试一下我刚刚所做的更改
    • 这行得通,谢谢!我将如何编写前缀,因为我知道如何编写,但如果它需要在括号 } 之前,并且如果他们更改服务器前缀,则需要覆盖它。编辑:当我更改文件中的服务器前缀时,我必须重新启动机器人才能使其生效?
    • 我该如何为所有服务器设置默认前缀?
    • 请注意,message.server.id 已替换为 message.guild.id
    【解决方案2】:

    迟到的答案,但对于那些也在寻找这个的其他人,您可以使用get_prefix 函数。

    它与 Patrick Haugh 的版本非常相似,但可能因为不同的 discord 库版本而略有不同?

    prefixes = ['.','!','s.','k!']
    ser_pref={'server id':['.',',']}
    def get_prefix(bot, msg):
        if msg.guild.id in ser_pref:
            return commands.when_mentioned_or(*ser_pref['server id'])
    
    
        return commands.when_mentioned_or(*prefixes)(bot, msg)
    
    bot = commands.Bot(command_prefix=get_prefix)
    

    您可以稍后通过将其他服务器的选项添加到 dict 来创建命令以允许更多自定义服务器前缀到其他服务器

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多