[英]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.