def check_user_photo(bot, update, user_data): update.message.reply_text("Обрабатываю фото") os.makedirs('downloads', exist_ok=True) photo_file = bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', f'{photo_file.file_id}.jpg') photo_file.download(filename) if is_cat(filename): update.message.reply_text("Обнаружен котик, добавляю в библиотеку") new_filename = os.path.join('images', f'{photo_file.file_id}.jpg') os.rename(filename, new_filename) else: os.remove(filename) update.message.reply_text("Тревога, котик не обнаружен!!")
def chek_user_photo(update, context): update.message.reply_text("Обрабатываем фотографию") os.makedirs("downloads", exist_ok=True) user_photo = context.bot.getFile(update.message.photo[-1].file_id) file_name = os.path.join("downloads", f"{user_photo.file_id}.png") user_photo.download(file_name) if is_cat(file_name): update.message.reply_text("Обнаружен кот, добавляю в библиотеку") new_filename = os.path.join("images", f"{user_photo.file_id}.png") os.rename(file_name, new_filename) else: update.message.reply_text("Кот на фото не обнаружен") os.remove(file_name)
def check_user_photo(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) update.message.reply_text('Обрабатываем фото') os.makedirs('downloads', exist_ok=True) photo_file = bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', '{}.jpg'.format(photo_file.file_id)) photo_file.download(filename) if is_cat(filename): update.message.reply_text('Обнаружен котик, добавляю в библиотеку.') new_filename = os.path.join('images', 'cat{}.jpg'.format(photo_file.file_id)) os.rename(filename, new_filename) else: os.remove(filename) update.message.reply_text("Котик не обнаружен.")
def check_user_photo(bot, update, user_data): update.message.reply_text('Обрабатываю фото') os.makedirs('downloads', exist_ok=True) photo_file = bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', f'{photo_file.file_id}.jpg') photo_file.download(filename) update.message.reply_text('Файл сохранен') if is_cat(filename): update.message.reply_text('Обнаружен шерстяной, добавляю в библиотеку') new_filename = os.path.join('img', f'cat_{photo_file.file_id}.jpg') os.rename(filename, new_filename) else: os.remove(filename) update.message.reply_text('Шерстяной не обнаружен')
def check_user_photo(update, context): user = get_or_create_user(db, update.effective_user, update.message.chat.id) update.message.reply_text("Обрабатываем фотографию") os.makedirs("downloads", exist_ok=True) user_photo = context.bot.getFile(update.message.photo[-1].file_id) file_name = os.path.join("downloads", f"{user_photo.file_id}.jpg") user_photo.download(file_name) if is_cat(file_name): update.message.reply_text("Обнаружен котик, добавляю в библиотеку") new_filename = os.path.join("images", f"cat_{user_photo.file_id}.jpg") os.rename(file_name, new_filename) else: update.message.reply_text("Тревога, котик на фото не обнаружен") os.remove(file_name)
def check_user_pic(update, context): update.message.reply_text('Process the pic') os.makedirs('downloads', exist_ok=True) user_pic = context.bot.getFile(update.message.photo[-1].file_id) file_name = os.path.join('downloads', f'{user_pic.file_id}.jpg') user_pic.download(file_name) update.message.reply_text('Pic is safe!') if is_cat(file_name): update.message.reply_text('Cat is detected, add to library') new_file_name = os.path.join('images', f'cat_{user_pic.file_id}.jpg') os.rename(file_name, new_file_name) else: os.remove(file_name) update.message.reply_text('Alarm, cat is not identify!')
def check_user_photo(bot, update, user_data): update.message.reply_text("Проверяю на котэ") os.makedirs('downloads', exist_ok=True) photo_file = bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', '{}.jpg'.format(photo_file.file_id)) photo_file.download(filename) if is_cat(filename): update.message.reply_text("Обнаружен котэ! Добавляю в библиотеку!") new_filename = os.path.join('images', 'Kot_{}.jpg'.format(photo_file.file_id)) os.rename(filename, new_filename) else: update.message.reply_text("К сожалению, котиков не нашел!") os.remove(filename)
def check_user_photo(update, context): get_or_create_user(db, update.effective_user, update.message.chat.id) update.message.reply_text('Обрабатываем фотографию') os.makedirs('downloads', exist_ok=True) user_photo = context.bot.getFile(update.message.photo[-1].file_id) file_name = os.path.join('downloads', f'{user_photo.file_id}.jpg') user_photo.download(file_name) if is_cat(file_name): update.message.reply_text('Обнаружен мемасик, добавляю в библиотеку') new_filename = os.path.join('images', f'meme_{user_photo.file_id}.jpg') os.rename(file_name, new_filename) else: update.message.reply_text('МЕМАС НЕ ОБНАРУЖЕН!!') os.remove(file_name)
def check_user_photo(update: Update, context: CallbackContext): update.message.reply_text("Обрабатываю фото") os.makedirs("downloads", exist_ok=True) photo_file = context.bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', '{}.jpg'.format(photo_file.file_id)) print(filename) photo_file.download(filename) if is_cat(filename): update.message.reply_text("Обнаружен котик, добавляю в библиотеку.") new_filename = os.path.join('images', 'cat_{}.jpg'.format(photo_file.file_id)) os.rename(filename, new_filename) else: os.remove(filename) update.message.reply_text("Тревога, котик не обнаружен.")
def check_user_photo(update, context): user = get_or_create_user(db, update.effective_user, update.message.chat_id) update.message.reply_text('Process image') os.makedirs('downloads', exist_ok=True) user_photo = context.bot.getFile(update.message.photo[-1].file_id) file_name = os.path.join('downloads', f'{user_photo.file_id}.jpg') user_photo.download(file_name) update.message.reply_text('Image saved') if is_cat(file_name): update.message.reply_text('Cat detected!') new_filename = os.path.join('images', f'{user_photo.file_id}.jpg') os.rename(file_name, new_filename) else: update.message.reply_text('Cat not found') os.remove(file_name)
def check_user_photo(update, context): user = get_or_create_user(db, update.effective_user, update.message) context.bot.send_message(chat_id=update.effective_chat.id, text=f'Обрабатываю фото') os.makedirs('downloads', exist_ok=True) photo_file = context.bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', f'{photo_file.file_id}.jpg') photo_file.download(filename) #context.bot.send_message(chat_id=update.effective_chat.id, text=f'Файл сохранен') if is_cat(filename): context.bot.send_message( chat_id=update.effective_chat.id, text=f'Обнаружен котик, добавляю в библиотеку.') new_filename = os.path.join('images', f'cat_{photo_file.file_id}.jpg') os.rename(filename, new_filename) else: context.bot.send_message(chat_id=update.effective_chat.id, text=f'неОбнаружен котик.') os.remove(filename)
def check_user_photo(bot, update, user_data): update.message.reply_text("Обрабатываю фото...") os.makedirs( 'downloads', exist_ok=True) # создает папку и не выдает ошибку, если она уже есть photo_file = bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', '{}.jpg'.format(photo_file.file_id)) photo_file.download(filename) if is_cat(filename): update.message.reply_text("Обнаружен котик, добавляю в библиотеку.") new_filename = os.path.join('images', 'cat_{}.jpg'.format(photo_file.file_id)) os.rename( filename, new_filename) # перемещает в новое место, а не переименовывает! logging.info('{}({}): new cat uploaded to images'.format( update.message.chat.username, update.message.chat.first_name)) else: os.remove(filename) update.message.reply_text("Кот не обнаружен.") logging.info('{}({}): non-cat image recieved - no action'.format( update.message.chat.username, update.message.chat.first_name))
def check_user_photo(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) update.message.reply_text('Обрабатываю фото') os.makedirs( 'downloads', exist_ok=True ) # создаем папку и не выбрасывае исключение даже если ее не существует photo_file = bot.getFile( update.message.photo[-1].file_id ) # если в бот присылается файл, то телеграмм сам его конвертирует в jpg и созадет несколько вариантов файла (превью), update.message.photo[-1] берем последний элемент (оригинальное изображение), file_id - идентификатор файла filename = os.path.join( 'downloads', '{}.jpg'.format(photo_file.file_id) ) # os.path.join - соединяем название файлов и папок между собой по правильным слешам, пусть сохранение файла и название - это id - это путь до файла photo_file.download(filename) # скачиваем файл update.message.reply_text('Файл сохранен') if is_cat(filename): update.message.reply_text('Котик обнаружен, добавлено в библиотеку') new_filename = os.path.join('images', 'cat_{}.jpg'.format(photo_file.file_id)) os.rename(filename, new_filename) # перемещаем файл и переименовываем его else: update.message.reply_text( 'Котик не обнаружен, не добавлено в библиотеку') os.remove(filename) # удаляем файл если там нету котика
def talk_to_me(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) emo = get_user_emo(db, user) user_text = "Привет {} {}! Ты написал: {}".format(user['first_name'], emo, update.message.text) logging.info("User: %s, Chat id: %s, Message: %s", user['username'], update.message.chat.id, update.message.text) update.message.reply_text(user_text, reply_markup=get_keyboard() def send_cat_picture(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) cat_list = glob('images/cat*.jp*g') cat_pic = choice(cat_list) bot.send_photo(chat_id=update.message.chat.id, photo=open(cat_pic, 'rb'), reply_markup=get_keyboard()) def change_avatar(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) if 'emo' in user: del user['emo'] emo = get_user_emo(db, user) update.message.reply_text('Готово: {}'.format(emo), reply_markup=get_keyboard()) def get_contact(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) print(update.message.contact) update.message.reply_text('Готово: {}'.format(get_user_emo(db, user)), reply_markup=get_keyboard()) def get_location(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) print(update.message.location) update.message.reply_text('Готово: {}'.format(get_user_emo(db, user)), reply_markup=get_keyboard()) def check_user_photo(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) update.message.reply_text("Обрабатываю фото") os.makedirs('downloads', exist_ok=True) photo_file = bot.getFile(update.message.photo[-1].file_id) filename = os.path.join('downloads', '{}.jpg'.format(photo_file.file_id)) photo_file.download(filename) if is_cat(filename): update.message.reply_text("Обнаружен котик, добавляю в библиотеку.") new_filename = os.path.join('images', 'cat_{}.jpg'.format(photo_file.file_id)) os.rename(filename, new_filename) else: update.message.reply_text("Тревога, котик не обнаружен!") os.remove(filename) def anketa_start(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) update.message.reply_text("Как вас зовут? Напишите имя и фамилию", reply_markup=ReplyKeyboardRemove()) return "name" def anketa_get_name(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) user_name = update.message.text if len(user_name.split(" ")) != 2: update.message.reply_text("Пожалуйста введите имя и фамилию") return "name" else: user_data['anketa_name'] = user_name reply_keyboard = [["1", "2", "3", "4", "5"]] update.message.reply_text( "Оцените нашего бота от 1 до 5", reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) ) return "rating" def anketa_rating(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) user_data['anketa_rating'] = update.message.text update.message.reply_text("""Пожалуйста напишите отзыв в свободной форме или /skip стобы пропустить этот шаг""") return "comment" def anketa_comment(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) user_data['anketa_comment'] = update.message.text text = """ <b>Фамилия Имя:</b> {anketa_name} <b>Оценка:</b> {anketa_rating} <b>Комментарий:</b> {anketa_comment}""".format(**user_data) update.message.reply_text(text, reply_markup=get_keyboard(), parse_mode=ParseMode.HTML) return ConversationHandler.END def anketa_skip_comment(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) text = """ <b>Фамилия Имя:</b> {anketa_name} <b>Оценка:</b> {anketa_rating}""".format(**user_data) update.message.reply_text(text, reply_markup=get_keyboard(), parse_mode=ParseMode.HTML) return ConversationHandler.END def dontknow(bot, update, user_data): user = get_or_create_user(db, update.effective_user, update.message) update.message.reply_text("Не понимаю") def subscribe(bot, update): user = get_or_create_user(db, update.effective_user, update.message) if not user.get('subscribed'): toggle_subscription(db, user) update.message.reply_text('Вы подписались') @mq.queuedmessage def send_updates(bot, job): for user in get_subscribers(db): try: bot.sendMessage(chat_id=user['chat_id'], text="BUZZZ!") except error.BadRequest: print('Chat {} not found'.format(user['chat_id'])) def unsubscribe(bot, update): user = get_or_create_user(db, update.effective_user, update.message) if user.get('subscribed'): toggle_subscription(db, user) update.message.reply_text("Вы отписались") else: update.message.reply_text("Вы не подписаны, нажмите /subscribe чтобы подписаться") def set_alarm(bot, update, args, job_queue): try: seconds = abs(int(args[0])) job_queue.run_once(alarm, seconds, context=update.message.chat_id) except(IndexError, ValueError): update.message.reply_text("Введите количество секунд после /alarm") @mq.queuedmessage def alarm(bot, job): bot.sendMessage(chat_id=job.context, text="Сработал будильник!")