You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建Discord Bot实现/refresh命令触发POST请求

实现Discord Bot的/refresh命令发送指定POST请求

前置准备

  • 安装依赖库:执行pip install discord.py requests
  • 准备好Discord应用的以下参数:CLIENT_ID、CLIENT_SECRET、REFRESH_TOKEN、REDIRECT_URI,以及POST请求的目标端点URL(比如Discord OAuth2的令牌刷新端点https://discord.com/api/oauth2/token)
  • 确保你的Discord Bot已开启并获取到Bot令牌,邀请Bot到服务器时要包含applications.commands权限范围

完整代码示例

import discord
from discord import app_commands
import requests

# 替换为你的Bot令牌
BOT_TOKEN = "YOUR_BOT_TOKEN"
# 替换为你的Discord应用参数
CLIENT_ID = "YOUR_CLIENT_ID"
CLIENT_SECRET = "YOUR_CLIENT_SECRET"
REFRESH_TOKEN = "YOUR_REFRESH_TOKEN"
REDIRECT_URI = "YOUR_REDIRECT_URI"
# 替换为POST请求的目标URL
TARGET_URL = "https://discord.com/api/oauth2/token"

class MyBot(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        await self.tree.sync()  # 同步斜杠命令到服务器

client = MyBot()

@client.tree.command(name="refresh", description="发送携带指定信息的POST请求")
async def refresh(interaction: discord.Interaction, info: str):
    # 构造POST请求的表单数据
    post_data = {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "refresh_token": REFRESH_TOKEN,
        "grant_type": "refresh_token",
        "redirect_uri": REDIRECT_URI
    }

    try:
        # 发送POST请求
        response = requests.post(TARGET_URL, data=post_data)
        response.raise_for_status()  # 抛出HTTP错误状态码的异常

        # 向用户返回请求结果
        await interaction.response.send_message(
            f"请求发送成功!\n响应内容:\n`{response.text}`",
            ephemeral=True  # 仅发送者可见
        )
    except requests.exceptions.RequestException as e:
        # 处理请求异常
        await interaction.response.send_message(
            f"请求失败:\n`{str(e)}`",
            ephemeral=True
        )

client.run(BOT_TOKEN)

代码说明

  • Bot初始化:创建自定义Bot类,启用默认intents并初始化命令树,通过setup_hook同步斜杠命令到服务器
  • /refresh命令定义:接受一个字符串参数info(对应你示例中的test),若需要可根据该参数动态调整请求内容(比如替换refresh_token)
  • POST请求构造:用字典构造表单数据,自动编码为application/x-www-form-urlencoded格式,完全匹配你要求的参数结构
  • 异常处理:捕获请求过程中的网络错误、HTTP错误等,向用户返回明确的错误提示
  • 响应发送:设置ephemeral=True让响应仅发送者可见,避免干扰服务器其他成员

注意事项

  • 所有YOUR_XXX占位符必须替换为你的真实参数
  • 若要根据用户输入的info动态修改请求参数,可直接调整post_data对应字段,例如post_data["refresh_token"] = info
  • 确保服务器网络能正常访问目标POST端点,避免因网络限制导致请求失败

内容的提问来源于stack exchange,提问作者Proximo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:15:57