def callback_inline_daily(call): """writing time to db""" user = User.query.filter_by(chat_id=call.from_user.id).first() user_id = user.id lang = user.language reminder_hours = call.data[:2] reminder_minutes = call.data[3:5] existing_reminder = Reminder.query.filter_by(user_id=user_id, hours=reminder_hours, minutes=reminder_minutes, is_phenomenon=False).first() if existing_reminder: # if reminder exists scheduler.remove_job( job_id=existing_reminder.job_id, jobstore='default') # remove the time from schedule db.session.delete(existing_reminder) # remove the time from db db.session.commit() text = f"{hints['schedule delete'][lang]}" else: # if reminder does not exist new_reminder = Reminder(user_id=user_id, hours=reminder_hours, minutes=reminder_minutes, is_phenomenon=False) db.session.add(new_reminder) db.session.commit() set_daily(new_reminder, reminder_hours, reminder_minutes) text = f"{hints['schedule set'][lang]} {reminder_hours}:{reminder_minutes}" callback_inline_daily_min(call) bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text=text)
def callback_remove_all_daily(call): user = User.query.filter_by(chat_id=call.from_user.id).first() all_reminders = Reminder.query.filter_by(user_id=user.id, is_phenomenon=False).all() for reminder in all_reminders: scheduler.remove_job( job_id=reminder.job_id, jobstore='default') # remove the time from schedule db.session.delete(reminder) # remove the time from db db.session.commit() try: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=f"{hints['time daily'][user.language]}", reply_markup=gen_markup_hours( user_id=user.id, is_phenomenon=False, lang=user.language)) except: pass finally: bot.answer_callback_query( callback_query_id=call.id, show_alert=False, text=f"{hints['schedule delete'][user.language]}")
def callback_phenomenon(call): """ handle phenomenon db add phenomenon to db """ user = User.query.filter_by(chat_id=call.from_user.id).first() phenomenon_data = call.data[11:] phenomenon = Phenomenon.query.filter_by(phenomenon=phenomenon_data, user_id=user.id).first() try: db.session.delete(phenomenon) except UnmappedInstanceError as e: logger.error( f'The phenomenon has not been found. Creating new one\n{e}') new_phenomenon = Phenomenon(phenomenon=phenomenon_data, user_id=user.id) db.session.add(new_phenomenon) text = hints['phenomenon set'][user.language] else: text = hints['phenomenon delete'][user.language] db.session.commit() bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=hints['phenomena intro'][user.language], reply_markup=gen_markup_phenomena( user.id, user.language)) bot.answer_callback_query( callback_query_id=call.id, show_alert=False, text=f"{hints['phenomenon set del'][user.language]} " f"{phenomenon_button_names[phenomenon_data][user.language]} {text}")
def callback_all_phenomena(call): """ handle inline button 'all phenomena' add all phenomena to db """ user = User.query.filter_by(chat_id=call.from_user.id).first() all_ph_from_db = Phenomenon.query.filter_by(user_id=user.id, value=None).all() if len(all_ph_from_db) == 7: for ph in all_ph_from_db: db.session.delete(ph) text = hints['all untick'][user.language] else: for ph in phenomena_list: new_phenomenon = Phenomenon.query.filter_by( phenomenon=ph, user_id=user.id).first() if new_phenomenon is None: new_phenomenon = Phenomenon(user_id=user.id, phenomenon=ph) db.session.add(new_phenomenon) text = hints['all tick'][user.language] db.session.commit() bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=hints['phenomena intro'][user.language], reply_markup=gen_markup_phenomena( user.id, user.language)) bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text=text)
def callback_worker(call): if call.data == 'next': next_article(call.message.chat.id) bot.answer_callback_query(call.id) elif call.data == 'get': with get_session() as session: bot.send_message(call.message.chat.id, get_last_urls(call.message.chat.id, session)) bot.answer_callback_query(call.id)
def add_to_favourite(user_info): try: user = User.query.filter_by(username=user_info.username).first() if user is None: init_user_db(user_info) album = Album(bot.get_item()) if album in user.albums: bot.answer_callback_query(user_info.id, 'Уже есть в вашем списке', show_alert=False) else: user.albums.append(album) db.session.commit() bot.answer_callback_query(user_info.id, 'Добавленно в избранное', show_alert=False) except Exception as e: raise Exception("'add_to_favourite' error with '{}'".format(e))
def callback_phenomenon_min(call): """ handle phenomenon inline keyboard writing phenomenon time to db """ user = User.query.filter_by(chat_id=call.from_user.id).first() phenomenon_hours = call.data[:2] phenomenon_minutes = call.data[3:5] phenomenon = Reminder.query.filter_by(user_id=user.id, hours=phenomenon_hours, minutes=phenomenon_minutes, is_phenomenon=True).first() delete_ph_time_jobs(user.id) ph_reminders = Reminder.query.filter_by(user_id=user.id, is_phenomenon=True).all() for reminder in ph_reminders: db.session.delete(reminder) db.session.commit() if phenomenon: text = f"{hints['schedule delete'][user.language]}" else: new_phenomenon = Reminder(user_id=user.id, hours=phenomenon_hours, minutes=phenomenon_minutes, is_phenomenon=True) db.session.add(new_phenomenon) # commits in set_phenomenon_time func set_phenomenon_time(new_phenomenon, new_phenomenon.hours, new_phenomenon.minutes) text = f"{hints['schedule set'][user.language]} {phenomenon_hours}:{phenomenon_minutes}" callback_phenomenon_hr(call) bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text=text)
def callback_all_manual_phenomena(call): """handle all manually phenomena db add a manual phenomena to db""" user = User.query.filter_by(chat_id=call.from_user.id).first() manual_phenomena_from_db = Phenomenon.query.filter_by( user_id=user.id, is_manually=True).all() for ph in manual_phenomena_from_db: db.session.delete(ph) db.session.commit() try: bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text=hints['phenomena manually intro'][user.language], reply_markup=gen_markup_phenomena_manually(user.id, user.language)) except: pass finally: bot.answer_callback_query( callback_query_id=call.id, show_alert=False, text=f"{hints['remove manually'][user.language]}")
def callback_handler(call): chat_id = call.message.chat.id if call.data == "add_favorite": # добавление статьи в избранное # собираем данные user = User.get(User.telegram_id == chat_id) title = call.message.text.split("\n\n")[0] url = call.message.text.split("\n\n")[1] tkeyboard = tools.generate_keyboard("unfavorite") # создаем новую статью в БД try: like = Favorite(user=user, title=title, liked_url=url) like.save() # уведомляем пользователя о добавлении статьи в избранное # + добавляем к сообщение кнопку для удаления bot.answer_callback_query(call.id, "Добавлено в избранные публикации", show_alert=True) bot.edit_message_reply_markup(chat_id=chat_id, message_id=call.message.message_id, reply_markup=tkeyboard) except IntegrityError: bot.answer_callback_query(call.id, "Уже добавлено в избранные публикации", show_alert=True) bot.edit_message_reply_markup(chat_id=chat_id, message_id=call.message.message_id, reply_markup=tkeyboard) elif call.data == "delete_favorite": # delete favorite article from the db user = User.get(User.telegram_id == chat_id) tkeyboard = tools.generate_keyboard("favorite") # проверяем существование публикации в избранном # это нужно, в случае нажатия по кнопке на старом сообщении try: like = Favorite.get( Favorite.liked_url == call.message.text.split("\n\n")[1]) like.delete_instance() except DoesNotExist: logs.add_error(f"{user} - got an exception DoesNotExist") bot.answer_callback_query( call.id, "Публикация уже удалена из списка избранного", show_alert=True) bot.edit_message_reply_markup(chat_id=chat_id, message_id=call.message.message_id, reply_markup=tkeyboard) return bot.answer_callback_query(call.id, "Удалено из избранных публикаций", show_alert=True) bot.edit_message_reply_markup(chat_id=chat_id, message_id=call.message.message_id, reply_markup=tkeyboard) elif call.data == "delete_element": # удаление публикации из избранного с ипсользование следующего шага markup = types.ForceReply(selective=False) bot.send_message( chat_id, "Введите номер публикации\n/cancel - отменить действие", reply_markup=markup) bot.register_next_step_handler(call.message, get_element) elif call.data == "to_main": # вернуть reply keyboard по нажатию на inline кнопку tkeyboard = tools.generate_keyboard() bot.send_message(chat_id, "Главная", reply_markup=tkeyboard)