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

如何通过Discord Bot API实现命令触发URL动态修改并返回请求结果

实现方案

首先安装所需依赖:

pip install discord.py requests

使用以下代码即可实现对应功能,将示例中的机器人令牌、基础URL替换为你自己的实际内容即可:

import discord
from discord.ext import commands
import requests

# 配置命令前缀为.
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())

# 机器人启动完成提示
@bot.event
async def on_ready():
    print(f'已登录为 {bot.user}')

# 实现.Check命令
@bot.command()
async def Check(ctx, param: str):
    # 拼接请求URL
    url = f'https://Test.com/{param}/json'
    try:
        # 自定义User-Agent避免被站点拦截
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        }
        res = requests.get(url, headers=headers, timeout=10)
        res.raise_for_status()
        # 发送接口返回内容
        await ctx.send(res.text)
    except requests.exceptions.RequestException as e:
        await ctx.send(f'请求失败:{str(e)}')

# 启动机器人,替换为你的Discord机器人令牌
bot.run('你的Discord机器人令牌')

必要配置说明

  • 需要先进入Discord开发者后台,在你的机器人设置的「Privileged Gateway Intents」板块,开启「Message Content Intent」权限,否则机器人无法读取频道内的消息内容
  • 如果接口返回的文本长度超过Discord单条消息2000字符的限制,可以将内容保存为txt文件后发送,避免发送失败
  • 可根据你的实际需求调整请求的超时时间、请求头等参数,降低被站点拦截的概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:54:07