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 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 give_reward_base_on_type(reward_of_the_day, user_id, username): logging_message = f"Updating user {username} ({user_id})'s wallet" response_result = False if reward_is_voucher(reward_of_the_day): voucher_info = reward_of_the_day LoggerManager.general_logs( f"{logging_message}. Adding voucher {voucher_info[0]} into the wallet") response_result = SharedFunctions.add_voucher_to_user_wallet(voucher_info, user_id, username) elif reward_is_snapcoin(reward_of_the_day): snapcoin_amount = reward_of_the_day LoggerManager.general_logs( f"{logging_message}. Adding {snapcoin_amount} snapcoins into the wallet") response_result = SharedFunctions.add_coin_to_user_wallet(snapcoin_amount, '+', user_id, username) else: LoggerManager.exception_logs( f"Unknown reward. Error occurred somewhere") return response_result
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 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 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 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 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 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 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 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 send_message_to_snapee_assistant(update, context, snapee_asst_id, photo_id): user_id = update.message.from_user.id username = update.message.from_user.username LoggerManager.general_logs( f"Sending user {username} ({user_id})'s photo to snapeeassistant now.") try: context.bot.send_photo(snapee_asst_id, photo=photo_id, caption=f"User: {username} ({user_id})") return True except Exception as e: LoggerManager.exception_logs(e) LoggerManager.exception_logs( f"Something went wrong while sending user {username} ({user_id})'s photo to SnapeeAssistant" )
def validate_referral_code(message_from_user): LoggerManager.general_logs(f"Verifying referral code {message_from_user}") referrer_telegram_id_and_snapcoin_amt = UserManager.is_valid_referral_code( message_from_user) if not referrer_telegram_id_and_snapcoin_amt: LoggerManager.exception_logs( f"Referral code: {message_from_user} is invalid! Prompting user to re-enter again.") return referrer_telegram_id = referrer_telegram_id_and_snapcoin_amt[0][0] referrer_snapcoin_amt = referrer_telegram_id_and_snapcoin_amt[0][1] LoggerManager.general_logs( f"Referral code found! Referrer's telegram id: {referrer_telegram_id} ({referrer_snapcoin_amt}) snapcoins.") return referrer_telegram_id_and_snapcoin_amt
def generate_start_command_message(update, result): user_id = update.message.from_user.id username = update.message.from_user.username if len(result) == EMPTY_LIST: LoggerManager.general_logs( f"User: {username} ({user_id}) is not a member. Redirecting to registration now." ) return update.message.reply_text( MessageTemplates.new_user_found_message) LoggerManager.general_logs(f"User: {username} ({user_id}) is a member.") message_to_send = MessageTemplates.welcome_back_message( update.message.from_user.username) update.message.reply_text(message_to_send, disable_web_page_preview=True, reply_markup=KeyboardTemplates.start_keyboard)
def new_user_email(update, context): user_id = str(update.message.from_user.id) LoggerManager.general_logs( f"Checking if email is valid for User: {update.message.from_user.username} ({user_id}).") message_from_user = update.message.text if not re.match(REGEX_EMAIL_CHECKER, message_from_user): update.message.reply_text(MessageTemplates.invalid_email_message) return 'NewUserEmail' context.user_data.update({ f'{user_id}': {'email': message_from_user} }) update.message.reply_text(MessageTemplates.ask_gender_message, reply_markup=KeyboardTemplates.gender_keyboard) return 'NewUserGender'
def new_user_gender(update, context): user_id = str(update.message.from_user.id) LoggerManager.general_logs( f"Checking gender info for User: {update.message.from_user.username} ({user_id}).") message_from_user = update.message.text if message_from_user != MALE_GENDER and message_from_user != FEMALE_GENDER: update.message.reply_text(MessageTemplates.invalid_response_message, reply_markup=KeyboardTemplates.gender_keyboard) return 'NewUserGender' context.user_data[user_id].update({ 'gender': message_from_user }) update.message.reply_text(MessageTemplates.ask_referral_message) return 'NewUserReferralInput'
def update_database_table(update_statement, values): try: conn = init_db_connection() if conn.is_connected(): cursor = conn.cursor() cursor.execute(update_statement, values) conn.commit() cursor.close() conn.close() return True else: LoggerManager.general_logs( 'Connection to SQL DB cannot be established.') conn.close() except Error as e: LoggerManager.exception_logs(e)
def query_database_no_conditions(query_statement): try: conn = init_db_connection() if conn.is_connected(): cursor = conn.cursor() cursor.execute(query_statement) result = cursor.fetchall() cursor.close() conn.close() return result else: LoggerManager.general_logs( 'Connection to SQL DB cannot be established.') conn.close() except Error as e: LoggerManager.exception_logs(e)
def referral_code_instruction_start(update, context): ReusableComponents.log_command_accessed_timing(update) user_id = update.message.from_user.id username = update.message.from_user.username referral_code = get_user_referral_code(user_id) if not referral_code: LoggerManager.general_logs( f"User {username} ({user_id} is not a member!") update.message.reply_text(MessageTemplates.new_user_found_message) return update.message.reply_text(MessageTemplates.referral_code_info_message) update.message.reply_text( MessageTemplates.gen_referral_code_instruction_template(referral_code), disable_web_page_preview=True) ReusableComponents.prompt_user_next_action(update)