Ruby Viewpoint Gem 1.27 - ruby

I'm trying to send a message with the Viewpoint Ruby Gem to an EWS endpoint. I am only able to send the message in plain text format. How can I send it in html format?
Here is the code:
Viewpoint::EWS::EWS.endpoint=Conf.application.email.ews.endpoint
Viewpoint::EWS::EWS.set_auth(Conf.application.email.ews.username,Conf.application.email.ews.password)
Viewpoint::EWS::Message.send(options[:subject],msg_str,to_addresses)
I see that there is a text_only "instance" method, but am not able to initialize an instance of a message object to use it.

Trick is to set body_type. Note: This example is derived from the example at https://github.com/zenchild/Viewpoint based on v1.0beta.
require 'viewpoint'
include Viewpoint::EWS
endpoint = 'https://example.com/ews/Exchange.asmx'
user = 'username'
pass = 'password'
cli = Viewpoint::EWSClient.new endpoint, user, pass
cli.send_message do |m|
m.subject = "Test"
m.body = "<html><body><strong>Test</strong> message</body></html>"
m.body_type = 'HTML'
m.to_recipients << 'test#example.com'
end

Related

What do I write to Slack's Socket-Mode websocket endpoint to send a chat message using Ruby?

I am trying to write a simple Slack chatbot for my team using Ruby. It's a bit rough because Slack doesn't have official support for Ruby. Nevertheless, I've been able to open a websocket and listen to Slack events using this code I wrote:
# frozen_string_literal: true
require "async"
require "async/io/stream"
require "async/http/endpoint"
require "async/websocket/client"
require "excon"
require "json"
module Slack
class Client
Error = Class.new(StandardError)
AquisitionError = Class.new(Error)
ConnectionError = Class.new(Error)
CONNECTION_AQUISITION_ENDPOINT = "https://slack.com/api/apps.connections.open"
def initialize
#token = "my-app-token"
end
def connect
connection_info = Excon.post(CONNECTION_AQUISITION_ENDPOINT, headers: {
"Content-type": "application/x-www-form-urlencoded",
Authorization: "Bearer #{#token}",
})
result = JSON.parse(connection_info.body)
raise(AquisitionError) unless result["ok"] # better error later
websocket = Async::HTTP::Endpoint.parse(result["url"])
Async do |_task|
Async::WebSocket::Client.connect(websocket) do |connection|
payload = connection.read
raise(ConnectionError) unless connection_check(payload)
puts "Listening..."
handle(payload) while (payload = connection.read)
end
end
end
private
def connection_check(payload)
payload[:type] == "hello"
end
def handle(payload)
puts payload.inspect
end
end
end
The documentation leads me to believe that I can write JSON to this connection e.g.
connection.write({
# JSON to send a message in Slack here
# Probably need to specify the channel somehow
# Probably need to specify if I'm using markdown
# Have no idea what the form should be
})
But I haven't been able to figure out what form that JSON needs to take.
I was also running into this and trying to determine why the docs do not provide a clear answer. It appears that you do not infact send requests back over websockets, and instead use websockets only to accept requests.
Which would mean that you would use something like the webAPI to perform responsive actions, you can see this pattern in the PythonSDK with websockets example provided by Slack.
eg:
if req.type == "events_api":
# Acknowledge the request, this ack is sent back over websockets
# the format is: { 'envelope_id': req['envelope_id'] }
response = SocketModeResponse(envelope_id=req.envelope_id)
client.send_socket_mode_response(response)
# Add a reaction to the message if it's a new message
# notice that this request uses the web_client here and not the socket one
if req.payload["event"]["type"] == "message" \
and req.payload["event"].get("subtype") is None:
client.web_client.reactions_add(
name="eyes",
channel=req.payload["event"]["channel"],
timestamp=req.payload["event"]["ts"],
)

How to use webmock to simulate a request?

My app create a github gist using API. I need to simulate a request to the API with rspec. I'm using the webmock gem but I don't quite understand how to use it for my application. I need a little help to get started.
This is my spec/Git_Request_spec.rb
require_relative '../Gist_Request.rb'
require 'spec_helper'
RSpec.describe GistRequest do
describe "#post" do
it "crear gist" do
filename = "test.txt"
description = "descripción"
state = true
content = "contenido"
gist_create = GistRequest.new(description, state, filename, content)
gist_create.post()
expect(gist_create.response_status).to eq "201"
end
it "campos no válidos" do
filename = "test.txt"
description = "descripción"
state = true
content = "contenido"
gist_create = GistRequest.new(filename, content, state, description)
gist_create.post()
expect(gist_create.response_status).to eq "422"
end
end
end
Any ideas?
You need to use the method stub_request to simulate your interaction with api
stub_request(:http_method, url).with(`your data in
request`).to_return(`what do you expect to receive in response`).

Gmail: Ruby gem google-api-client broken?

