making a bot respond to an image using discord.py

六眼飞鱼酱① 提交于 2019-12-08 07:54:21

问题


New to bot coding using discord.py. As the title suggests, I'm hoping if someone can tell me how to make a bot respond to someone sending an image, whether it's pasted from the internet or uploaded from their computer.


回答1:


Sure, you can use the .attachments

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

For pictures from outside links you could do something like

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

.attachments also returns a list with a dict inside

[{'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'}]

so to access any value (in this case its url) from it you can do something like

message.attachments[0]['url']

Example of dict code

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

Example of url code

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


来源:https://stackoverflow.com/questions/52173801/making-a-bot-respond-to-an-image-using-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!