【问题标题】:making a bot respond to an image using discord.py使用 discord.py 让机器人响应图像
【发布时间】:2019-02-09 22:19:53
【问题描述】:

使用 discord.py 进行机器人编码的新手。正如标题所示,我希望有人能告诉我如何让机器人响应发送图像的人,无论是从互联网粘贴还是从他们的计算机上传。

【问题讨论】:

  • 那么,为了澄清,您想检测给定消息的图像吗?我认为收听和回复消息超出了具体问题的范围。

标签: python bots discord.py


【解决方案1】:

当然,您可以使用.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")

【讨论】:

  • 所以我尝试了以下语句: if message.attachments[0]['url']: 好在程序正常工作,它检测到图像已发送并回复我的消息想。但它抛出了这个错误:第 67 行,在 on_message if message.attachments[0]['url']: IndexError: list index out of range
  • 是的,您可以使用 try/except 捕获错误。我已将示例添加到我的答案中
猜你喜欢
  • 2018-07-09
  • 2021-08-18
  • 2021-11-03
  • 2021-11-28
  • 2021-10-06
  • 1970-01-01
  • 2018-11-17
  • 2021-10-22
  • 2020-09-27
相关资源
最近更新 更多