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

如何为discord.py开发的Discord机器人添加谷歌搜索命令

discord.py 机器人谷歌搜索功能实现方法

1. 安装前置依赖

终端执行以下命令安装所需库:

  • 安装/更新 discord.py 到稳定v2版本:pip install -U discord.py
  • 安装无需官方API密钥的谷歌搜索解析库:pip install googlesearch-python

注意:不要安装名称相似的其他谷歌搜索相关包,否则会出现导入报错。

2. 核心功能代码

提前将机器人指令前缀设置为.,同时打开消息内容权限,添加如下逻辑即可匹配.search "关键词"的指令格式:

import discord
from discord.ext import commands
from googlesearch import search
import re

# 初始化机器人配置
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='.', intents=intents)

@bot.command(name='search')
@commands.cooldown(1, 10, commands.BucketType.user) # 单用户10秒冷却,防止频繁请求触发反爬
async def google_search(ctx, *, query: str):
    # 自动去除用户输入里包裹关键词的前后双引号
    cleaned_query = re.sub(r'^"|"$', '', query.strip())
    await ctx.defer() # 提前发送延迟响应,避免搜索耗时过长触发discord交互超时
    
    try:
        # 拉取前5条中文搜索结果,可按需调整返回数量、语言、安全搜索规则
        result_list = []
        for idx, url in enumerate(search(cleaned_query, num_results=5, lang='zh-CN'), start=1):
            result_list.append(f"{idx}. {url}")
        
        if not result_list:
            await ctx.send(f"未找到和 **{cleaned_query}** 相关的搜索结果,请更换关键词重试。")
            return
        
        # 拼接结果发送
        reply = f"**关键词「{cleaned_query}」的谷歌搜索结果:**\n" + "\n".join(result_list)
        await ctx.send(reply)
    
    except Exception as e:
        await ctx.send("搜索失败,大概率是短时间请求过多被谷歌临时限制,请1-2分钟后再试。")

# 替换为你自己的机器人Token即可运行
bot.run("YOUR_BOT_TOKEN")

3. 常见踩坑提示

  • 必须到Discord开发者后台打开机器人的「Message Content Intent」开关,否则无法接收普通消息内容,指令不会触发
  • 该搜索库基于公开搜索结果爬取实现,仅适合个人小服务器低频率使用,如果是千人以上大服务器公用,建议替换为官方搜索接口,避免IP被临时封禁
  • 单用户冷却时间不要低于5秒,否则极容易触发谷歌反爬机制
  • 如果需要展示网页标题,可以额外加简单的网页请求逻辑解析title字段,记得给请求加3秒超时,避免卡住响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 11:06:33