Commit 43404c87 authored by Mangesh Divate's avatar Mangesh Divate

Import Upstream version 0.0.5

parents
# Changelog
## 0.0.5
* Resolved missing dependencies for development and testing
## 0.0.4
* Added Card Messages support
## 0.0.3
* Added YARD documentation
* Added HangoutsChat::Sender::APIError exception for unsuccessful responses
## 0.0.2
* Added tests
* Improved appearance
* Added and performed rubocop code analyze
## 0.0.1
* Initial version with Hangouts Chat simple text messages support
MIT License
Copyright (c) 2018 enzinia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
[![Gem Version](https://badge.fury.io/rb/hangouts-chat.svg)](https://badge.fury.io/rb/hangouts-chat)
[![Build Status](https://travis-ci.org/enzinia/hangouts-chat.svg?branch=master)](https://travis-ci.org/enzinia/hangouts-chat)
[![Maintainability](https://api.codeclimate.com/v1/badges/c6106eab23781ab0be46/maintainability)](https://codeclimate.com/github/enzinia/hangouts-chat/maintainability)
[![Inline docs](http://inch-ci.org/github/enzinia/hangouts-chat.svg?branch=master)](http://inch-ci.org/github/enzinia/hangouts-chat)
# Hangouts Chat gem
Send messages to [Hangouts Chat](https://gsuite.google.com/products/chat/) rooms using incoming webhooks.
## Installation
```
$ gem install hangouts-chat
```
or add to your Gemfile
```ruby
require 'hangouts-chat'
```
## Usage
### Simple Text Message
Simple messages that appear inline as if typed by a user. Details and format: [Simple Text Messages](https://developers.google.com/hangouts/chat/reference/message-formats/basic)
```ruby
sender = HangoutsChat::Sender.new 'webhook_URL'
sender.simple 'text'
```
### Card Message
More complex messages that have UI elements with actions and HTML support. Details and format: [Card messages](https://developers.google.com/hangouts/chat/reference/message-formats/cards)
```ruby
sender = HangoutsChat::Sender.new 'webhook_URL'
header = { title: 'Pizza Bot Customer Support',
subtitle: 'pizzabot@example.com',
imageUrl: 'https://goo.gl/aeDtrS' }
sections = [{ keyValue: { topLabel: 'Order No.', content: '12345' } },
{ keyValue: { topLabel: 'Status', content: 'In Delivery' } }]
sender.card(header, sections)
```
### How to get Webhook URL
1. Open channel to which you want to send messages
2. Click on the channel name in top bar and select 'Configure webhooks'
3. Click on 'Add webhook' and fill name for bot, that will be display messages
4. Click on 'Save' and copy 'Webhook URL'
Details: [Setting up an incoming webhook](https://developers.google.com/hangouts/chat/how-tos/webhooks)
## Contributing
Please feel free to contribute any changes, that you want too see in this gem.
Feature requests are also accepted.
Before Pull Request submitting please check
* Changed or added code has tests and YARD documentation
* All tests are pass
* `rubocop` doesn't report any offenses
## Tests
All tests are use usual Minitest `assert` syntax.
To run tests execute `rake tests`.
## Changelog
Changelog is available [here](CHANGELOG.md).
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << 'test'
t.test_files = FileList['test/**/*_test.rb']
end
desc 'Run tests'
task default: :test
#########################################################
# This file has been automatically generated by gem2tgz #
#########################################################
# -*- encoding: utf-8 -*-
# stub: hangouts-chat 0.0.5 ruby lib
Gem::Specification.new do |s|
s.name = "hangouts-chat".freeze
s.version = "0.0.5"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["enzinia".freeze]
s.date = "2018-03-31"
s.description = "Send messages to G Suite Hangouts Chat rooms using incoming webhooks and Net::HTTP::Post".freeze
s.email = "vkukovskij@gmail.com".freeze
s.files = ["CHANGELOG.md".freeze, "LICENSE".freeze, "README.md".freeze, "Rakefile".freeze, "lib/hangouts_chat.rb".freeze, "lib/hangouts_chat/exceptions.rb".freeze, "lib/hangouts_chat/http.rb".freeze, "lib/hangouts_chat/version.rb".freeze, "test/hangouts_chat/http_test.rb".freeze, "test/hangouts_chat_test.rb".freeze, "test/test_helper.rb".freeze]
s.homepage = "https://github.com/enzinia/hangouts-chat".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "2.7.6".freeze
s.summary = "Library for sending messages to Hangouts Chat rooms".freeze
s.test_files = ["test/hangouts_chat/http_test.rb".freeze, "test/hangouts_chat_test.rb".freeze, "test/test_helper.rb".freeze]
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<bundler>.freeze, ["~> 1"])
s.add_development_dependency(%q<minitest>.freeze, ["~> 5"])
s.add_development_dependency(%q<rake>.freeze, ["~> 12"])
s.add_development_dependency(%q<rubocop>.freeze, ["<= 0.54.0"])
s.add_development_dependency(%q<webmock>.freeze, ["~> 3"])
s.add_development_dependency(%q<yard>.freeze, ["> 0.9.11", "~> 0.9"])
else
s.add_dependency(%q<bundler>.freeze, ["~> 1"])
s.add_dependency(%q<minitest>.freeze, ["~> 5"])
s.add_dependency(%q<rake>.freeze, ["~> 12"])
s.add_dependency(%q<rubocop>.freeze, ["<= 0.54.0"])
s.add_dependency(%q<webmock>.freeze, ["~> 3"])
s.add_dependency(%q<yard>.freeze, ["> 0.9.11", "~> 0.9"])
end
else
s.add_dependency(%q<bundler>.freeze, ["~> 1"])
s.add_dependency(%q<minitest>.freeze, ["~> 5"])
s.add_dependency(%q<rake>.freeze, ["~> 12"])
s.add_dependency(%q<rubocop>.freeze, ["<= 0.54.0"])
s.add_dependency(%q<webmock>.freeze, ["~> 3"])
s.add_dependency(%q<yard>.freeze, ["> 0.9.11", "~> 0.9"])
end
end
require_relative 'hangouts_chat/version'
require_relative 'hangouts_chat/http'
require_relative 'hangouts_chat/exceptions'
# Main namespace
module HangoutsChat
# Provide methods to send messages to Hangouts Chat rooms using webhooks API
class Sender
# @return [String] Webhook URL, given on initialization
attr_reader :url
# Creates Sender object
# @param webhook_url [String] URL for incoming webhook
def initialize(webhook_url)
@url = webhook_url
@http = HTTP.new(@url)
end
# Sends Simple Text Message
# @param text [String] text to send to room
# @return [Net::HTTPResponse] response object
def simple(text)
payload = { text: text }
send_request(payload)
end
# Sends Card Message
# @since 0.0.4
# @param header [Hash] card header content
# @param sections [Array<Hash>] card widgets array
# @return [Net::HTTPResponse] response object
def card(header, sections)
payload = { cards: [header: header, sections: sections] }
send_request(payload)
end
private
# Sends payload and check response
# @param payload [Hash] data to send by POST
# @return [Net::HTTPResponse] response object
# @raise [APIError] if got unsuccessful response
def send_request(payload)
response = @http.post payload
raise APIError, response unless response.is_a?(Net::HTTPSuccess)
response
end
end
end
require 'net/http/response'
module HangoutsChat
class Sender
# Unsuccessful API respond exception
class APIError < StandardError
# Creates exception object with generated message
# @param response [Net::HTTPResponse] API response
def initialize(response)
msg = "HTTP #{response.code} #{response.msg}\n"
msg += "Body:\n#{response.body}"
super(msg)
end
end
end
end
require 'net/http'
require 'json'
module HangoutsChat
class Sender
# Unsuccessful respond exception
class APIError < StandardError; end
# Service class to send HTTP POST requests
class HTTP
# Creates HTTP::Post object with JSON content type
# @param url [String] URL to send request
def initialize(url)
@uri = URI(url)
@req = Net::HTTP::Post.new(@uri)
@req['Content-Type'] = 'application/json'
end
# Sends HTTP POST request
# @param payload [String] request body to send
# @return [Net::HTTPResponse] response object
def post(payload)
@req.body = payload.to_json
res = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: true) do |http|
http.request(@req)
end
res
end
end
end
end
module HangoutsChat
# Library version
VERSION = '0.0.5'.freeze
end
require 'test_helper'
class HTTPTest < Minitest::Test
def setup
@url = 'https://example.com'
@http = HangoutsChat::Sender::HTTP.new(@url)
end
def test_initialized_with_valid_uri
uri = @http.instance_variable_get(:@uri)
assert_equal 'https', uri.scheme
assert_equal 'example.com', uri.host
end
def test_initialized_with_valid_post_request
req = @http.instance_variable_get(:@req)
assert_equal 'POST', req.method
assert_equal 'application/json', req['Content-Type']
end
def test_post_request
stub_request(:any, @url)
payload = 'Test text'
@http.post(payload)
assert_requested :post, @url, times: 1, body: payload.to_json, headers:
{ 'Content-Type' => 'application/json' }
assert_not_requested :get, @url
end
end
require 'test_helper'
class HangoutsChatTest < Minitest::Test
def setup
@webhook_url = 'https://chat.googleapis.com/v1/spaces/space_id/' \
'messages?key=secret_key&token=secret_token'
@sender = HangoutsChat::Sender.new(@webhook_url)
end
def test_initialized_with_valid_variables
url = @sender.instance_variable_get(:@url)
http = @sender.instance_variable_get(:@http)
assert_equal @webhook_url, url
assert_equal HangoutsChat::Sender::HTTP, http.class
end
def test_simple_message_request
stub_request(:any, /chat\.googleapis\.com/).to_return(status: 200)
message = 'Test simple message'
@sender.simple(message)
assert_requested :post, @webhook_url, times: 1, body:
{ text: message }.to_json
end
def test_card_message_request
stub_request(:any, /chat\.googleapis\.com/).to_return(status: 200)
header = { title: 'Pizza Bot Customer Support',
subtitle: 'pizzabot@example.com',
imageUrl: 'https://goo.gl/aeDtrS' }
sections = [{ keyValue: { topLabel: 'Order No.', content: '12345' } },
{ keyValue: { topLabel: 'Status', content: 'In Delivery' } }]
@sender.card(header, sections)
assert_requested :post, @webhook_url, times: 1, body:
{ cards: [header: header, sections: sections] }.to_json
end
def test_api_error_exception_message
stub_request(:any, /chat\.googleapis\.com/)
.to_return(status: [403, 'Forbidden'], body: 'Response body')
exception = assert_raises HangoutsChat::Sender::APIError do
@sender.simple('Exception test')
end
assert_match(/^HTTP 403 Forbidden$/, exception.message)
assert_match(/^Body:\nResponse body$/, exception.message)
end
end
require 'minitest/autorun'
require 'webmock/minitest'
require 'hangouts_chat'
WebMock.disable_net_connect!(net_http_connect_on_start: true)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment