Back to Parent

module Sinatra
  module CommandsHelper

    # ------------------------------------------------------------------------
    # =>   MAPS THE CURRENT EVENT TO AN ACTION
    # ------------------------------------------------------------------------
    
    def event_to_action client, event
      
      puts event
      puts "Formatted Text: #{event.formatted_text}"
      
      return if event.formatted_text.nil?
      is_admin = is_admin_or_owner client, event
    
      
      # ------------------------------------------------------------------------
      # Hi Commands
      # ------------------------------------------------------------------------
      if ["hi", "hey", "hello"].any? { |w| event.formatted_text.starts_with? w }
        client.chat_postMessage(channel: event.channel, text: "Hi! I am Ginger. I can help you keep a grocery list.\n You can say `add` , `edit`, `delete`, `mark done`or `show list` ", as_user: true)
      
      # ------------------------------------------------------------------------
      # Add Commands
      # ------------------------------------------------------------------------
      elsif event.formatted_text == "add" 
        client.chat_postMessage(channel: event.channel, text:"Tell me one or multiple things you want to add to your grocery list. \n `Example: add potato, milk carton, cherries, chips` ", as_user: true )
      
      elsif event.formatted_text.starts_with? "add" 
        # we want to take the add part away
        # and then the rest we wanna add to our database
        items = event.formatted_text.gsub( "add", "" ).strip
        items.split( "," ).each do |item|
        listed = GroceryList.create( item_name: item  )
        listed.item_quantity = 1
        listed.save 
      end 
        # print the list
        all_items = GroceryList.order(:id) 
        grocery_list = ""
        all_items.each_with_index do |item, index|
        grocery_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
      end
      client.chat_postMessage(channel: event.channel, text: "I've added that to you list.\n*Your updated list is as follows:*\n" + grocery_list  , as_user: true )
     
     # ------------------------------------------------------------------------
     #Edit Commands
     # ------------------------------------------------------------------------
     elsif event.formatted_text == "edit" 
     # print the list
     all_items = GroceryList.order(:id)
     grocery_list = ""
     all_items.each_with_index do |item, index|
       grocery_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
      end
     client.chat_postMessage(channel: event.channel, text: "\n*Your grocery list is as follows:*\n" + grocery_list +"\nWhich one do you want to *edit*? \n`Example: edit 4 to potatoes`"  , as_user: true )
     
     elsif event.formatted_text.starts_with? "edit"
      # we want to take the edit part away
      # and then the rest we want to use for editing
      input  = event.formatted_text.gsub( "edit", "" ).strip
      input_words = input.split
      #getting the index number user wants to edit
      input_index = input_words[0].to_i - 1
      #removing the index number from string
      input_words.shift
      all_items = GroceryList.order(:id)
        #checking if the input exists in the list at all
        if input_index<=0 or input_index>all_items.length
          text = "\nI think you asked me to edit something that's not on your list. \nYou can say, `edit 1 to eggs`"
        #checking if user has followed 'to' syntax
        elsif input_words[0].to_s == "to"
          #removing the 'to' to get just the new edited entry
          input_words.shift
          grocery_string = input_words.join(" ")
          #saving the edit
          all_items[input_index].item_name = grocery_string
          all_items[input_index].save     
          #display edited list 
          grocery_list = ""
          edited_list = GroceryList.order(:id)
          edited_list.each_with_index do |item, index|
            grocery_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
          end
          text = "\nSure, I made the edit! *Your grocery list now looks like this:*\n" + grocery_list  
        else
          text = "\nI can make the edit right away. Say something like  ' *edit* 1 *to* eggs '"
        end
      client.chat_postMessage(channel: event.channel, text: text , as_user: true )
      
      # ------------------------------------------------------------------------ 
      #Delete Commands
      # ------------------------------------------------------------------------
      elsif event.formatted_text == "delete" 
      # print the list
      all_items = GroceryList.order(:id)
      grocery_list = ""
      all_items.each_with_index do |item, index|
        grocery_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
      end
      client.chat_postMessage(channel: event.channel, text: "\n*Your grocery list is as follows:*\n" + grocery_list +"\n\nWhich one/ones do you want to *delete*? \n`Example: delete 4`"  , as_user: true )
      
      elsif event.formatted_text == "delete all"
      client.chat_postMessage(channel: event.channel, text: "Are you sure you want to delete you *entire list*? Say `yes delete` or `no don't`"  , as_user: true )
      
      elsif ["yes delete", "yes, delete.", "yes, delete","yes del","yes please"].any? { |w| event.formatted_text.starts_with? w }
      GroceryList.destroy_all
      client.chat_postMessage(channel: event.channel, text: "Okay, I just cleaned up your entire grocery list. You're good to start a fresh new list!" , as_user: true )
      
      elsif ["no don't", "no dont", "no, don't","no, dont","dont", "no"].any? { |w| event.formatted_text.starts_with? w } 
      client.chat_postMessage(channel: event.channel, text: "Don't worry! I won't delete anything till you're absolutely sure you are done with this one!" , as_user: true )
      
      elsif event.formatted_text.starts_with? "delete"
      text= ""
      error_text =""
      # we want to take the add part away
      # and then the rest we wanna add to our database
      items = event.formatted_text.gsub( "delete", "" ).strip
      all_items = GroceryList.order(:id)
      flag = 0
      items.split( "," ).each do |num|
        #checking if the input exists in the list at all
        if num.to_i>0 and num.to_i<all_items.length+1
          i= (num.to_i)-1
          all_items[i].destroy
          flag = 1
        else
          #error text if one or more are not valid indexes
          error_text = "I think one or more of those entries that you asked for don't exist on your list.Please check if you mistyped."
        end
      end
      redefined_list = GroceryList.order(:id)
      #if no error
      if error_text == ""
      grocery_list = ""
      redefined_list.each_with_index do |item, index|
        grocery_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
      end
      text= "Okay, I've deleted that from your list. \n*Your updated list is as follows:*\n" + grocery_list
      #if there are some indexes that exist and some that don't
      elsif flag ==1
        grocery_list = ""
        redefined_list.each_with_index do |item, index|
          grocery_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
        end
      text= "I've deleted some things you asked me to. \nBut " + error_text + " \n*Your updated list is as follows:*\n" + grocery_list
      #if all indexes don't exist in the list
      else
        text = error_text
      end
      client.chat_postMessage(channel: event.channel, text: text, as_user: true )
 
      # ------------------------------------------------------------------------
      #Show Command
      # ------------------------------------------------------------------------
      
      elsif ["show", "list", "display", "grocery list", "show list" " show grocery list", "grocery"].any? { |w| event.formatted_text.starts_with? w }
      # print the list
      if GroceryList.all.empty?
        client.chat_postMessage(channel: event.channel, text: "\nYour grocery list is empty and clean to start adding things right away! \n For example, you can say `add eggs`" , as_user: true )
      else  
        all_items = GroceryList.order(:id)
        grocery_list = ""
        all_items.each_with_index do |item, index|
          grocery_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
          end
      client.chat_postMessage(channel: event.channel, text: "\n*Your grocery list :*\n" + grocery_list  , as_user: true )
      end
      
      # ------------------------------------------------------------------------
      #Mark Done Command
      # ------------------------------------------------------------------------
      elsif event.formatted_text == "mark done"
        client.chat_postMessage(channel: event.channel, text: "Awesome, you got things done?\nTell me which ones and I'll strike them out right away. \nYou can say `mark done 4,5`"  , as_user: true )

      elsif event.formatted_text.starts_with? "mark done"
        input = event.formatted_text.gsub( "mark done", "" ).strip
        done_list = ""
        done_item = ""
        recipe_ingredient = ""
        recipe = ""
        #variables for customizing text received for different error scenarios in mark done
        flag =0
        error_text = ""
        text =""
        
        all_items = GroceryList.order(:id)        
        input.split( "," ).each do |num|
          #checking if all input indexes exist in the list
          if num.to_i>0 and num.to_i<all_items.length+1
            i= (num.to_i)-1
            done_item = all_items[i][:item_name]
            recipe_ingredient = done_item
            done_list += done_item+"\n"
            all_items[i].destroy
            flag = 1
          else
            #error text if one or more are not valid indexes
            error_text = "I think one or more of those entries that you asked for don't exist on your list.Please check if you mistyped."
            end
          end
        #if no error    
        if error_text == ""
          remaining_items = GroceryList.order(:id)
          remaining_list = ""
          remaining_items.each_with_index do |item, index|
            remaining_list += "*#{ index+ 1 }.* #{ item.item_name } \n"
          end
          yummly_app_id = '19a71c98'
          yummly_app_key = 'a3bdaf1de2b3acbb2abcb8755b214874'
          # Accessing Yummly API
          base_url = "https://api.yummly.com/v1/api/recipes?_app_id=#{yummly_app_id}&_app_key=#{yummly_app_key}&requirePictures=true"
          base_url+="&allowedIngredient="+recipe_ingredient
          url = URI.parse(URI.encode(base_url.strip))
          response = HTTParty.get(url)
          data = JSON.parse(response.body)
          
          # this gets me the matches element from the JSON response
          recipe_options = data["matches"]
          recipe_names = "Try this recipe: \n"
          recipe = recipe_options.sample(1).first
          name = recipe["recipeName"]
          image = recipe["smallImageUrls"].first
          url = "http://www.yummly.co/#recipe/" + recipe["id"]
          ingredients = recipe["ingredients"].join( ", ")
          recipe_names += "*#{name}*" + " \n#{url } \n#{image} \nMade with: #{ingredients}"
          text= "Awesome! I noted that the following are done:\n" + done_list + "*Now your remaining list looks like this:*\n "+ remaining_list +"\nAlso, Here's an awesome recipe that uses "+ recipe_ingredient+ ".\n" +recipe_names
        else
          text = "Umm, I'd be happy to mark things done on the list, but some of those things don't exist on your list. Please check if you mistyped."
        end
        client.chat_postMessage(channel: event.channel, text: text, as_user: true ) 
      
      # ------------------------------------------------------------------------
      #Thanks Response
      # ------------------------------------------------------------------------  
      elsif event.formatted_text.starts_with? "thank"
        text = ""
        responses =["You're very welcome", "You're most welcome", "Welcome!", "Oh, mention not :)" ]
        text = responses.sample
        client.chat_postMessage(channel: event.channel, text: text, as_user: true)
      
      # ------------------------------------------------------------------------
      #Appreciation Response
      # ------------------------------------------------------------------------
      
      elsif ["awesome", "great", "brilliant", "good", "okay", ":+1:"].any? { |w| event.formatted_text.starts_with? w }
        client.chat_postMessage(channel: event.channel, text: "Happy to help. I'm always there for you!", as_user: true)
      # ------------------------------------------------------------------------
      #Help Response
      # ------------------------------------------------------------------------  
      elsif event.formatted_text.starts_with? "help"
      client.chat_postMessage(channel: event.channel, text: "I am Ginger, a grocery list bot.\n You can say `add` , `edit`, `delete`, `mark done`or `show list` " , as_user: true)
      
      # ------------------------------------------------------------------------
      #Error Response
      # ------------------------------------------------------------------------                   
      else
            # ERROR Commands
            # not understood or an error
            client.chat_postMessage(channel: event.channel, text: "I didn't get that. If you're stuck, type `help` to find my commands.",  as_user: true)
          end
    end

    # ------------------------------------------------------------------------
    #  GETS USEFUL INFO FROM SLACK
    # ------------------------------------------------------------------------
    
    def get_user_name client, event
      # calls users_info on slack
      info = client.users_info(user: event.user_id ) 
      info['user']['name']
    end
    
    def is_admin_or_owner client, event
      # calls users_info on slack
      info = client.users_info(user: event.user_id ) 
      info['user']['is_admin'] || info['user']['is_owner']
    end
  
  end
  
end
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0