Discord.py get server name or id by server link
So i want a bot that can return the server name/id by the join link.
Like:
https://discord.gg/WxwgCQzW
Will return: cryptoTribe
Solution 1:
Update
Better way
After some more digging, there's a better way to do this, using discord.Client.fetch_invite()
, which returns a discord.Invite
:
async def get_invite_name(link: str):
# Assuming bot or client is a global variable
invite = await bot.fetch_invite(link)
return invite.guild.name
Old way
You can perform a GET request to the invite endpoint:
GET https://discordapp.com/api/invite/WxwgCQzW
Then, with the JSON data:
guild_name = data["guild"]["name"]
Code
Using aiohttp:
import aiohttp
import json
DISCORD_API_LINK = "https://discordapp.com/api/invite/"
async def get_invite_name(link: str) -> str:
# Get the invite code of the link by splitting the link and getting the last element
invite_code = link.split("/")[-1]
async with aiohttp.ClientSession() as session:
async with session.get(DISCORD_API_LINK + invite_code) as response:
data = await response.text()
json_data = json.loads(data)
return json_data["guild"]["name"]