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

如何用Python为Discord Bot编写按标签搜索图片的命令

实现Discord Bot的!img命令指南

嘿,刚入门两天就能搞定踢人、封禁这些基础命令,这进度真的不错!要实现你想要的!img命令其实没那么复杂,咱们一步步来拆解:

第一步:准备必要的工具库

你已经在用discord.py开发Bot了,还需要一个用来发送网络请求的库requests;如果要爬取指定网站的图片,还得用到解析网页的beautifulsoup4。打开终端安装它们:

pip install discord.py requests beautifulsoup4

第二步:选择图片获取方式

有两种主流方式适合你现在的阶段:

  • 方式1:使用免费图片API(推荐新手)
    很多平台提供支持关键词搜索的免费图片API,部分需要免费注册获取密钥,但步骤很简单。这类API会返回JSON格式的数据,你只需要解析拿到图片URL就行,不会遇到反爬问题。
  • 方式2:爬取指定网站的图片
    如果要从你指定的网站获取图片,就需要简单的网页爬取,但要注意遵守网站的robots.txt规则,避免触发反爬机制。

第三步:编写!img命令代码

用API实现的示例代码

先给你一个用API实现的完整示例,你只需要替换成你选的API地址就行:

import discord
from discord.ext import commands
import requests
import random

# 初始化Bot,记得开启消息内容权限
intents = discord.Intents.default()
intents.message_content = True  # 必须开启,否则Bot读不到用户输入的命令
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.command()
async def img(ctx, *, tag):
    """发送和指定标签相关的随机图片"""
    # 替换成你选择的图片API的请求地址,把{tag}替换成关键词参数
    api_request_url = f"这里替换成你的API地址,带上tag参数"
    
    try:
        # 发送请求获取图片数据
        response = requests.get(api_request_url)
        response.raise_for_status()  # 如果请求失败,抛出异常
        img_data = response.json()
        
        # 假设API返回的结果存在results列表里,随机选一张
        if img_data.get('results'):
            selected_img = random.choice(img_data['results'])
            # 根据API返回的结构,提取图片的URL,这里要对应调整
            img_url = selected_img['urls']['regular']
            
            # 用Embed发送图片,比直接发URL更美观
            embed = discord.Embed(title=f"✨ 你要的{tag}图片来啦!")
            embed.set_image(url=img_url)
            await ctx.send(embed=embed)
        else:
            await ctx.send(f"😔 没找到和「{tag}」相关的图片哦")
    except Exception as e:
        await ctx.send(f"⚠️ 出错啦:{str(e)}")

# 运行Bot,替换成你的Bot令牌
bot.run('你的Discord Bot令牌')

爬取指定网站的示例思路

如果要爬取指定网站,比如某个图库,代码大概是这样的(需要根据网站的HTML结构调整):

@bot.command()
async def img(ctx, *, tag):
    """从指定网站爬取随机图片"""
    # 替换成指定网站的搜索URL,把tag作为搜索关键词
    target_url = f"指定网站的搜索页面URL?keyword={tag}"
    
    try:
        response = requests.get(target_url)
        response.raise_for_status()
        from bs4 import BeautifulSoup
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 找到页面里的图片标签,比如根据class或者标签属性筛选
        img_elements = soup.find_all('img', class_='图片的class名称')
        if img_elements:
            random_img = random.choice(img_elements)
            img_url = random_img['src']
            # 有些网站的图片是相对路径,需要拼接成完整URL
            if not img_url.startswith('http'):
                img_url = f"指定网站的域名{img_url}"
            await ctx.send(img_url)
        else:
            await ctx.send(f"没找到和「{tag}」相关的图片哦")
    except Exception as e:
        await ctx.send(f"出错啦:{str(e)}")

关键注意事项

  • 开启Discord Intents:一定要在Discord开发者平台的Bot设置里,开启「Message Content Intent」,否则Bot无法读取用户发送的命令内容。
  • API密钥(如果需要):如果选的API需要密钥,记得在请求里带上密钥参数,比如requests.get(api_url, params={'key': '你的密钥', 'q': tag})。
  • 测试优先:先在你的私人服务器里测试命令,确认没问题再推广使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:06:20