Lillie Callinan
Lillie Callinan

Reputation: 11

Get server ID in discord.py rewrite

Im trying to figure out how to get a server ID in discord rewrite so that I can save specific settings on an individual server- level basis. Is there anyway to do this?

Upvotes: 1

Views: 4989

Answers (2)

user2863294
user2863294

Reputation: 472

If you're collecting context from the original message/command, then you can use ctx.guild.name to return the name or ctx.guild.id to return the ID of the guild where the command was posted.

Example:

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}).')

Upvotes: 2

Thundo
Thundo

Reputation: 173

If you want to storage any data I recommend to you JSON files Simply (to get server (guild in rewrite) ID: if command:

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

if event (e.g. on_member_join()):

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

if you wanna to save that into JSON file you could:

@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)

It will dump a data to JSON file. In this files it will be look like:

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

With this method you can save as much as you want

Upvotes: 1

Related Questions