在discord.py重写中获取服务器ID



我想知道如何在discord重写中获得服务器ID,这样我就可以在单个服务器级别的基础上保存特定的设置。有办法这样做吗?

如果您从原始消息/命令中收集上下文,则可以使用ctx.guild.name返回名称,或者使用ctx.guild.id返回发布命令的公会的ID。

示例:

bot = commands.Bot(command_prefix='!')
@bot.command(name='whereami', help='print the current server name/id')
async def whereami(ctx):
await ctx.send(f'{ctx.author.name}, you are currently in {ctx.guild.name} ({ctx.guild.id}).')

如果您想存储我推荐给您的任何数据JSON文件只需(获取服务器(改写中的公会(ID:if命令:

@bot.command()
async def test(ctx):
ID = ctx.guild.id

if事件(例如on_member_join(((:

@bot.event()
async def on_member_join(member):
ID = member.guild.id

如果您想将其保存到JSON文件中,您可以:

@bot.command()
async def test(ctx):
ID[str(ctx.guild.id)] = [content to save with specific ID]
with open("data.json", "w") as f:
json.dump(ID, f, indent=4)

它将把数据dump转换成JSON文件。在这个文件中,它将看起来像:

{
"[guild id]": "[content to save]",
}

有了这种方法,你可以节省你想要的

最新更新