如何检查邀请是否无效?

时间:2020-06-13 00:03:06

标签: python python-3.x discord.py

我在stackoverflow上看到了这个问题:Testing if discord invite link is invalid?,但是它已经使用了一年,并且某些模块在Python 3中不存在。

我尝试做过(这里的邀请无效):我希望有404 not found error

import urllib.request
content = urllib.request.urlopen('https://discord.gg/UWxaV8m').read()
print(content)

但是,这给了我一个错误:urllib.error.HTTPError: HTTP Error 403: Forbidden;还有其他方法吗?另外,还要查看错误:由于我是机器人用户,因此我似乎无法访问该邀请? idk

2 个答案:

答案 0 :(得分:1)

如果您希望用户通过命令参数输入邀请,则如果邀请无效(确切地说是discord.NotFound错误),它将引发异常:

@bot.command()
async def inv(ctx, invite: discord.Invite):
    await ctx.send("That invite is valid!")
@inv.error
async def inv_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        if isinstance(error.original, discord.NotFound):
            await ctx.send("That invite is invalid or has expired.")

或者您可以使用fetch_invite()

try:
    invite = await bot.fetch_invite(URL_OR_ID_HERE)
    await ctx.send("That's a valid invite!")
except:
    await ctx.send("Sorry, that invite was invalid or has expired.")

不需要任何其他模块-只是discord库能够告诉您有关邀请的信息。


参考:

答案 1 :(得分:1)

使用不和谐请求页面中的网址,并在标题中添加用户代理,我就能得到响应:

import urllib.request
url = 'https://discord.com/api/v6/invites/UWxaV8m?with_counts=true'
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need
print(data)

输出:

b'{"code": "UWxaV8m", "guild": {"id": "599754844676554783", "name": "Thicc Mario Hub | 10 Boosts", "splash": "1d76b7a1ecceffa42552abc88ea5d6ad", "banner": "7036d8cd5e36e91fe5c87478c5eae37a", "description": null, "icon": "a_3355e47f1d336ad04737afc2ba08fe62", "features": ["ANIMATED_ICON", "INVITE_SPLASH"], "verification_level": 2, "vanity_url_code": null}, "channel": {"id": "599761618720653313", "name": "\\u2554\\u27a4\\u300e\\ud83d\\udcdc\\u300frules", "type": 0}, "inviter": {"id": "429840967470678037", "username": "Thicc Mario", "avatar": "dd33989a2b86a43f53280174addd3a21", "discriminator": "8611", "public_flags": 256}, "approximate_member_count": 1662, "approximate_presence_count": 373}'