假设我不想将自己限制为单个前缀,而是使用命令将前缀更改为我所使用的每个服务器的任何我想要的前缀。
基本上,首先会有一个默认前缀,例如bl!,如果有另一个带有该前缀的机器人,我可以做类似bl!prefix .... 这将使机器人读取给定的文本文件或 json,根据公会编辑前缀,并与该公会一起工作,并且只与该公会一起工作。
第 1 步 -设置您的 json 文件:首先,您需要制作一个 json 文件。该文件将存储该message.guild.id公会的信息和前缀。在下图中,您将看到添加到多个服务器后的 json 文件。如果您的机器人已经在大量服务器中,您可能需要手动添加它们,然后才能拥有自动系统。

第 2 步 -定义 get_prefix:当您设置discord.py机器人时,您通常会遇到一行代码,说明command_prefix机器人的名称。要拥有自定义前缀,您首先需要定义get_prefix,它将从您之前制作的 json 文件中读取。
def get_prefix(client, message): ##first we define get_prefix
with open('prefixes.json', 'r') as f: ##we open and read the prefixes.json, assuming it's in the same file
prefixes = json.load(f) #load the json as prefixes
return prefixes[str(message.guild.id)] #recieve the prefix for the guild id given
Run Code Online (Sandbox Code Playgroud)
第 3 步 -您的机器人 command_prefix:这是为了确保您的机器人具有前缀。而不是使用的command_prefix = "bl!",您将使用先前定义的get_prefix。
client = commands.Bot(
command_prefix= (get_prefix),
)
Run Code Online (Sandbox Code Playgroud)
第 4 步 -加入和离开服务器:所有这些都是操作prefixes.json。
@client.event
async def on_guild_join(guild): #when the bot joins the guild
with open('prefixes.json', 'r') as f: #read the prefix.json file
prefixes = json.load(f) #load the json file
prefixes[str(guild.id)] = 'bl!'#default prefix
with open('prefixes.json', 'w') as f: #write in the prefix.json "message.guild.id": "bl!"
json.dump(prefixes, f, indent=4) #the indent is to make everything look a bit neater
@client.event
async def on_guild_remove(guild): #when the bot is removed from the guild
with open('prefixes.json', 'r') as f: #read the file
prefixes = json.load(f)
prefixes.pop(str(guild.id)) #find the guild.id that bot was removed from
with open('prefixes.json', 'w') as f: #deletes the guild.id as well as its prefix
json.dump(prefixes, f, indent=4)
Run Code Online (Sandbox Code Playgroud)
第 5 步 -更改前缀命令:
@client.command(pass_context=True)
@has_permissions(administrator=True) #ensure that only administrators can use this command
async def changeprefix(ctx, prefix): #command: bl!changeprefix ...
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f: #writes the new prefix into the .json
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed to: {prefix}') #confirms the prefix it's been changed to
#next step completely optional: changes bot nickname to also have prefix in the nickname
name=f'{prefix}BotBot'
client.run("TOKEN")
Run Code Online (Sandbox Code Playgroud)
编辑:这是针对您在使用它时可能遇到的任何问题。
我如何使用commands.when_mentioned它?
为什么每当有人给我的机器人发送 DM 时我都会收到错误消息?
| 归档时间: |
|
| 查看次数: |
8401 次 |
| 最近记录: |