使机器人使用discord.py响应图像

时间:2018-09-04 20:48:44

标签: python bots discord.py

使用discord.py进行机器人编码的新手。顾名思义,我希望有人能告诉我如何使漫游器响应某人发送的图像,无论该图像是从Internet粘贴还是从其计算机上传的。

1 个答案:

答案 0 :(得分:2)

好的,您可以使用.attachments

@client.event
async def on_message(message):
  print(message.attachments)

对于外部链接的图片,您可以执行

  pic_ext = ['.jpg','.png','.jpeg']
  for ext in pic_ext:
    if message.content.endswith(ext):
      #do stuff

.attachments还会返回一个列表,其中包含字典

[{'width': 1200, 'url': 'https://cdn.discordapp.com/attachments/421005768494678016/486646740993179688/1200px-Greek_uc_Omega.svg.png', 'size': 27042, 'proxy_url': 'https://media.discordapp.net/attachments/421005768494678016/486646740993179688/1200px-Greek_uc_Omega.svg.png', 'id': '486646740993179688', 'height': 1200, 'filename': '1200px-Greek_uc_Omega.svg.png'}]

因此,要访问其中的任何值(在本例中为URL),您可以执行

message.attachments[0]['url']

字典代码示例

  try:
    print(message.attachments[0]['url'])
  except IndexError:
    pass

网址代码示例

pic_ext = ['.jpg','.png','.jpeg']
@bot.event
async def on_message(message):
  for ext in pic_ext:
    if message.content.endswith(ext):
      print("test")