Have you ever been forgetting to take water? Let’s create a water reminder app that may notify you per hour utilizing to take a glass of water utilizing slack messages.
By the tip of this tutorial, you’ll learn to:
- Create incoming webhooks on Slack to ship Slack messages
- Create a Ruby on Rails app and add the webhook URL to
- Use HTTParty to invoke the API requests
- Use each time to schedule cron jobs
Begin by downloading VSCode. If you have already got VSCode, soar to the subsequent part.
Navigate to Incoming Webhooks and create an incoming webhook.
- Click on Create Your Slack App
2. Create an app from scratch
3. Edit an app identify and choose a workspace from the dropdown then click on on create an app
4. Then observe steps 2 and three here to create an incoming webhook.
5. Copy the webhook URL you’ll get like proven within the screenshot under.
You’ll be able to take a look at the webhook URL utilizing Postman and make sure that you simply get a Slack notification
Open a terminal occasion, and create a brand new rails app with out the view and mannequin:
bundle gem slackbot
We don’t wish to expose our slack credentials to the general public after we push the challenge to Github due to this fact we’ll use atmosphere variables.
Step 1. Create a
.env file in your root listing
Step 2. Add the
WEBHOOK_URL = "your_webhook_url"
Step 3: Add
dotenv gem to the Gemfile then run bundle set up
gem 'dotenv-rails', teams: [:development, :test]
bundle set up
What’s a cron job?
Cron jobs are used to schedule duties that run repeatedly at a specific time daily or week e.g schedule reminders to drink water each hour or a hearth your alarm each Wednesday at 4 AM
Step 1: Add each time to the Gemfile
gem 'each time', require: false
Step 2: Run
bundle set up
Step 3: Run
wheneverize which is able to generate
bundle exec wheneverize .
Step 4. Generate a rake file to outline the duties to be run by the cron job.
rails g activity slack run_notifications
The command above will generate
lib/duties folder then add the code under to your rake file:
require 'httparty'require 'dotenv/duties'namespace :slack dodesc "Ship hourly remonders to drink water in Slack"activity :run_notifications => :atmosphere doHTTParty.publish(ENV["WEBHOOK_URL"], :physique => :channel => '#basic',:username => 'Slack Bot',:textual content => 'Time to take a glass of water."'.to_json)finish
To put in
HTTParty, add the gem under to your Gemfile and run bundle set up
gem 'httparty'bundle set up
Step 5. Navigate to
schedule.rb file. First, you’ll must specify the place cron jobs will log when the job completes
set :output, "log/cron.log"
Add the rake activity:
each 1.hour dorake "slack:run_notifications"finish
Step 6: Replace the crontab file.
Navigate to your terminal and run the command under:
each time — update-crontab — set atmosphere=’improvement’
Step 7: Take a look at your rake activity by operating the command under in your terminal
It is best to get a slack notification