def changing_repeating_interval(update: Update, context: CallbackContext) -> int: text = update.message.text owner_id = str(get_user_id(update)) if text.isnumeric(): try: if int(text) > 0: update_dict = {'repeat': 'Daily-' + str(text)} else: update_dict = {'repeat': 'Once'} task_id = bl.updating_inactive_task(update_dict, owner_id) msg = 'it was ok' except Exception as e: my_logging('error', str(e)) msg = 'Sorry, right now we faced a difficulty.(396)' msg = msg_validate(msg) reply_keyboard_additional = get_additional_task_info_as_keyboards( task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) update.message.reply_text(msg, reply_markup=reply_markup) return CHANGING_TASK else: update.message.reply_text( 'I expect a number, please give me a number or 0 for "without repeating"' ) my_logging( 'info', ' __Interface__ changing_repeating_interval __> result: Noting. Stay at this status' )
def adding_task(update: Update, context: CallbackContext) -> int: text = update.message.text owner_id = get_user_id(update) group_id = 'P_' + owner_id try: task_id = bl.adding_task(text, group_id, owner_id) was_successful = True msg = 'it was ok' except Exception as e: my_logging('error', str(e)) msg = 'Sorry, right now we faced a difficulty.(179)' msg = msg_validate(msg) reply_keyboard_additional = get_additional_task_info_as_keyboards(task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) update.message.reply_text(msg, reply_markup=reply_markup) if was_successful and False: user_ids = [91686406, 96166505] #bl.get_user_ids_in_group('G_1') user_id = get_user_id(update) bot = telepot.Bot(os.environ['tlg_token']) for uid in user_ids: if uid != user_id: bot.sendMessage( uid, '"' + text + '" has been added to the group tasks') return CHANGING_TASK
def cat_selecting(update: Update, context: CallbackContext) -> int: text = update.message.text if text == 'Show Tasks': try: user_id = get_user_id(update) reply_markup, _ = get_tasks_as_keyboards(user_id) update.message.reply_text('Please choose:', reply_markup=reply_markup) except Exception as e: my_logging('error', ' __Interface__ cat_selecting __>' + str(e)) msg = 'Sorry, right now we faced a difficulty.(207)' update.message.reply_text(msg) return SELECTING_COMMAND elif text == 'New Task': update.message.reply_text('What is the task title?') return NEW_TASK elif text == 'Setting': user_id = get_user_id(update) reply_markup = get_settings_as_keyboards(user_id) update.message.reply_text('Please choose:', reply_markup=reply_markup) return CHANGING_SETTING else: update.message.reply_text(text=f"I confuesed, please try again.") return SELECTING_COMMAND
def get_tasks_as_keyboards(user_id, category='Current suggestion'): if category == 'Current suggestion': # 'short':1,'Today':1,'current':1, done:0 task_list, has_new = bl.get_tasks_list( user_id, 'not_done & current & start_end') elif category == 'All current': # 'short':0,'Today':1,'current':1, done:0 task_list, has_new = bl.get_tasks_list( user_id, 'not_done & current & start_end') elif category == 'All today': # 'short':0,'Today':1,'current':0, done:0 task_list, has_new = bl.get_tasks_list(user_id, 'not_done & start_end') else: my_logging('error', 'Category is out of expectation ') if len(task_list) > 0: buttoms = [ InlineKeyboardButton( (str(round(row['time_cost'])) + '.' if row['time_cost'] == row['time_cost'] else '') + row['name'], callback_data='Task,' + row['name'] + ',' + str(row['id'])) for idx, row in task_list.iterrows() ] keyboard = my_reshape(buttoms) keyboard += [[ InlineKeyboardButton('Back - ' + str( time_plus_now( user_id, task_list.time_cost.apply(lambda x: (x + 5 + min( x, 60) / 6) if x == x else 0).sum())), callback_data='Task_categories') ]] else: keyboard = [[ InlineKeyboardButton( 'There is not any task to do, you can add new tasks. Back', callback_data='Task_categories') ]] reply_markup = InlineKeyboardMarkup(keyboard) current_time_user = bl.time_to_num(bl.get_time(user_id)) time_of_last_task_which_has_done = bl.get_last_time_a_task_has_done( user_id) sleep_time = int(os.environ['sleep_time']) trigger = len(task_list) > 0 and ( has_new or time_of_last_task_which_has_done + sleep_time < current_time_user) print('''\t\tlen task list: {} has new: {} time_of_last_task_which_has_done: {} sleep_time: {} current_time_user: {} '''.format( len(task_list) > 0, has_new, time_of_last_task_which_has_done, sleep_time, current_time_user)) return reply_markup, trigger
def start(update: Update, context: CallbackContext) -> int: my_logging( 'info', ' __Interface__ start __> update:' + str(update) + '| CallbackContext:' + str(CallbackContext)) name_tlg = update['message']['chat']['username'] + ' / ' + update[ 'message']['chat']['first_name'] owner_id = get_user_id(update) bl.add_user_if_not_exist(owner_id, name_tlg) menu(update, context) my_logging('info', ' __Interface__ start __> result: SELECTING_COMMAND') return SELECTING_COMMAND
def change_status(val, text, update): ''' a wrapper for change status of business_layer to prevent of failing and keep program running ''' user_id = get_user_id(update) try: msg = bl.change_status(val, text, user_id) except Exception as e: my_logging('error', ' __Interface__ change_status __> Error:' + str(e)) msg = 'Sorry, right now we faced a difficulty.(46)' return msg
def get_time(owner_id=None, diff_time=None): if not diff_time: if owner_id: df_users = dl.reading_file('users.csv') diff_time = df_users[df_users.id == int( owner_id)].local_time_diff.max() else: my_logging( 'error', ' __Business__ get_time __> Error: owner_id and diff_time are empty' ) raise result = (datetime.datetime.now().astimezone(timezone('Etc/GMT0')) + datetime.timedelta(hours=int(diff_time))).time() return result
def talker(update): for user_id in bl.user_id_list(): reply_markup, trigger = get_tasks_as_keyboards(user_id) if trigger: try: first_task = '' try: first_task = reply_markup.inline_keyboard[0][0].text except: pass update.bot.sendMessage(chat_id=user_id, text=first_task + ' \nwould you like to do a task?', reply_markup=reply_markup) except Exception as e: my_logging('error', str(e))
def changing_title(update: Update, context: CallbackContext) -> int: text = update.message.text owner_id = str(get_user_id(update)) try: update_dict = {'name': text} task_id = bl.updating_inactive_task(update_dict, owner_id) msg = 'it was ok' except Exception as e: my_logging('error', str(e)) msg = 'Sorry, right now we faced a difficulty.(419)' msg = msg_validate(msg) reply_keyboard_additional = get_additional_task_info_as_keyboards(task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) update.message.reply_text(msg, reply_markup=reply_markup) return CHANGING_TASK
def changing_setting(update: Update, _: CallbackContext) -> None: #owner_id = str(get_user_id(update)) query = update.callback_query # CallbackQueries need to be answered, even if no notification to the user is needed # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery query.answer() val = query.data.split(',') my_logging('info', ' __Interface__ changing_setting __>>> val: ' + str(val)) if val[0] == 'Back': query.edit_message_text(text="Done.") return SELECTING_COMMAND elif val[0] == 'Setting': query.edit_message_text(text="What is the new local time difference?") return CHANGING_LOCAL_TIME else: query.edit_message_text(text=f"I confuesed, please try again.") return SELECTING_COMMAND
def changing_local_time(update: Update, context: CallbackContext) -> int: text = update.message.text owner_id = str(get_user_id(update)) try: if text.isnumeric(): update_dict = {'local_time_diff': text} _ = bl.updating_setting(update_dict, owner_id) msg = 'ok, it changed' else: msg = 'it was not a number' except Exception as e: my_logging('error', str(e)) msg = 'Sorry, right now we faced a difficulty.(419)' msg = msg_validate(msg) reply_markup = get_settings_as_keyboards(owner_id) update.message.reply_text(msg, reply_markup=reply_markup) return CHANGING_SETTING
def get_user_id(update): if update['callback_query']: user_id = update['callback_query']['message']['chat']['id'] my_logging('info', ' __Interface__ get_user_id __> result:' + str(user_id)) return str(user_id) elif update['message']: user_id = update['message']['chat']['id'] my_logging('info', ' __Interface__ get_user_id __> result:' + str(user_id)) return str(user_id) my_logging( 'error', ' __Interface__ get_user_id __> there is not any user_id in the update' ) raise
def changing_task(update: Update, _: CallbackContext) -> None: owner_id = str(get_user_id(update)) query = update.callback_query # CallbackQueries need to be answered, even if no notification to the user is needed # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery query.answer() val = query.data.split(',') my_logging('info', ' __Interface__ changing_task __>>> val: ' + str(val)) if val[0] == 'Add': if val[1] == 'Title': query.edit_message_text(text="What is the new title for the task?") return CHANGING_TASK_TITLE elif val[1] == 'Repeating': keyboard = [ [ InlineKeyboardButton('Once', callback_data=f'Repeating,Once'), InlineKeyboardButton('Daily', callback_data=f'Repeating,Daily'), ], ] reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text(text=f"How is it repeating?", reply_markup=reply_markup) return CHANGING_TASK elif val[1] == 'Duration': keyboard = get_duration_keyboard(owner_id) reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text(text=f"what is the duration?", reply_markup=reply_markup) return CHANGING_TASK elif val[1] == 'Who': keyboard = get_who_keyboard(owner_id) reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text(text=f"Who is going to do this?", reply_markup=reply_markup) return CHANGING_TASK elif val[1] == 'Start Date': pass elif val[1] == 'End Date': pass elif val[1] == 'Add': update_dict = {'status': 'active'} task_id = bl.updating_inactive_task(update_dict, owner_id) query.edit_message_text(text="The task has been Added") return SELECTING_COMMAND elif val[1] == 'Cancel': query.edit_message_text(text="Adding task has been Canceled") return SELECTING_COMMAND elif val[0] == 'Who': update_dict = {'group_id': val[1]} task_id = bl.updating_inactive_task(update_dict, owner_id) reply_keyboard_additional = get_additional_task_info_as_keyboards( task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) query.edit_message_text(text=f"Is it ok now?", reply_markup=reply_markup) return CHANGING_TASK elif val[0] == 'Repeating': if val[1] == 'Once': update_dict = {'repeat': 'Once'} task_id = bl.updating_inactive_task(update_dict, owner_id) reply_keyboard_additional = get_additional_task_info_as_keyboards( task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) query.edit_message_text(text=f"Is it ok now?", reply_markup=reply_markup) return CHANGING_TASK if val[1] == 'Daily': query.edit_message_text( text="Every how many day you want to do this task?") return CHANGING_TASK_REPEATING_INTERVAL elif val[0] == 'Duration': update_dict = {'duration': val[1]} task_id = bl.updating_inactive_task(update_dict, owner_id) reply_keyboard_additional = get_additional_task_info_as_keyboards( task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) query.edit_message_text(text=f"Is it ok now?", reply_markup=reply_markup) return CHANGING_TASK elif val[0] == 'Edit': update_dict = {'status': 'active'} task_id = bl.updating_inactive_task(update_dict, owner_id) query.edit_message_text(text="The task has been Added") return SELECTING_COMMAND else: query.edit_message_text(text=f"I confuesed, please try again.") return SELECTING_COMMAND
def InlineKeyboardHandler(update: Update, _: CallbackContext) -> None: query = update.callback_query # CallbackQueries need to be answered, even if no notification to the user is needed # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery query.answer() val = query.data.split(',') if val[0] == 'Task': keyboard = [ [ InlineKeyboardButton( 'Done', callback_data=f'Action,Done,{val[2]},{val[1]}') ], [ InlineKeyboardButton( 'Postponed', callback_data=f'Action,Postpone,{val[2]},{val[1]}'), #InlineKeyboardButton('Done Yesterday', callback_data=f'_Action,Done yesterday,{val[2]},{val[1]}'), InlineKeyboardButton( '#Undo', callback_data=f'_Action,Undo,{val[2]},{val[1]}') ], [ InlineKeyboardButton('Cancel', callback_data=f'Cancel,0,0,{val[1]}'), InlineKeyboardButton( '#Delete', callback_data=f'Action,Delete,{val[2]},{val[1]}'), InlineKeyboardButton( 'Edit', callback_data=f'Action,Edit,{val[2]},{val[1]}') ], ] reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text( text=f"You have selected {val[1]}. What is its status?", reply_markup=reply_markup) my_logging( 'info', ' __Interface__ InlineKeyboardHandler __> result:' + str(reply_markup)) return elif val[0] == 'Action': if val[1] == 'Edit': owner_id = get_user_id(update) task_id = val[2] try: bl.editing_task(task_id, owner_id) msg = 'Please Edit it:' except Exception as e: my_logging('error', str(e)) msg = 'Sorry, right now we faced a difficulty.(245)' msg = msg_validate(msg) reply_keyboard_additional = get_additional_task_info_as_keyboards( task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) query.edit_message_text(msg, reply_markup=reply_markup) return CHANGING_TASK else: msg = change_status(val[1], val[2], update) if msg == 'Done': user_id = get_user_id(update) reply_markup, _ = get_tasks_as_keyboards(user_id) msg = f'{val[3]} has been {val[1]}.' if val[1] == 'Done': msg = '<b>' + msg + '</b>' query.edit_message_text(text=msg, parse_mode=ParseMode.HTML) updater.bot.sendMessage( chat_id=user_id, text= #f'<b>{val[3]} has been {val[1]}.</b> 'Do you want to change status of any other task?', reply_markup=reply_markup, parse_mode=ParseMode.HTML) my_logging( 'info', ' __Interface__ InlineKeyboardHandler __> result:' + str(reply_markup)) return else: my_logging( 'error', ' __Interface__ InlineKeyboardHandler __> this values are not expected:' + str(val)) raise elif val[0] == 'Cancel': query.edit_message_text(text='Canceled') my_logging( 'info', ' __Interface__ InlineKeyboardHandler __> result:Canceled') elif val[0] == 'Task_categories': keyboard = [ [ InlineKeyboardButton( 'Current suggestion', callback_data=f'Category,Current suggestion') ], [ InlineKeyboardButton('All current', callback_data=f'Category,All current'), InlineKeyboardButton('All today', callback_data=f'Category,All today'), ], ] reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text( text="Which category of task you would like to see", reply_markup=reply_markup) my_logging( 'info', ' __Interface__ InlineKeyboardHandler __> result:' + str(reply_markup)) return elif val[0] == 'Category': user_id = update['callback_query']['message']['chat']['id'] reply_markup, _ = get_tasks_as_keyboards(user_id, val[1]) query.edit_message_text(text="Please choose a task", reply_markup=reply_markup) my_logging( 'info', ' __Interface__ InlineKeyboardHandler __> result:' + str(reply_markup)) return else: query.edit_message_text(text=f"I confuesed, please try again.") return SELECTING_COMMAND
msg = 'Sorry, right now we faced a difficulty.(419)' msg = msg_validate(msg) reply_keyboard_additional = get_additional_task_info_as_keyboards(task_id) reply_markup = InlineKeyboardMarkup(reply_keyboard_additional) update.message.reply_text(msg, reply_markup=reply_markup) return CHANGING_TASK ########################## main function ################################################################## # def main() -> None: logging.basicConfig( format='%(asctime)s %(levelname)s: %(message)s', handlers=[logging.FileHandler('logfile.log', 'w', 'utf-8')], level=logging.INFO) my_logging('info', ' __Interface__ main __>\n\n\n') updater = Updater(os.environ['tlg_token'], use_context=True) #updater.dispatcher.add_handler(CallbackQueryHandler(InlineKeyboardHandler)) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO conv_handler = ConversationHandler( entry_points=[ CommandHandler('start', start), CommandHandler('menu', menu), MessageHandler(Filters.regex('^(Show Tasks|New Task|Setting)$'), cat_selecting), CallbackQueryHandler(InlineKeyboardHandler) ],
def add_user_if_not_exist(owner_id, name): df_user = dl.reading_file('users.csv') if int(owner_id) not in df_user.id.to_list(): new_user_row = {'id': owner_id, 'name': name, 'local_time_diff': '-4'} df_user = df_user.append(new_user_row, ignore_index=True) dl.writing_file(df_user, 'users.csv') df_usergroup = dl.reading_file('user_group.csv') new_row = { 'group_id': 'P_' + owner_id, 'user_id': owner_id, 'branch_name': 'Personal' } df_usergroup = df_usergroup.append(new_row, ignore_index=True) dl.writing_file(df_usergroup, 'user_group.csv') df_times = dl.reading_file('times.csv') max_id = df_times.id.max() if len(df_times) > 0 else 0 new_row = [{ 'id': max_id + 1, 'title': 'All time', 'start time': 7, 'end time': 23, 'days': "0,1,2,3,4,5,6", 'owner_id': owner_id }, { 'id': max_id + 2, 'title': 'Free time', 'start time': 7, 'end time': 23, 'days': "5,6", 'owner_id': owner_id }, { 'id': max_id + 3, 'title': 'Free time', 'start time': 17, 'end time': 23, 'days': "0,1,2,3,4", 'owner_id': owner_id }, { 'id': max_id + 3, 'title': 'Free time', 'start time': 7, 'end time': 7, 'days': "0,1,2,3,4", 'owner_id': owner_id }, { 'id': max_id + 4, 'title': 'Weekend', 'start time': 7, 'end time': 23, 'days': "5,6", 'owner_id': owner_id }] df_times = df_times.append(new_row, ignore_index=True) dl.writing_file(df_times, 'times.csv') my_logging( 'info', ' __Business__ add_user_if_not_exist __> result: this rows has been added:' + str(new_row) + '|\n and this row: ' + str(new_user_row))