Discord.py 通过服务器获取服务器名称或 ID link
Discord.py get server name or id by server link
所以我想要一个机器人,它可以 return 服务器 name/id 通过加入 link。
喜欢:
https://discord.gg/WxwgCQzW
将 return: cryptoTribe
更新
更好的方法
经过更多挖掘,有更好的方法可以做到这一点,使用 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
老办法
您可以对邀请端点执行 GET 请求:
GET https://discordapp.com/api/invite/WxwgCQzW
然后,使用 JSON 数据:
guild_name = data["guild"]["name"]
代码
使用 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"]
所以我想要一个机器人,它可以 return 服务器 name/id 通过加入 link。
喜欢:
https://discord.gg/WxwgCQzW
将 return: cryptoTribe
更新
更好的方法
经过更多挖掘,有更好的方法可以做到这一点,使用 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
老办法
您可以对邀请端点执行 GET 请求:
GET https://discordapp.com/api/invite/WxwgCQzW
然后,使用 JSON 数据:
guild_name = data["guild"]["name"]
代码
使用 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"]