如何使用 Python 修改 Discord webhook 的频道

How to modify channel of Discord webhook with Python

我有一个 Python 脚本,它使用分配给我的 Discord 服务器的 webhook 发送消息。我想让我的程序有时能够更改 webhook 的频道。

Discord Developer Portal I read there are two ways of modifying webhooks using requests (1. Modify webhook, 2. Modify webhook with token).

我已经测试了更简单的第二个,但它只允许更改头像和用户名:

 r = requests.patch("https://discordapp.com/api/webhooks/.../...", json={ "name":"New Name" })
 # status code 200

更改 webhook 通道由第一个提供,但它需要某种称为 MANAGE_WEBHOOKS 的权限,因此下面的方法当然不起作用:

 r = requests.patch("https://discordapp.com/api/webhooks/...", json={ "channel_id":12345 })
 # status code 401 (unauthorized)

我已经创建了 Discord 应用程序并开始阅读有关处理 webhook 授权的内容 over here 但我卡住了,我不明白如何让它真正起作用。

重新查看 Discord 文档后,我终于解决了我的问题。下面我写了如何在简单的 Python 脚本中实现这样的结果:

  1. 打开 Discord 开发者门户,创建新应用,在 OAuth2 部分添加用于重定向的 bot 和 URI。
  2. 使用 OAuth2 部分中的生成器创建授权 URL。对于 Scopes select botdiscord.incoming机器人权限 select Manage Webhooks。你会得到这样的东西:

    https://discordapp.com/api/oauth2/authorize?client_id=<MY_CLIENT_ID>&permissions=536870912&redirect_uri=<MY_URI>&response_type=code&scope=bot%20webhook.incoming
    
  3. 在您的浏览器中打开此 link 以将 bot 和 webhook 连接到您的服务器。接受后,您将被重定向到您的 URI 地址。

  4. 该地址将包含 code 查询字符串参数。我只是手动复制了这个 code 并将其粘贴到后续步骤中的脚本(请注意 code 的有效期很短,所以如果你做得太慢,身份验证可能不会成功)。
  5. 这里是进行必要认证的代码:

    import requests
    
    CLIENT_ID = # Your client id 
    CLIENT_SECRET = # Your client secret
    REDIRECT_URI = # Your redirect URI
    CODE = # Your code from step 4.
    
    data = {
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'grant_type': 'authorization_code',
        'code': CODE,
        'redirect_uri': REDIRECT_URI,
        'scope': 'bot webhook.incoming',
        'permissions': "536870912",
    }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    r = requests.post('https://discordapp.com/api/oauth2/token', data=data, headers=headers)
    r.raise_for_status()
    

    无异常则认证成功

  6. 如果一切正常,运行此代码用于更改当前的 webhook 通道:

    ...
    
    BOT_TOKEN = # Your bot's token
    WEBHOOK_ID = # Your webhook's id
    
    json = { "channel_id": 12345 } # Replace with new webhook's channel id
    headers = { "Authorization": "Bot " + BOT_TOKEN }
    
    r = requests.patch('https://discordapp.com/api/webhooks/' + WEBHOOK_ID, json=json, headers=headers)