繁体   English   中英

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

[英]Get server ID in discord.py rewrite

我试图弄清楚如何在 discord 重写中获取服务器 ID,以便我可以在单个服务器级别保存特定设置。 有没有办法做到这一点?

如果你想存储我推荐给你的任何数据 JSON 文件简单(获取服务器(重写中的公会)ID:if 命令:

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

如果事件(例如 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]",
}

使用这种方法,您可以节省尽可能多的钱

如果您从原始消息/命令中收集上下文,则可以使用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}).')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM