首页 > 解决方案 > 使用 Discord.py 发送 Google 图片

问题描述

我已经在 Discord 机器人上工作了很长一段时间,我一直在尝试添加新命令,比如根据命令从 Google 发送随机图像的命令。但是,我似乎无法弄清楚如何设置代码。

到目前为止,我有这个:

  async def razorcrest(self, ctx):
    if len(sys.argv) <= 1:
      print('Usage:')
      print('razorcrest fetch_google_image.py cat cute')
      exit()
      q = ''
    for arg in sys.argv[1:]:
      q += urllib.parse.quote(arg) + '+'
      request = urllib.request.Request('https://www.googleapis.com/customsearch/v1?key=' + API_KEY + '&cx=' + SEARCH_ENGINE_ID + '&q=' + q + '&searchType=image')
      with urllib.request.urlopen(request) as f:
        data = f.read().decode('utf-8')
        data = json.loads(data)
        results = data['items']
        url = random.choice(results)['link']
        urllib.request.urlretrieve(url, './image')
        imagetype = imghdr.what('./image')
      if not type(imagetype) is None:
        os.rename('./image', './image.' + imagetype)

但是,每当我运行此代码时,它都会打印:

Usage:
razorcrest

在终端。

我也试过这个:

from discord.ext import commands

class Images(commands.Cog):
  def __init__(self, client):
    self.client = client
  gis = GoogleImagesSearch('...', '...')

  _search_params = {
    'q': 'razorcrest',
    'num': 10,
    'safe': 'off',
    'fileType': 'png',
    'imgType': 'photo',
    'imgSize': 'large',
    'imgDominantColor': 'black',
    'imgColorType': 'color',
    'rights': 'cc_publicdomain'
  }

  gis.search(search_params=_search_params)

  gis.search(search_params=_search_params, path_to_dir='/path/')

  gis.search(search_params=_search_params, path_to_dir='/path/', width=500, height=500)

  gis.search(search_params=_search_params)
  for image in gis.results():
    image.download('/path/')
    image.resize(500, 500)

def setup(client):
  client.add_cog(Images(client))

但是这段代码也没有成功。

我该怎么办?

标签: discord.py

解决方案


推荐阅读