Помогите переделать код, с проверкой формата

пользователи Stackoverflow. Я хочу у вас попросить, как можно переделать два этих кода в один?

Код с проверкой формата .png/.jpg/.gif.

@dp.message_handler(commands=['waifu'])
async def send_randavatar(message: types.Message):
  your_name = message.from_user.username
  hugimg = nekos.img('hug')
  extension = os.path.splitext(hugimg)[1]
  if extension == '.jpg':
    await bot.send_photo(message.chat.id, hugimg, caption=f'@{your_name}')
  elif extension == '.png':
    await bot.send_photo(message.chat.id, hugimg, caption=f'@{your_name}')
  elif extension == '.gif':
    await bot.send_animation(message.chat.id, hugimg, caption=f'@{your_name}')
  else:
    await message.answer('Нет картинки')

Код команды /hug

@dp.message_handler(commands=['hug', 'обнять', 'обнимашки', 'обнял'])
async def send_hug(message: types.Message):
    hugtarget = message.get_args().split()
    your_id = message.from_user.id
    your_name = message.from_user.username
    hugimg = nekos.img('hug')
    if not hugtarget or hugtarget[0][0] != '@':
      await bot.send_message(message.chat.id, f'Введите /hug @имя_пользователя')
    else:
      await bot.send_animation(message.chat.id, hugimg, caption=f'[{hugtarget[0]}], вас обнял [{your_name}](tg://user?id={str(your_id)})', parse_mode="Markdown")

Заранее спасибо ?


Ответы (1 шт):

Автор решения: ZxNuClear

Вот так вроде должно работать. Проверьте

@dp.message_handler(commands=['hug', 'обнять', 'обнимашки', 'обнял'])
async def send_hug(message: types.Message):
    hugtarget = message.get_args().split()
    your_id = message.from_user.id
    your_name = message.from_user.username
    hugimg = nekos.img('hug')
    if not hugtarget or hugtarget[0][0] != '@':
      await bot.send_message(message.chat.id, f'Введите /hug @имя_пользователя')
    else:
      extension = os.path.splitext(hugimg)[1]
      if extension == '.jpg':
        await bot.send_photo(message.chat.id, hugimg, caption=f'[{hugtarget[0]}], вас обнял [{your_name}](tg://user?id={str(your_id)})', parse_mode="Markdown")
      elif extension == '.png':
        await bot.send_photo(message.chat.id, hugimg, caption=f'[{hugtarget[0]}], вас обнял [{your_name}](tg://user?id={str(your_id)})', parse_mode="Markdown")
      elif extension == '.gif':
        await bot.send_animation(message.chat.id, hugimg, caption=f'[{hugtarget[0]}], вас обнял [{your_name}](tg://user?id={str(your_id)})', parse_mode="Markdown")
      else:
        await message.answer('Нет картинки')
→ Ссылка