def display_quest_description(update, context): user_choice = update.message.text if is_invalid_user_choice(user_choice, context): update.message.reply_text(MessageTemplates.invalid_response_message) return 'QuestDescription' # Get quest description from database parsed_user_choice = int(user_choice) - 1 selected_quest_title = context.chat_data["quest_titles"][ parsed_user_choice][0] quest_description = QuestManager.get_list_of_available_quests_for_the_week( selected_quest_title) if not quest_description: username = update.message.from_user.username user_id = update.message.from_user.id LoggerManager.general_logs( f"Error occurred while {username} ({user_id}) is viewing quest description" ) return ConversationHandler.END update.message.reply_text(MessageTemplates.gen_quest_description_message( selected_quest_title, quest_description), disable_web_page_preview=True) return 'ImageResponse'
def send_quest_image_start(update, context): ReusableComponents.log_command_accessed_timing(update) user_id = update.message.from_user.id username = update.message.from_user.username if not user_is_a_member(update): LoggerManager.general_logs( f"User {username} ({user_id}) is not a member!") update.message.reply_text(MessageTemplates.new_user_found_message) return ConversationHandler.END list_of_available_quests = get_list_of_available_quests_for_the_week() if len(list_of_available_quests) <= 0: update.message.reply_text(MessageTemplates.error_message) ReusableComponents.prompt_user_next_action(update) return ConversationHandler.END context.chat_data["quest_titles"] = list_of_available_quests update.message.reply_text( MessageTemplates.send_quest_image_message(list_of_available_quests)) return 'QuestDescription'
def add_voucher_to_user_wallet(voucher_info, user_id, username): expiry_date = TimeManager.gen_expiry_date() voucher_id_in_db = voucher_info[2] voucher_to_be_added_into_db = { 'telegram_id': user_id, 'asset_type': 'coupon', 'asset_id': voucher_id_in_db, 'asset_value': 1, 'expiry_date': expiry_date } result = UserManager.add_user_voucher(voucher_to_be_added_into_db) logging_message = f"{voucher_info[0]} voucher to user {username} ({user_id})'s wallet!" if result: LoggerManager.general_logs(f"Successfully added {logging_message}") voucher_id_to_be_updated = voucher_info[7] VoucherManager.update_voucher_details(voucher_id_to_be_updated, 'dailycoupons', 'issueamount') return True else: LoggerManager.exception_logs( f"Error occurred while adding {logging_message}")
def main(): # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary updater = Updater(_TOKEN, use_context=True) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Register handlers to dispatcher # On different commands - answer in Telegram TelegramHandlers.initialize_dispatchers(dispatcher) # Start the Bot current_environment_type = IOassetsManager.get_project_environment() if current_environment_type == 'development': updater.start_polling() elif current_environment_type == 'production': updater.start_webhook(listen="127.0.0.1", port=_PORT, url_path=_TOKEN) updater.bot.setWebhook(f"{_WEBHOOK_URL}{_TOKEN}") else: raise EnvironmentError( 'Invalid project environment. Please set a valid environment!') LoggerManager.general_logs("Bot started!") # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle() LoggerManager.general_logs("Bot shutting down now...")
def get_list_of_admins(): try: with open(_admin_info_file_path, 'r') as file: return [line.strip() for line in file] except Exception as e: LoggerManager.exception_logs(e) LoggerManager.exception_logs("Error occurred while getting admin list")
def exchange_start(update, context): ReusableComponents.log_command_accessed_timing(update) update.message.reply_text(MessageTemplates.loading_message) user_id = update.message.from_user.id username = update.message.from_user.username if is_not_a_registered_member(update): LoggerManager.general_logs( f"User: {username} ({user_id}) is not a member. Redirecting to registration now." ) update.message.reply_text(MessageTemplates.new_user_found_message) return ConversationHandler.END exchangeable_voucher_list = UserManager.get_user_exchangeable_vouchers_and_snapcoin_amt( user_id) if len(exchangeable_voucher_list) <= EMPTY_LIST_LENGTH: LoggerManager.general_logs(f"No vouchers to exchange currently.") update.message.reply_text( MessageTemplates.no_vouchers_claimable_message) ReusableComponents.prompt_user_next_action(update) return ConversationHandler.END send_exchangeable_message_to_user(update, context, exchangeable_voucher_list) return 'ExchangeInput'
def get_all_allocated_new_user_vouchers(): query_statement = ''' select title, teleimageurl, couponid, businesshours, location, website, dailycoupon_table.id, phone from snapshop_property.coupons coupon_table inner join snapshop_property.dailycoupons dailycoupon_table on coupon_table.id = dailycoupon_table.couponid inner join snapshop_property.shops shop_table on coupon_table.shopid = shop_table.id where dailycoupon_table.issueamount != dailycoupon_table.totalamount and dailycoupon_table.action = 'new_user' and coupon_table.id >= 13 and isdeleted = 0 ''' try: return db_manager.query_database_no_conditions(query_statement) except Exception as e: LoggerManager.exception_logs(e)
def get_weekly_allocated_voucher(voucher_id): query_statement = ''' select title, teleimageurl, couponid, businesshours, location, website, dailycoupon_table.id, phone from snapshop_property.coupons coupon_table inner join snapshop_property.dailycoupons dailycoupon_table on coupon_table.id = dailycoupon_table.couponid inner join snapshop_property.shops shop_table on coupon_table.shopid = shop_table.id where dailycoupon_table.issueamount != dailycoupon_table.totalamount and dailycoupon_table.id = %s and action = 'weekly_login' and isdeleted = 0 ''' value = (voucher_id, ) try: return db_manager.query_database_with_conditions( query_statement, value) except Exception as e: LoggerManager.exception_logs(e)
def add_voucher_to_user_wallet(user_selected_voucher, user_id, username): expiry_date = TimeManager.gen_expiry_date() voucher_id_in_db = user_selected_voucher[1] voucher_title = user_selected_voucher[2] exchange_fee = user_selected_voucher[9] voucher_to_be_added_into_db = { 'telegram_id': user_id, 'asset_type': 'coupon', 'asset_id': voucher_id_in_db, 'asset_value': 1, 'expiry_date': expiry_date } result = UserManager.add_user_voucher(voucher_to_be_added_into_db) if result: exchange_voucher_id_to_be_updated = user_selected_voucher[8] VoucherManager.update_voucher_details( exchange_voucher_id_to_be_updated, 'exchangecoupons', 'issueamount') UserManager.update_user_snapcoin_amt(exchange_fee, '-', user_id) UserManager.update_user_voucher_history(user_id, 'exchanged', voucher_id_in_db) return True LoggerManager.exception_logs( f"Error occurred while adding {voucher_title} voucher to user {username} ({user_id})'s wallet!" )
def broadcast_message_to_users(context, broadcast_message, target_users_list): blocked_users_list, unreachable_users_list, unexpected_error_occurred_users_list = [], [], [] for user_id in target_users_list: try: if user_id == EMPTY_USER_ID: continue context.bot.send_message(chat_id=user_id, text=broadcast_message) except telegram.error.Unauthorized: blocked_users_list.append(user_id) except telegram.error.BadRequest: unreachable_users_list.append(user_id) except Exception as e: error_message = MessageTemplates.gen_error_message_while_sending_to_user( user_id) LoggerManager.exception_logs(e) LoggerManager.exception_logs(error_message) unexpected_error_occurred_users_list.append(user_id) error_occurred_while_sending_to_users_dict = SharedFunctions.gen_broadcast_error_for_users_report( blocked_users_list, unreachable_users_list, unexpected_error_occurred_users_list) return error_occurred_while_sending_to_users_dict
def claim_voucher(update, context): user_response = update.message.text if is_invalid_shop_code(user_response): update.message.reply_text(MessageTemplates.invalid_shop_code_message) return 'ClaimVoucher' user_id = str(update.message.from_user.id) username = update.message.from_user.username LoggerManager.general_logs( f"User {username} ({user_id}) wants to claim their voucher!") update.message.reply_text(MessageTemplates.loading_message) response_result = delete_voucher_from_user_wallet(context, username, user_id) if not response_result: update.message.reply_text(MessageTemplates.error_message) else: user_selected_voucher_title = context.user_data[user_id]['user_selected_voucher'][2] inform_user_claim_successful(update, user_selected_voucher_title) ReusableComponents.prompt_user_next_action(update) context.user_data[user_id].clear() return ConversationHandler.END
def new_user_referral_input(update, context): user_id = str(update.message.from_user.id) username = update.message.from_user.username LoggerManager.general_logs( f"Check if user: {username} ({user_id}) was referred by someone.") message_from_user = update.message.text referrer_telegram_id_and_snapcoin_amt = validate_referral_code( message_from_user) if not referrer_telegram_id_and_snapcoin_amt: update.message.reply_text(MessageTemplates.invalid_referrer_message) return 'NewUserReferralInput' award_referrer_referee(context, user_id, username, referrer_telegram_id_and_snapcoin_amt) register_new_user(update, context) return ConversationHandler.END
def check_membership_status(update): user_id = update.message.from_user.id LoggerManager.general_logs( f"Checking if user {update.message.from_user.username} ({user_id}) is a member" ) return UserManager.is_a_member(user_id)
def target_user_list_is_empty(target_users_list): if len(target_users_list) == EMPTY_USER_LIST or not target_users_list: LoggerManager.general_logs( "User list is empty! No users to broadcast message to.") return True else: LoggerManager.general_logs( "User list is not empty! Preparing to send to users.")
def send_message_to_referrer(context, referrer_id, referee_username): LoggerManager.general_logs( f"Sending notification to user {referrer_id} about referring now!") referrer_message_to_send = MessageTemplates.gen_referrer_bonus_message( referee_username) context.bot.send_message(chat_id=referrer_id, text=referrer_message_to_send)
def inform_sender_no_of_users_to_broadcast(update, target_users_list): length_of_target_users = len(target_users_list) LoggerManager.general_logs( f"Broadcasting message to {length_of_target_users} user(s) now") message_to_inform_sender = MessageTemplates.gen_message_to_inform_sender( length_of_target_users) update.message.reply_text(message_to_inform_sender)
def timeout_handler(update, context): LoggerManager.general_logs( f"No action performed after {context.effective_message.text} " + f"by user {context.effective_message.chat.username} " + f"({context.effective_message.chat.id})") context.message.reply_text(MessageTemplates.action_auto_cancelled_message, reply_markup=KeyboardTemplates.start_keyboard) return ConversationHandler.END
def send_message_to_referee(context, referee_id, referee_username): LoggerManager.general_logs( f"Awarding referee {referee_username} ({referee_id}) 500 snapcoins now.") context.user_data[referee_id].update({ 'referral_bonus': RewardManager.REFERRAL_BONUS_AMT }) context.bot.send_message(chat_id=referee_id, text=MessageTemplates.congratulate_referee_message)
def user_does_not_exists(user_login_details, update): if len(user_login_details) <= 0: LoggerManager.general_logs( f"User: {update.message.from_user.username} ({update.message.from_user.id}) " + "is not an existing member! Redirecting to sign up now!") update.message.reply_text(MessageTemplates.new_user_found_message) return True return False
def is_valid_choice(user_choice_str_format, context, user_id): try: user_choice = int(user_choice_str_format) - 1 user_selected_voucher = "" if user_choice >= MINIMUM_VOUCHER_INDEX_RANGE: user_selected_voucher = context.user_data[user_id]['claimable_vouchers'][user_choice] return user_selected_voucher except Exception as e: LoggerManager.exception_logs(e)
def dispatch_voucher(update, voucher_path, caption_to_send): try: LoggerManager.general_logs( f"Sending voucher to {update.message.from_user.username} ({update.message.from_user.id}) now" ) update.message.reply_photo(photo=open(voucher_path, 'rb'), caption=caption_to_send) except Exception as e: update.message.reply_text(MessageTemplates.error_message) LoggerManager.exception_logs(e)
def claimed_promo_code_before(code_entered_by_user, user_id, username): if UserManager.user_claimed_promo_code_before(code_entered_by_user, user_id): LoggerManager.general_logs( f"User {username} ({user_id}) has claimed the promo code {code_entered_by_user} before!" ) return True LoggerManager.general_logs( f"User {username} ({user_id}) has not claimed the promo code {code_entered_by_user} before! " + "Validating code now") return False
def update_voucher_details(voucher_id, table, field): update_statement = f''' update snapshop_property.{table} set {field} = {field} + 1 where id = %s ''' value = (voucher_id, ) try: return db_manager.update_database_table(update_statement, value) except Exception as e: LoggerManager.exception_logs(e)
def get_random_new_user_voucher(): vouchers = VoucherManager.get_all_allocated_new_user_vouchers() if len(vouchers) == 0: LoggerManager.exception_logs( "There are not vouchers allocated for new user bonus!") if len(vouchers) > 1: random_voucher_index = randomize_voucher_index(len(vouchers)) else: random_voucher_index = 0 return vouchers[random_voucher_index]
def get_all_vouchers_owned_by_user(user_id, username): list_of_vouchers_owned_by_user = UserManager.get_all_vouchers_owned_by_user( user_id) if len(list_of_vouchers_owned_by_user) == EMPTY_LIST_LENGTH: LoggerManager.general_logs( f"User {username} ({user_id}) does not have any vouchers in their wallet.") return filtered_list_of_vouchers = ExpiryManager.filter_expired_and_non_expired_vouchers( list_of_vouchers_owned_by_user, user_id) return filtered_list_of_vouchers
def add_coin_to_user_wallet(snapcoin_amount, arithmetic_operator, user_id, username): result = UserManager.update_user_snapcoin_amt(snapcoin_amount, arithmetic_operator, user_id) logging_message = f"{snapcoin_amount} to user {username} ({user_id})'s wallet!" if result: LoggerManager.general_logs(f"Successfully added {logging_message}") return True else: LoggerManager.exception_logs( f"Error occurred while adding {logging_message}")
def award_referrer_referee(context, referee_id, referee_username, referrer_telegram_id_and_snapcoin_amt): referrer_id = referrer_telegram_id_and_snapcoin_amt[0][0] referrer_snapcoin_amt = referrer_telegram_id_and_snapcoin_amt[0][1] updated_snapcoin_amt = referrer_snapcoin_amt + \ RewardManager.REFERRAL_BONUS_AMT LoggerManager.general_logs( f"Referrer {referrer_id} updated! Previously: {referrer_snapcoin_amt}, updated: {updated_snapcoin_amt}") UserManager.update_referrer_snapcoin_amt(referrer_id, updated_snapcoin_amt) send_message_to_referrer(context, referrer_id, referee_username) send_message_to_referee(context, referee_id, referee_username) UserManager.update_user_referal_history_table(referrer_id, referee_id)
def promo_code_start(update, context): ReusableComponents.log_command_accessed_timing(update) result = ReusableComponents.check_membership_status(update) if len(result) == 0: LoggerManager.general_logs( f"User: {update.message.from_user.username} ({update.message.from_user.id}) " + "is not an existing member! Redirecting to sign up now!") update.message.reply_text(MessageTemplates.new_user_found_message) return ConversationHandler.END update.message.reply_text(MessageTemplates.prompt_enter_promo_code_message) return 'PromoCodeInput'
def validate_promo_code(code_entered_by_user, user_id, username): if claimed_promo_code_before(code_entered_by_user, user_id, username): return CLAIMED_BEFORE date_today = TimeManager.get_current_date() vouchers_in_promo_code = VoucherManager.get_all_promo_code_vouchers( code_entered_by_user, date_today) if not vouchers_in_promo_code: LoggerManager.general_logs( f"Promo code {code_entered_by_user} entered by user {username} ({user_id}) is not valid!" ) return INVALID_PROMOCODE return vouchers_in_promo_code
def get_shop_by_code_entered(code_entered): query_statement = ''' select code from snapshop_property.shops where code = %s ''' value = (code_entered, ) try: return db_manager.query_database_with_conditions( query_statement, value) except Exception as e: LoggerManager.exception_logs(e)