Completed
Push — master ( 727159...d83294 )
by John
01:02
created

new_slack()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 6
rs 9.4285
1
#!ruby
2
3
require 'ringcentral_sdk'
4
require 'glip-poster'
5
require 'pp'
6
7
# Set your credentials in the .env file
8
# Use the rc_config_sample.env.txt file as a scaffold
9
10
config = RingCentralSdk::REST::Config.new.load_dotenv
11
12
client = RingCentralSdk::REST::Client.new
13
client.app_config(config.app)
14
client.authorize_user(config.user)
15
16
# An SMS event poster. Takes a message store subscription
17
# event and posts inbound SMS as chats.
18
class RcEventSMSChatPoster
19
  attr_accessor :event
20
  def initialize(client, posters=[], event_data={})
21
    @client = client
22
    @posters = posters
23
    @event = RingCentralSdk::REST::Event.new event_data
24
    @retriever = RingCentralSdk::REST::MessagesRetriever.new @client
25
  end
26
27
  def post_message()
28
    return unless @event.new_sms_count > 0
29
    messages = @retriever.retrieve_for_event(@event, {direction: 'Inbound'})
30
    messages.each do |message|
31
      post_message_to_chat message
32
    end
33
  end
34
35
  def post_message_to_chat(rec)
36
    text = 'SMS from ' + rec['from']['phoneNumber'] \
37
      + "\n* Time: " + rec['creationTime'] + "\n* Message: " + rec['subject']
38
    @posters.each { |v| v.send_message(text) }
39
  end
40
end
41
42
# An observer object that uses RcEventSMSChatPoster to post
43
# to multiple chat posters
44
class RcSmsToChatObserver
45
  def initialize(client, posters)
46
    @client = client
47
    @posters = posters
48
  end
49
50
  def update(message)
51
    event = RcEventSMSChatPoster.new(@client, @posters, message)
52
    event.post_message
53
    puts JSON.dump(message)
54
  end
55
end
56
57
def new_glip(config)
58
  glip = Glip::Poster.new(config.env.data['RC_DEMO_GLIP_WEBHOOK_URL'])
59
  glip.options[:icon] = config.env.data['RC_DEMO_GLIP_WEBHOOK_ICON']
60
  glip.options[:activity] = 'New Inbound SMS'
61
62
  body = "* event_filter: extension/message-store?messageType=SMS\n* actions: post SMS messages to Glip team"
63
64
  glip.send_message(body, {
65
    activity: 'RingCentral subscription initiated',
66
  })
67
  return glip
68
end
69
70
def run_subscription(config, client)
71
  # Create an observable subscription and add your observer
72
  sub = client.create_subscription()
73
  sub.subscribe(['/restapi/v1.0/account/~/extension/~/message-store'])
74
75
  # Create and add first chat poster
76
  posters = []
77
  posters.push new_glip(config)
78
79
  # Add observer
80
  sub.add_observer(RcSmsToChatObserver.new(client, posters))
81
82
  # Run until key is clicked
83
  puts "Click any key to finish"
84
  stop_script = gets
85
86
  # End the subscription
87
  sub.destroy()
88
end
89
90
run_subscription(config, client)
91
92
puts "DONE"
93