不和谐让机器人在被提及时做出回应,但带有单独的行会集前缀 [英] Discord py Getting bot to respond when mentioned but with individual guild set prefixes

查看:18
本文介绍了不和谐让机器人在被提及时做出回应,但带有单独的行会集前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有我的前缀设置,这样每个公会都可以通过执行一个命令来单独更改它。 我希望能够提到机器人,并且它使用";响应。我的前缀是:";,但也响应使用set前缀调用的命令。 当前如果我添加WHEN

def get_prefix(client, message):
  with open('prefixes.json', 'r') as f:
    prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

def Mentioned_prefix(client, message):
    prefix = get_prefix(client.message)
    return commands.when_mentioned_or(f'{prefix}')

client = commands.Bot(command_prefix = Mentioned_prefix, intents=intents)

@client.event
async def on_guild_join(guild):
  with open('prefixes.json', 'r') as f:
    prefixes = json.load(f)
    prefixes[str(guild.id)] = '%'
    with open('prefixes.json', 'w') as f:
      json.dump(prefixes, f, indent=4)
       
@client.command()
@commands.has_permissions(administrator=True)
async def setprefix(ctx, prefix):
  with open('prefixes.json', 'r') as f:
    prefixes = json.load(f)
    prefixes[str(ctx.guild.id)] = prefix
    with open('prefixes.json', 'w') as f:
      json.dump(prefixes, f, indent=4)
      await ctx.send(f'Prefix is now: {prefix}')

@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        prefix = get_prefix(client, message)
        await message.channel.send(f"Prefix is:' {prefix} '")

推荐答案

您应该创建一个单独的函数来获取公会的前缀。您可以检查您的‘prefixes.json’文件中是否有公会的id,然后返回此信息。有关详细说明,请参阅下面的代码。

def prefix_check(guild):
    # Check if this is a dm instead of a server
    # Will give an error if this is not added (if guild is None)
    if guild == None:
        return "!"
    try:
        # Check if the guild id is in your 'prefixes.json'
        with open('prefixes.json', 'r') as f:
            prefixes = json.load(f)
            p = prefixes[str(guild.id)]
    except:
        # Otherwise, default to a set prefix
        p = "!"
    # If you're confident that the guild id will always be in your json,
    # feel free to remove this try-except block

    return p

# on_message event
@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        # This is how you call the prefix_check function. It takes a guild object
        await message.channel.send(f"My prefix is {prefix_check(message.guild)}")
    
    # Don't forget to process, otherwise your commands won't work!
    await client.process_commands(message)

# In a command (using ctx), do use prefix_check(ctx.guild) to get the guild's prefix

这篇关于不和谐让机器人在被提及时做出回应,但带有单独的行会集前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