这是我的第一个问题,我希望能为我的问题找到答案。
情况: 我不是程序员,但我目前正在学习 python(有趣且有趣)。我寻找与 python 相关的有趣项目(我愿意接受建议和建议!:))并且我偶然发现了一个 Discord Bot。我开始观看教程并开始编码。我了解 python 的基础知识,所以很容易理解大部分内容。我的机器人基本上可以工作。现在我想为不同的服务器添加自定义前缀。我研究了一下,然后写了代码。 .json 文件已正确调整并保存。每个不和谐都应该能够设置自定义前缀。
我的问题:
如果我更改前缀并输入(前缀=!)“!help”,它会在我的自定义帮助中显示:“
我的代码:
import nextcord
from nextcord.ext import commands
from nextcord import Embed
import json
# Token for the Discord-Bot
TOKEN = '<not showing here>'
# Declaring intents which are necessary
intents = nextcord.Intents.default()
intents.message_content = True
# Create a Bot instance
bot = commands.Bot(intents=intents)
# Define the get_prefix function
def get_prefix(bot, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes.get(str(message.guild.id), '!') # Default to '!' if no prefix is set
# Set the command prefix using the command_prefix parameter when creating the Bot instance
bot = commands.Bot(command_prefix=get_prefix, intents=intents)
@bot.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)
@bot.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@bot.command()
async def changeprefix(ctx, prefix: str):
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)
bot.remove_command("help")
# Starting the bpt
@bot.event
async def on_ready():
await bot.change_presence(status=nextcord.Status.do_not_disturb, activity=nextcord.Game('nothing'))
print(f'{bot.user} is now running!')
print("------------------------------")
# Define a custom error handler
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(f"Not a valid command. Use {bot.command_prefix}help for a list of available commands.")
# Custom help
@bot.command(name="help", brief="Shows this window")
async def custom_help(ctx, *args):
if not args:
# Sort the commands alphabetically, help always at the top
sorted_commands = sorted(bot.commands, key=lambda x: (x.name != "help", x.name))
# No arguments provided, show a list of top-level commands
embed = Embed(color=0x0080ff, title="Available Commands")
for command in sorted_commands:
if not command.hidden:
description = command.brief or "No desc. yet."
embed.add_field(name=f"{bot.command_prefix}{command.name}", value=description, inline=False)
await ctx.send(embed=embed)
elif len(args) == 1:
# One argument provided, show command description if available
command_name = args[0]
command = bot.get_command(command_name)
if command:
embed = Embed(color=0x0080ff, title=f"Help for {bot.command_prefix}{command.name}")
embed.description = command.help
await ctx.send(embed=embed)
else:
await ctx.send(f"Command not found: {command_name}")
elif len(args) == 2:
# Two arguments provided, show subcommand description if available
command_name, subcommand_name = args
command = bot.get_command(f"{command_name} {subcommand_name}")
if command:
embed = Embed(color=0x0080ff, title=f"Help for {bot.command_prefix}{command.name}")
embed.description = command.help
await ctx.send(embed=embed)
else:
await ctx.send(f"Subcommand not found: {bot.command_prefix}{command_name} {subcommand_name}")
else:
await ctx.send(f"Invalid usage. Use {bot.command_prefix}help to list commands, {bot.command_prefix}help command to see command details, or {bot.command_prefix}help command subcommand to see subcommand details.")
# Run the bot
bot.run(TOKEN)
任何想法或想法表示赞赏!
我尝试过的: 我一直在尝试研究一个解决方案,为什么它输出函数而不是值。我尝试过调整不同的东西,并使用 chatgpt 来尝试解决问题。不幸的是,这一切都没有帮助。
问题是您正在尝试访问
bot
定义中的“参数”。
假设服务器设置了前缀,您可以使用以下代码:
def get_prefix(bot, msg: discord.Message):
guild = msg.guild
base = ["!"]
with open('prefixes.json', 'r', encoding='utf-8') as fp:
prefixes = json.load(fp)
if guild:
try:
prefix = prefixes[str(guild.id)]
base.append(prefix)
except KeyError:
pass
return base
此方法可用于将所有前缀加载到机器人中。
msg.guild
)继续,如何检索前缀非常简单:
prefix = get_prefix(bot, ctx.message)[1]
请注意,其中不包含错误处理程序,请自行执行(以防 JSON 为空或任何其他情况)
在这里,我们再次从头开始使用我们定义的函数。
然后您可以在其余代码中使用上面的代码:
for command in commands:
embed.add_field(name=f"{prefix}{command.name}", value=command.help, inline=False)
value
字段返回命令的文档字符串描述这将返回公会的设置前缀。再说一遍:我的部分中没有包含错误处理程序。