Nobody has encountered this?
I can get the email message object (Google::Apis::GmailV1::Message) but other Message attributes just returns Nil. Only id, thread_id seems to be returned.
SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_MODIFY
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
user_msgs = service.list_user_messages('me',
{:include_spam_trash => false, :label_ids => ['INBOX'], :q => "is:unread"})
user_msgs.messages.each do |msg|
puts "CLASS: #{msg.class}" # Google::Apis::GmailV1::Message
puts "MESSAGE ID: #{msg.id}" # WORKS I get the email ID
msg_part = msg.payload
puts "MSGPART: #{msg_part.class}" # NIL !!!, All other attributes are also NIL
end
So basically I do get the email with the correct ID, but that's about it, all methods or attributes of the GmailV1::Message class is Nil. I also tried changing the SCOPE to MODIFY and same result.
Attributes that just returns Nil:
internal_date label_ids payload raw size_estimate snippet
Also noticed that github project linked in their documentation opens a 404 page on some.
Might be due to Google now forcing developers to have publicly available apps reviewed first: https://developers.google.com/gmail/api/auth/about-auth (see the notification in the blue box with the star)

Creating a Ruby API

I have been tasked with creating a Ruby API that retrieves youtube URL's. However, I am not sure of the proper way to create an 'API'... I did the following code below as a Sinatra server that serves up JSON, but what exactly would be the definition of an API and would this qualify as one? If this is not an API, how can I make in an API? Thanks in advance.
require 'open-uri'
require 'json'
require 'sinatra'
# get user input
puts "Please enter a search (seperate words by commas):"
search_input = gets.chomp
puts
puts "Performing search on YOUTUBE ... go to '/videos' API endpoint to see the results and use the output"
puts
# define query parameters
api_key = 'my_key_here'
search_url = 'https://www.googleapis.com/youtube/v3/search'
params = {
part: 'snippet',
q: search_input,
type: 'video',
videoCaption: 'closedCaption',
key: api_key
}
# use search_url and query parameters to construct a url, then open and parse the result
uri = URI.parse(search_url)
uri.query = URI.encode_www_form(params)
result = JSON.parse(open(uri).read)
# class to define attributes of each video and format into eventual json
class Video
attr_accessor :title, :description, :url
def initialize
#title = nil
#description = nil
#url = nil
end
def to_hash
{
'title' => #title,
'description' => #description,
'url' => #url
}
end
def to_json
self.to_hash.to_json
end
end
# create an array with top 3 search results
results_array = []
result["items"].take(3).each do |video|
#video = Video.new
#video.title = video["snippet"]["title"]
#video.description = video["snippet"]["description"]
#video.url = video["snippet"]["thumbnails"]["default"]["url"]
results_array << #video.to_json.gsub!(/\"/, '\'')
end
# define the API endpoint
get '/videos' do
results_array.to_json
end
An "API = Application Program Interface" is, simply, something that another program can reliably use to get a job done, without having to busy its little head about exactly how the job is done.
Perhaps the simplest thing to do now, if possible, is to go back to the person who "tasked" you with this task, and to ask him/her, "well, what do you have in mind?" The best API that you can design, in this case, will be the one that is most convenient for the people (who are writing the programs which ...) will actually have to use it. "Don't guess. Ask!"
A very common strategy for an API, in a language like Ruby, is to define a class which represents "this application's connection to this service." Anyone who wants to use the API does so by calling some function which will return a new instance of this class. Thereafter, the program uses this object to issue and handle requests.
The requests, also, are objects. To issue a request, you first ask the API-connection object to give you a new request-object. You then fill-out the request with whatever particulars, then tell the request object to "go!" At some point in the future, and by some appropriate means (such as a callback ...) the request-object informs you that it succeeded or that it failed.
"A whole lot of voodoo-magic might have taken place," between the request object and the connection object which spawned it, but the client does not have to care. And that, most of all, is the objective of any API. "It Just Works.™"
I think they want you to create a third-party library. Imagine you are schizophrenic for a while.
Joe wants to build a Sinatra application to list some YouTube videos, but he is lazy and he does not want to do the dirty work, he just wants to drop something in, give it some credentials, ask for urls and use them, finito.
Joe asks Bob to implement it for him and he gives him his requirements: "Bob, I need YouTube library. I need it to do:"
# Please note that I don't know how YouTube API works, just guessing.
client = YouTube.new(api_key: 'hola')
video_urls = client.videos # => ['https://...', 'https://...', ...]
And Bob says "OK." end spends a day in his interactive console.
So first, you should figure out how you are going to use your not-yet-existing lib, if you can – sometimes you just don't know yet.
Next, build that library based on the requirements, then drop it in your Sinatra app and you're done. Does that help?

how to serialize AMF body and send it with Ruby RocketAMF

I am trying to serialized an AMF body and send it with RestClient.post.
From the Charles proxy, I can deserialized my request body and show it as follows:
# s is the raw binary from request body
pp RocketAMF::Envelope.new.populate_from_stream(s).messages
However, I cannot figure it out how to serialize such an object and send it (with RestClient.post) in the body.
You'll want to change the URL it's using, but the below is the correct way to do it.
require 'rubygems'
require 'RocketAMF'
require 'rest-client'
data = [] # whatever data you want
env = RocketAMF::Envelope.new :amf_version => 3
env.messages << RocketAMF::Message.new('BatchController.authenticate_iphone', '/1', data)
res = RestClient.post "http://localhost:9292/amf", env.to_s, :content_type => 'application/x-amf'
puts RocketAMF::Envelope.new.populate_from_stream(res).inspect

Resources