GithubHelp home page GithubHelp logo

cakejelly / layer-api Goto Github PK

View Code? Open in Web Editor NEW
18.0 4.0 11.0 131 KB

A ruby toolkit for Layer's Web API's (https://developer.layer.com/docs)

Ruby 99.79% Shell 0.21%
layer ruby messaging-layer

layer-api's Introduction

[DEPRECATED] The layer messaging platform shut down on October 30th 2019 along with it's API

Layer Ruby Gem

Build Status Gem Version

Simple wrapper for Layer's Web API's

If you want to learn more, check out the official documentation.

Migrating from 0.3.x

Version 0.4 is not compatible with older versions. SEE MIGRATING for details on how to migrate your code to the latest version.

Installation

Add this line to your application's Gemfile:

gem 'layer-api'

And then execute:

$ bundle

Or install it yourself as:

$ gem install layer-api

Usage

Resources

All client methods return Resource objects or a collection of Resource objects. Every attribute from a resource can be accessed by calling attribute methods:

conversation = platform.conversations.find("fb2f3a48-523d-4449-a57f-c6651fc6612c")
#<Layer::Resources::Conversation @attributes={...}>

# Get the stripped uuid for any resource
conversation.uuid
# => "fb2f3a48-523d-4449-a57f-c6651fc6612c"

conversation.url
# => "https://api.layer.com/apps/<APP_ID>/conversations/fb2f3a48-523d-4449-a57f-c6651fc6612c"

# Retrieve all attributes
conversation.attributes
# => {"id" => "fb2f3a48-523d-4449-a57f-c6651fc6612c", "url" => "https://api.layer.com/apps/<APP_ID>/conversations/fb2f3a48-523d-4449-a57f-c6651fc6612c", ...}

See the Platform API docs for additional info.

Authentication/setup

platform = Layer::Platform::Client.new(api_token: "your_api_token", app_id: "your_app_id")
# => #<Layer::Platform::Client @api_token="...", @app_id="...">

If you have ENV['LAYER_API_TOKEN'] and ENV['LAYER_APP_ID'] environment variables setup, they will be used by default and don't need to be included:

platform = Layer::Platform::Client.new
# => #<Layer::Platform::Client @api_token="...", @app_id="...">

Retrieving Conversations

user = platform.users.find("user_id")
convs = user.conversations.list
# => [#<Layer::Resources::Conversation>, #<Layer::Resources::Conversation>, ...]

Retrieving A Single Conversation

# For a user
user = platform.users.find("user_id")
conv = user.conversations.find("conversation_id")
# => #<Layer::Resources::Conversation @attributes={...}>

# or alternatively
conv = platform.conversations.find("conversation_id")
# => #<Layer::Resources::Conversation @attributes={...}>

Creating Conversations

conversation = {
  participants: [
    "1234",
    "5678"
  ],
  distinct: false,
  metadata: {
    background_color: "#3c3c3c"
  }
}

platform.conversations.create(conversation)
# => #<Layer::Resources::Conversation @attributes={...}>

Editing Conversations

conv = platform.conversations.find("conversation_id")

operations = [
  { operation: "add", property: "participants", value: "user1" },
  { operation: "add", property: "participants", value: "user2" }
]

conv.update(operations)
# => true

Deleting Conversations

conv = platform.conversations.find("conversation_id")
conv.destroy
# => true

Initiating a Rich Content Upload

conv = platform.conversations.find("conversation_id")
content = conv.content.create(mime_type: "image/png", file: File.open("image.png"))
# => #<Layer::Resources::RichContent @attributes={...}>

content.upload_url
# => "https://www.googleapis.com/upload/storage/path/to/content"

Refreshing the download URL for a Content Object

content = conv.content.find("content_id")
# => #<Layer::Resources::RichContent @attributes={...}>

content.download_url
# => "http://google-testbucket.storage.googleapis.com/some/download/path"

content.refresh_url
# => "https://api.layer.com/apps/<APP_ID>/conversations/<CONVERSATION_ID>/content/<CONTENT_ID>"

Sending Messages

message = {
  sender: {
    name: "t-bone"
  },
  parts: [
    {
        body: "Hello, World!",
        mime_type: "text/plain"
    },
    {
        body: "YW55IGNhcm5hbCBwbGVhc3VyZQ==",
        mime_type: "image/jpeg",
        encoding: "base64"
    }
  ],
  notification: {
    text: "This is the alert text to include with the Push Notification.",
    sound: "chime.aiff"
  }
}

conv = platform.conversations.find("conversation_id")
conv.messages.create(message)
# => #<Layer::Resources::Message @attributes={...}>

Retrieving Messages

# From a specific user's perspective
conv = platform.users.find("user_id").conversations.find("conversation_id")
conv.messages.list
# => [#<Layer::Resources::Message>, #<Layer::Resources::Message>, ...]

# From the system's perspective
conv = platform.conversations.find("conversation_id")
conv.messages.list
# => [#<Layer::Resources::Message>, #<Layer::Resources::Message>, ...]

Retrieving A Single Message

# From a specific user's perspective
user = platform.users.find("user_id")
messages = user.messages.find("message_id")
# => #<Layer::Resources::Message @attributes={...}>

# From the systems perspective
conv = platform.conversations.find("conversation_id")
messages = conv.messages.find("message_id")
# => #<Layer::Resources::Message @attributes={...}>

Deleting A Message

conv = platform.conversations.find("conversation_id")
conv.messages.find("message_id").destroy
# => true

Sending Announcements

announcement = {
  recipients: [ "1234", "5678" ],
  sender: {
    name: "The System"
  },
  parts: [
    {
        body: "Hello, World!",
        mime_type: "text/plain"
    }
  ],
  notification: {
    text: "This is the alert text to include with the Push Notification.",
    sound: "chime.aiff"
  }
}

platform.announcements.create(announcement)
# => #<Layer::Resources::Announcement @attributes={...}>

Modifying A Users Block List

user = platform.users.find("user_id")

operations = [
    { operation: "add", property: "blocks", value: "blockMe1" },
    { operation: "add", property: "blocks", value: "blockMe2" },
    { operation: "remove", property: "blocks", value: "unblockMe" }
]

user.update(operations)
# => true

Retrieving A Users Block List

user = platform.users.find("user_id")

blocks = user.blocks.list
# => [#<Layer::Resources::Block>, [#<Layer::Resources::Block>, ...]

Blocking Users

# using params
owner = platform.users.find("owner")
owner.blocks.create(user_id: "blocked")
# => #<Layer::Resources::Block @attributes={...}>

# passing a User object
owner = platform.users.find("owner")
blocked = platform.users.find("blocked")

owner.blocks.create(blocked)
# => #<Layer::Resources::Block @attributes={...}>

Unblocking Users

# using the blocked users id
owner = platform.users.find("owner")
owner.blocks.find("blocked_user").destroy
# => true

# using a User object
owner = platform.users.find("owner")
blocked = platform.users.find("blocked")

owner.blocks.find(blocked).destroy
# => true

Creating a User Identity

identity = {
  display_name: "Frodo the Dodo",
  avatar_url: "http://sillylordoftheringspictures.com/frodo-riding-a-dodo.png",
  first_name: "Frodo",
  last_name: "Baggins",
  phone_number: "13791379137",
  email_address: "[email protected]",
  metadata: {
    level: "35",
    race: "Dodo"
  }
}

user = platform.users.find("user_id")
user.create_identity(identity)
# => true

Retrieving a User's Identity

user = platform.users.find("user_id")
user.identity
# => {"first_name"=>"Frodo", "phone_number"=>"13791379137", "email_address"=>"[email protected]", "display_name"=>"Frodo the Dodo", "user_id"=>"jake", "last_name"=>"Baggins", "metadata"=>{"race"=>"Dodo", "level"=>"35"}, "avatar_url"=>"http://sillylordoftheringspictures.com/frodo-riding-a-dodo.png"}

Updating an Identity

operations = [
  { operation: "set", property: "last_name", value: "Dodo" },
  { operation: "set", property: "phone_number", value: "" },
  { operation: "set", property: "metadata.level", value: "2" }
]

user.update_identity(operations)
# => true

Replacing an identity

identity = {
  display_name: "Frodo the Dodo",
  avatar_url: "http://sillylordoftheringspictures.com/frodo-riding-a-dodo.png",
  first_name: "Frodo",
  last_name: "Baggins",
  phone_number: "13791379137",
  email_address: "[email protected]",
  metadata: {
    level: "35",
    race: "Dodo"
  }
}

user.replace_identity(identity)
# => true

Deleting a User's Identity

user = platform.users.find("user_id")
user.destroy_identity
# => true

Setting a Users Badge

user = platform.users.find("user_id")
user.set_badge(10)
# => true

Retrieving a Users Badge

user = platform.users.find("user_id")
user.badge
# => { "external_unread_count" => 13, "unread_conversation_count" => 10, "unread_message_count" => 50 }

Generating Identity Tokens

See: the official authentication guide

Make sure the following environment variables are set: ENV['LAYER_KEY_ID'] ENV['LAYER_PROVIDER_ID'] ENV['LAYER_PRIVATE_KEY']

# Returns a valid signed identity token. #
token = platform.generate_identity_token(user_id: "1234", nonce: "your_random_nonce")
# => #<Layer::IdentityToken:0x007f89b4adb890>

token.to_s
# => "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsInR.cCI6IkpXVCIsImN0eSI6ImxheWVyLWVpdDt2PTEiLCJraWQiOiJhNz.5YTE0MC02YzY3LTExZTUtYjM0Mi1jZGJmNDAwZTE5NDgifQ"

See the Webhooks API docs for additional info.

Authentication/setup

client = Layer::Webhooks::Client.new(api_token: "your_api_token", app_id: "your_app_id")
# => #<Layer::Webhooks::Client @api_token="...", @app_id="...">

If you have ENV['LAYER_API_TOKEN'] and ENV['LAYER_APP_ID'] environment variables setup, they will be used by default and don't need to be included:

client = Layer::Webhooks::Client.new
# => #<Layer::Webhooks::Client @api_token="...", @app_id="...">

Registering Webhooks

client.webhooks.create(
  version: "1.0",
  target_url: "https://mydomain.com/my-webhook-endpoint",
  events: ["conversation.created", "message.sent"],
  secret: "1697f925ec7b1697f925ec7b",
  config: {:key1=>"value1", :key2=>"value2"}
)
# => #<Layer::Resources::Webhook @attributes={...}>

Listing Webhooks

client.webhooks.list
# => [#<Layer::Resources::Webhook>, #<Layer::Resources::Webhook>, ...]

Retrieving Webhooks

client.webhooks.find("webhook_id")
# => #<Layer::Resources::Webhook @attributes={...}>

Activating Webhooks

webhook = client.webhooks.find("webhook_id")
webhook.activate

Deactivating Webhooks

webhook = client.webhooks.find("webhook_id")
webhook.deactivate

Deleting Webhooks

webhook = client.webhooks.find("webhook_id")
webhook.destroy

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake rspec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/cakejelly/layer-api.

layer-api's People

Contributors

cakejelly avatar daninfpj avatar mjurin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

layer-api's Issues

please update the dependencies

This gem is incompatible with other gems which require higher version of faraday.
Request you to please update the dependencies to its latest versions.

thanks.

Sorting conversations

You should be able to sort the conversations, as such:

conversations = user.conversations.list(sort_by: 'last_message')

However, because of the way the list method was written, that doesn't work. Instead of adding the params to the query parameters, it sends a JSON encoded string as the body of the request, which doesn't make sense for a GET request.

Get last message with conversation

Hi,

another question. I was looking over the layer documentation and I cant find a way to get a list of conversations for a user and inside the conversation also the last message (with a single call).

Right now I am calling the message list for each conversation and it will be become slow in the future with a lot of conversations.

thx

Unable to update identity

Here is my code:

def update_layer_identity(user)
    operations = [
      {operation: "set", property: "display_name", value: "Hello Friend"}
    ]
    layer_user = layer_client.users.find(user.uuid)
    layer_user.update(operations)
end

And I get the following error:

Layer responded with status 422: {"url":"https://developer.layer.com/docs/platform","data":{"property":"display_name"},"code":9,"id":"invalid_operation","message":"Patch operation \"set\" on \"display_name\" is not allowed."}

Same thing happens when I try to update first_name, last_name and phone_number. I'm able to PATCH successfully using curl, so it must be an issue with this Library?

'If-None-Match' header causes the API to reject consecutive calls

There's a problem with the way you're handling the 'If-None-Match' header. The token is created when you instantiate the platform object. So if you use that instance to say create two messages, layer will reject the second one:

conv = platform.conversations.find("conversation_id")
conv.messages.create(message)
conv.messages.create(another_message)

another_message will get rejected and the message won't be send since the API already saw that token and will interpret it as a duplicate.

invalid_app_id

Tested the same App Id on layer-ruby gem and it works but somehow it doesn't work with this gem.

Layer::Error: Layer responded with status 403: {"id":"invalid_app_id","code":2,"message":"The referenced App ID is invalid.

Layer identity not working

Hi,

I am using the layer-api gem to load / create conversations on layer. I was trying to update the users identity using the indications from the readme, but as soon as I tried to call the create_identity method on a retrieved user, I received an error saying:

NoMethodError: undefined method `create_identity' for #<Layer::Resources::User:0xcd73618>

Any ideea why is that happening?
I was testing it very simple:

identity = {
  display_name: "Frodo the Dodo",
  avatar_url: "http://sillylordoftheringspictures.com/frodo-riding-a-dodo.png",
  first_name: "Frodo",
  last_name: "Baggins",
  phone_number: "13791379137",
  email_address: "[email protected]",
  metadata: {
    level: "35",
    race: "Dodo"
  }
}
user = @platform.users.find("user_id")
user.create_identity(identity)

The gem version I am using is 0.6.1

bundle show | grep layer
  * layer-api (0.6.1)

TypeError: no implicit conversion of nil into String

Hi,

when calling the function to_s on a identity_token I get TypeError: no implicit conversion of nil into String, because there are no substitutions when key.gsub!("\n","\n") is called and a nil is returned instead.

Any special reason why you dont use just gsub ?

best regards,
Marko

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.