discord.py - 使用 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))
但是这段代码也没有成功。
我该怎么办?
解决方案
推荐阅读
- r - 删除状态为无效的行/保留状态为有效的行
- linux - shell 脚本:转换原始输出(从 dict 行到 csv)
- javascript - 要求指导以检测站点中的元素是否已更改
- css - 在 Material UI 中调整组件大小而不变形
- jupyter-notebook - Jupyter Notebook“密码或令牌”问题
- android - 创建 realase apk 时出现字体未找到 AAPT 错误
- c - 在图表中搜索一个值并打印它下面的值
- laravel - Laravel 8 Eloquent ORM 登录流程
- java - Spring 安全缺少带有连接语句的选择
- javascript - 是否可以仅使用 vuetify-google-autocomplete 列出城市?