Software

How to Generate a JSON Web Token (JWT) for Oracle Cloud Applications

IDCS REST API w/ Java

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

public class IdcsSample {

  public static void main(String[] args) {
    Client client = ClientBuilder.newClient();

    MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>();

    params.putSingle("grant_type", "client_credentials");
    params.putSingle("scope", "sampleScope");

    Response res = client.target("https://host/oauth2/v1/token").header("Authorization", "...").post(Entity.form(params));

    if (res.getStatus() == 200)
      out.println(res.readEntity(String.class));

    client.close();
  }

}

IDCS REST API w/ Go

package main

import (
  "fmt"

  "github.com/go-resty/resty/v2"
)

func main() {
  client := resty.New()

  res, _ := client.R().SetHeader("Authorization", "...").SetHeader("Content-Type", "application/x-www-form-urlencoded").SetBody(`grant_type=client_credentials&scope=sampleScope`).Post("https://host/oauth2/v1/token")

  if res.StatusCode() == 200 {
    fmt.Printf("%v\n", res)
  }

}

IDCS REST API w/ Node.js

const https = require('https')

var req = https.request({ headers: { 'Authorization': '...', 'Content-Type': 'application/x-www-form-urlencoded' }, hostname: 'host', method: 'POST', path: '/oauth2/v1/token' }, (res) => {

  if (res.statusCode === 200) {
    var body = ''

    res.on('data', (chunk) => {
      body += chunk.toString()
    })

    res.on('end', () => {
      console.log(body)
    })

  }

})

req.write('grant_type=client_credentials&scope=sampleScope')

req.end()

IDCS REST API w/ Python

import requests

res = requests.post('https://host/oauth2/v1/token', data = { 'grant_type': 'client_credentials', 'scope': 'sampleScope' }, headers = { 'Authorization': '...' })

if res.ok:
  print(res.text)

IDCS REST API w/ Ruby

require 'rest-client'

res = RestClient.post 'https://host/oauth2/v1/token', { grant_type: 'client_credentials', scope: 'sampleScope' }, :authorization => '...'

if res.code == 200
  puts res.body
end

IDCS Java SDK

import static java.lang.System.out;

import java.util.HashMap;
import java.util.Map;

import oracle.security.jps.idcsbinding.api.AuthenticationResult;
import oracle.security.jps.idcsbinding.api.OAuthToken;
import oracle.security.jps.idcsbinding.shared.AuthenticationManager;
import oracle.security.jps.idcsbinding.shared.AuthenticationManagerFactory;
import oracle.security.jps.idcsbinding.shared.IDCSTokenAssertionConfiguration;

public class IdcsSample {

  public static void main(String[] args) {
    Map<String, String> config = new HashMap<String, String>();

    config.put(IDCSTokenAssertionConfiguration.IDCS_CLIENT_ID, "sampleClientId");
    config.put(IDCSTokenAssertionConfiguration.IDCS_CLIENT_SECRET, "sampleClientSecret");
    config.put(IDCSTokenAssertionConfiguration.IDCS_CLIENT_TENANT, "sampleClientTenant");
    config.put(IDCSTokenAssertionConfiguration.IDCS_HOST, "host");
    config.put(IDCSTokenAssertionConfiguration.IDCS_PORT, "443");
    config.put("SSLEnabled", "true");

    AuthenticationManager mgr = AuthenticationManagerFactory.getInstance(new IDCSTokenAssertionConfiguration(config));

    AuthenticationResult res = mgr.clientCredentials("sampleScope");

    out.println(res.getToken(OAuthToken.TokenType.ACCESS_TOKEN).getToken());
  }

}

IDCS Node.js SDK

const IdcsAuthenticationManager = require ('./lib/idcsauthenticationmanager.js')

options = {
  ClientId: 'sampleClientId',
  ClientSecret: 'sampleClientSecret',
  ClientTenant:: 'sampleClientTenant',
  IDCSHost: 'https://host'
}

mgr = new IdcsAuthenticationManager(options)

mgr.clientCredentials('sampleScope').then(function(res) {
  console.log(res)
})

IDCS Python SDK

from IdcsClient import *

options = {
  Constants.BASE_URL: 'https://host'
  Constants.CLIENT_ID: 'sampleClientId',
  Constants.CLIENT_SECRET: 'sampleClientSecret',
}

mgr = AuthenticationManager(options)

res = mgr.clientCredentials('sampleToken')

print(res.getAccessToken())

JWT Java Client

import static java.lang.System.out;

import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

public class JwtSample {

  public static void main(String[] args) {
    Map<String, String> claims = new HashMap<String, String>();

    claims.put(Claims.AUDIENCE, "sampleScope");
    claims.put(Claims.SUBJECT, "sampleClientId");

    out.println(Jwts.builder().setClaims(claims).signWith(Keys.hmacShaKeyFor("sampleClientSecret".getBytes())).compact());
}

JWT Go Client

package main

import (
  "fmt"

  "github.com/SermoDigital/jose/crypto"
  "github.com/SermoDigital/jose/jws"
)

func main() {
  claims := jws.Claims{
    "scopes": []string {
      "sampleScope",
    },
    "sub": "sampleClientId",
  }

  token := jws.NewJWT(claims, crypto.SigningMethodHS256)

  serializedToken, _ := token.Serialize([]byte("sampleClientSecret"))

  fmt.Printf("%s\n", serializedToken)
}

JWT Node.js Client

const jwt = require('jsonwebtoken')

payload = { aud: 'sampleScope', sub: 'sampleClientId' }

console.log(jwt.sign(payload, 'sampleClientSecret')))

JWT Python Client

from authlib.jose import jwt

headers = { 'alg': 'HS256' }

payload = { 'aud': 'sampleScope', 'sub': 'sampleClientId' }

print(jwt.encode(headers, payload, 'sampleClientSecret'))

JWT Ruby Client

require 'jwt'

payload = { aud: 'sampleScope', sub: 'sampleClientId' }

puts JWT.encode payload, 'sampleClientSecret'
Software

How to Run a Bot in Automation Anywhere

W/o a Queue

Bot Deploy API w/ Java

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

public class AaeSample {

  public static void main(String[] args) {
    Client client = ClientBuilder.newClient();

    client.target("https://host/v3/automations/deploy").header("X-Authorization", "...").post(Entity.json("{ \"fileId\": \"sampleBotId\", \"runAsUserIds\": [ \"sampleUserId\" ], \"callbackInfo\": { \"url\": \"sampleCallbackUrl\" } }"));

    client.close();
  }


}

Bot Deploy API w/ Go

package main

import "github.com/go-resty/resty/v2"

func main() {
  client := resty.New()

  client.R().SetHeader("X-Authorization", "...").SetBody(`{ "fileId": "sampleBotId", "runAsUserIds": [ "sampleUserId" ], "callbackInfo": { "url": "sampleCallbackUrl" } }`).Post("https://host/v3/automations/deploy")
}

Bot Deploy API w/ Node.js

const https = require('https')

var req = https.request({ headers: { 'X-Authorization': '...' }, hostname: 'host', method: 'POST', path: '/v3/automations/deploy' })

req.write('{ "fileId": "sampleBotId", "runAsUserIds": [ "sampleUserId" ], "callbackInfo": { "url", "sampleCallbackUrl" } }')

req.end()

Bot Deploy API w/ Python

import requests

requests.post('https://host/v3/automations/deploy', json = { 'fileId': 'sampleBotId', 'runAsUserIds': [ 'sampleUserId' ], 'callbackInfo': { 'url': 'sampleCallbackUrl' } }, headers = { 'X-Authorization': '...' })

Bot Deploy API w/ Ruby

require 'rest-client'

RestClient.post 'https://host/v3/automations/deploy', '{ "fileId": "sampleBotId", "runAsUserIds": [ "sampleUserId" ], "callbackInfo": { "url", "sampleCallbackUrl" } }', :x_authorization => '...'

W/ a Queue

Workload Management API w/ Java

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

public class AaeSample {

  public static void main(String[] args) {
    Client client = ClientBuilder.newClient();

    client.target("https://host/v3/queues/sampleQueueId/workitems").header("X-Authorization", "...").post(Entity.json("{ \"workItems\": [ { \"json\": { ... } ] }"));

    client.close();
  }


}

Workload Management API w/ Go

package main

import "github.com/go-resty/resty/v2"

func main() {
  client := resty.New()

  client.R().SetHeader("X-Authorization", "...").SetBody(`{ "workItems": [ { "json": { ... } ] }`).Post("https://host/v3/queues/sampleQueueId/workitems")
}

Workload Management API w/ Node.js

const https = require('https')

var req = https.request({ headers: { 'X-Authorization': '...' }, hostname: 'host', method: 'POST', path: '/v3/queues/sampleQueueId/workitems' })

req.write('{ "workItems": [ { "json": { ... } ] }')

req.end()

Workload Management API w/ Python

import requests

requests.post('https://host/v3/queues/sampleQueueId/workitems', json = { 'workItems': [ { 'json': { ... } ] }, headers = { 'X-Authorization': '...' })

Workload Management API w/ Ruby

require 'rest-client'

RestClient.post 'https://host/v3/queues/sampleQueueId/workitems', '{ "workItems": [ { "json": { ... } ] }', :x_authorization => '...'
Software

How to Create an Incident in Oracle B2C Service

Java

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

public class B2cServiceSample {

  public static void main(String[] args) {
    Client client = ClientBuilder.newClient();

    client.register(HttpAuthenticationFeature.basic("user", "password")); // also supports OAuth

    client.target("https://host/services/rest/connect/v1.4/incidents").header("OSvC-CREST-Application-Context", "Sample Request").post(Entity.json("{ \"primaryContact\": { \"id\": sampleContactId }, \"subject\": \"Sample Incident\" }"));

    client.close();
  }

}

Go

package main

import "github.com/go-resty/resty/v2"

func main() {
  client := resty.New()

  client.R().SetBasicAuth("user", "password").SetHeader("OSvC-CREST-Application-Context", "Sample Request").SetBody(`{ "primaryContact": { "id": sampleContactId }, "subject": "Sample Incident" }`).Post("https://host/services/rest/connect/v1.4/incidents") // also supports OAuth
}

Node.js

const https = require('https')

var req = https.request({ auth: 'user:password', headers: { 'OSvC-CREST-Application-Context': 'Sample Request' }, hostname: 'host', method: 'POST', path: '/services/rest/connect/v1.4/incidents' }) // also supports OAuth

req.write('{ "primaryContact": { "id": sampleContactId }, "subject": "Sample Incident" }')

req.end()

Python

import requests

requests.post('https://host/services/rest/connect/v1.4/incidents', json = { 'primaryContact': { 'id': sampleContactId }, 'subject': 'Sample Incident' }, auth = ( 'user', 'password'), headers = { 'OSvC-CREST-Application-Context': 'Sample Request' }) # also supports OAuth

Ruby

require 'rest-client'

RestClient.post 'https://user:password@host/services/rest/connect/v1.4/incidents', '{ "primaryContact": { "id": sampleContactId }, "subject": "Sample Incident" }', :osvc_crest_application_context => 'Sample Request' # also supports OAuth
Software

How to Create a Webhook for Uptime Robot

Java

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "SampleUptimeRobotServlet", value = "/")
public class SampleUptimeRobotServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    ...
  }

}

Go

package main

import (
  "net/http"

  "github.com/gorilla/handlers"
)

func main() {
  http.Handle("/", handlers.MethodHandler{
    http.MethodGet: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      ...
    }),
  })

  http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
}

Node.js

const fs = require('fs')
const https = require('https')

const express = require('express')

var options = {
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem')
}

var app = express()

app.get('/', (req, res) => {
  ...
})

https.createServer(options, app).listen(8443)

Python

from flask import Flask

app = Flask(__name__)

@app.route('/', methods = [ 'GET' ])
def do_get():
  ...

Ruby

require 'sinatra'

get '/' do
  ...
end
Software

How to Create a Webhook for Uptime (formerly Pingometer)

Java

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "SampleUptimeServlet", value = "/")
public class SampleUptimeServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    ...
  }

}

Go

package main

import (
  "net/http"

  "github.com/gorilla/handlers"
)

func main() {
  http.Handle("/", handlers.MethodHandler{
    http.MethodPost: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      ...
    }),
  })

  http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
}

Node.js

const fs = require('fs')
const https = require('https')

const express = require('express')

var options = {
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem')
}

var app = express()

app.post('/', (req, res) => {
  ...
})

https.createServer(options, app).listen(8443)

Python

from flask import Flask

app = Flask(__name__)

@app.route('/', methods = [ 'POST' ])
def do_post():
  ...

Ruby

require 'sinatra'

post '/' do
  ...
end
Software

How to Create a Webhook for Pingdom

Java

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "SamplePingdomServlet", value = "/")
public class SamplePingdomServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    ...
  }

}

Go

package main

import (
  "net/http"

  "github.com/gorilla/handlers"
)

func main() {
  http.Handle("/", handlers.MethodHandler{
    http.MethodPost: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      ...
    }),
  })

  http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
}

Node.js

const fs = require('fs')
const https = require('https')

const express = require('express')

var options = {
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem')
}

var app = express()

app.post('/', (req, res) => {
  ...
})

https.createServer(options, app).listen(8443)

Python

from flask import Flask

app = Flask(__name__)

@app.route('/', methods = [ 'POST' ])
def do_post():
  ...

Ruby

require 'sinatra'

post '/' do
  ...
end
Software

How to Create an Incident in Status.io

API w/ Java

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

public class StatusioSample {

  public static void main(String[] args) {
    Client client = ClientBuilder.newClient();

    client.target("https://api.status.io/v2/incident/create").request().header("x-api-id", "...").header("x-api-key", "...").post(Entity.json("{ \"statuspage_id\": \"sampleStatusPageId\", \"all_infrastructure_affected\": \"0\", \"current_state\": 200, \"current_status\": 400, \"incident_details\": \"Sample Incident\", \"incident_name\": \"Sample Incident\", \"infrastructure_affected\": [ \"sampleComponentId-sampleContainerId\" ], \"social\": \"0\" }"));

    client.close();
  }

}

API w/ Go

package main

import "github.com/go-resty/resty/v2"

func main() {
  client := resty.New()

  client.R().SetHeader("Content-Type", "application/json").SetHeader("x-api-id", "...").SetHeader("x-api-key", "...").SetBody(`{ "statuspage_id": "sampleStatusPageId", "all_infrastructure_affected": "0", "current_state": 200, "current_status": 400, "incident_details": "Sample Incident", "incident_name": "Sample Incident", "infrastructure_affected": [ "sampleComponentId-sampleContainerId" ], "social": "0" }`).Post("https://api.status.io/v2/incident/create")
}

API w/ Node.js

const https = require('https')

var req = https.request({ headers: { 'Content-Type': 'application/json', 'x-api-id': '...', 'x-api-key': '...' }, hostname: 'api.status.io', method: 'POST', path: '/v2/incident/create' })

req.write('{ "statuspage_id": "sampleStatusPageId", "all_infrastructure_affected": "0", "current_state": 200, "current_status": 400, "incident_details": "Sample Incident", "incident_name": "Sample Incident", "infrastructure_affected": [ "sampleComponentId-sampleContainerId" ], "social": "0" }')

req.end()

API w/ Python

import requests

requests.post('https://api.status.io/v2/incident/create', json = { 'statuspage_id': 'sampleStatusPageId', 'all_infrastructure_affected': '0', 'current_state': 200, 'current_status': 400, 'incident_details': 'Sample Incident', 'incident_name': 'Sample Incident', 'infrastructure_affected': [ 'sampleComponentId-sampleContainerId' ], 'social': '0' }, headers = { 'x-api-id': '...', 'x-api-key': '...' })

API w/ Ruby

require 'rest-client'

RestClient.post 'https://api.status.io/v2/incident/create', '{ "statuspage_id": "sampleStatusPageId", "all_infrastructure_affected": "0", "current_state": 200, "current_status": 400, "incident_details": "Sample Incident", "incident_name": "Sample Incident", "infrastructure_affected": [ "sampleComponentId-sampleContainerId" ], "social": "0" }', :content_type => 'application/json', :x_api_id => '...', :x_api_key => '...'

Go Client

package main

import "github.com/statusio/statusio-go"

func main() {
  api := statusio.NewStatusioApi("...", "...")

  api.IncidentCreate(statusio.Incident{
    StatuspageID: "sampleStatusPageId",
    AllInfrastructureAffected: "0",
    CurrentState: statusio.StateIdentified,
    CurrentStatus: statusio.StatusPartialServiceDisruption,
    IncidentDetails: "Sample Incident",
    IncidentName: "Sample Incident",
    InfrastructureAffected: []string { "sampleComponentId-sampleContainerId" },
    Social: "0",
  })
}

Node.js Client

const statusio = require('statusio')

var api = new statusio.StatusIOApi('...', '...')

api.setStatusPage('sampleStatusPageId')

api.incidents.create({ all_infrastructure_affected: '0', current_state: 200, current_status: 400, incident_details: 'Sample Incident', incident_name: "Sample Incident", infrastructure_affected: [ 'sampleComponentId-sampleContainerId' ], social: '0' })

Python Client

import statusio

api = statusio.Api('...', '...')

api.IncidentCreate('sampleStatusPageId', [ 'sampleComponentId-sampleContainerId' ], 'Sample Incident', 'Sample Incident', 400, 200)

Ruby Client

require 'statusio'

api = StatusioClient.new('...', '...')

api.incident_create('sampleStatusPageId', 'Sample Incident', 'Sample Incident', [ 'sampleComponentId-sampleContainerId' ], StatusioClient::STATUS_PARTIAL_SERVICE_DISRUPTION, StatusioClient::STATE_IDENTIFIED)
Software

How to Create an Incident in Statuspage

Java

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

public class StatuspageSample {

  public static void main(String[] args) {
    Client client = ClientBuilder.newClient();

    client.target("https://api.statuspage.io/v1/pages/sampleStatusPageId/incidents").request().header("Authorization", "...").post(Entity.json("{ \"incident\": { \"name\":\"Sample Incident\", \"status\": \"identified\", \"components\": { \"sampleComponentId\": \"partial_outage\" }, component_ids\": [ \"sampleComponentId\" ] } }"));

    client.close();
  }

}

Go

package main

import "github.com/go-resty/resty/v2"

func main() {
  client := resty.New()

  client.R().SetHeader("Authorization", "...").SetHeader("Content-Type", "application/json").SetBody(`{ "incident": { "name":"Sample Incident", "status": "identified", "components": { "sampleComponentId": "partial_outage" }, component_ids": [ "sampleComponentId" ] } }`).Post("https://api.statuspage.io/v1/pages/sampleStatusPageId/incidents")
}

Node.js

const https = require('https')

var req = https.request({ headers: { 'Authorization': '...', 'Content-Type': 'application/json' }, hostname: 'api.statuspage.io', method: 'POST', path: '/v1/pages/sampleStatusPageId/incidents' })

req.write('{ "incident": { "name":"Sample Incident", "status": "identified", "components": { "sampleComponentId": "partial_outage" }, component_ids": [ "sampleComponentId" ] } }')

req.end()

Python

import requests

requests.post('https://api.statuspage.io/v1/pages/sampleStatusPageId/incidents', json = { 'incident': { 'name':'Sample Incident', 'status': 'identified', 'components': { 'sampleComponentId': 'partial_outage' }, component_ids': [ 'sampleComponentId' ] } }, headers = { 'Authorization': '...' })

Ruby

require 'rest-client'

RestClient.post 'https://api.statuspage.io/v1/pages/sampleStatusPageId/incidents', '{ "incident": { "name":"Sample Incident", "status": "identified", "components": { "sampleComponentId": "partial_outage" }, component_ids": [ "sampleComponentId" ] } }', :authorization => '...', :content_type => 'application/json'
Software

How to Create a Function in Oracle Functions

Java

SampleFn.java

package com.wordpress.simplesassim.fn;

public class SampleFn {

  public String handle(String input) {
    return "";
  }

}

func.yaml

...

cmd: com.wordpress.simplesassim.fn.SampleFn::handle

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wordpress.simplesassim.fn</groupId>
  <artifactId>sample-fn</artifactId>
  <version>1.0.0</version>
  <repositories>
    <repository>
      <id>fn-release-repo</id>
      <url>https://dl.bintray.com/fnproject/fnproject</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>
  <dependencies>
    <dependency>
      <groupId>com.fnproject.fn</groupId>
      <artifactId>api</artifactId>
      <version>1.0.108</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>14</source>
          <target>14</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Go

func.go

package main

import (
  "context"
  "io"

  fdk "github.com/fnproject/fdk-go"
)

func main() {
  fdk.Handle(fdk.HandlerFunc(handle))
}

func handle(ctx context.Context, in io.Reader, out io.Writer) {
  io.WriteString(out, "")
}

func.yaml

...

entrypoint: ./func

go.mod

module func

Node.js

func.js

const fdk = require('@fnproject/fdk');

fdk.handle(function(input) {
  return ''
})

func.yaml

...

entrypoint: node func.js

package.json

{
  "dependencies": {
    "@fnproject/fdk": ">=0.0.17"
  }
}

Python

func.py

import io
from fdk import response

def handle(ctx, data: io.BytesIO = None):
  return response.Response(ctx, '')

func.yaml

...

entrypoint: /python/bin/fdk /function/func.py handle

requirements.txt

fdk

Ruby

func.rb

require 'fdk'

def handle(context:, input:)
  ''
end

FDK.handle(target: :handle)

func.yaml

...

entrypoint: ruby func.rb

Gemfile

source 'https://rubygems.org' do
  gem 'fdk', '>= 0.0.20'
end
Software

How to Create a Bot for Microsoft Teams

Bot Framework API w/ Java

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

@WebServlet(name = "SampleTeamsServlet", value = "/")
public class SampleTeamsServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    ...

    Client client = ClientBuilder.newClient();

    client.target("https://host/v3/conversations/sampleConversationId/activities/sampleActivityId").request().header("Authorization", "...").post(Entity.json("{ \"type\": \"message\", \"from\": { \"id\": \"sampleBotId\", \"name\": \"SampleBot\" }, \"recipient\": { \"id\": \"sampleUserId\", \"name\": \"Sample User\" }, \"text\": \"Sample Message\" }"));

    client.close();
  }

}

Bot Framework API w/ Go

package main

import (
  "net/http"

  "github.com/go-resty/resty/v2"
  "github.com/gorilla/handlers"
)

func main() {
  http.Handle("/", handlers.MethodHandler{
    http.MethodPost: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      ...

      client := resty.New()

      client.R().SetHeader("Authorization", "...").SetHeader("Content-Type", "application/json").SetBody(`{ "type": "message", "from": { "id": "sampleBotId", "name": "SampleBot" }, "recipient": { "id": "sampleUserId", "name": "Sample User" }, "text": "Sample Message" }`).Post("https://host/v3/conversations/sampleConversationId/activities/sampleActivityId")
    }),
  })

  http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
}

Bot Framework API w/ Node.js

const fs = require('fs')
const https = require('https')

const express = require('express')

var options = {
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem')
}

var app = express()

app.post('/', (req, res) => {
  ...

  var req = https.request({ headers: { 'Authorization': '...', 'Content-Type': 'application/json', 'User-Agent': 'Sample Client' }, hostname: 'graph.facebook.com', method: 'POST', path: '/me/messages' })

  req.write('{ "type": "message", "from": { "id": "sampleBotId", "name": "SampleBot" }, "recipient": { "id": "sampleUserId", "name": "Sample User" }, "text": "Sample Message" }')

  req.end()
})

https.createServer(options, app).listen(8443)

Bot Framework API w/ Python

from flask import Flask
import requests

app = Flask(__name__)

@app.route('/', methods = [ 'POST' ])
def do_post():
  ...

  requests.post('https://host/v3/conversations/sampleConversationId/activities/sampleActivityId', json = { 'type': 'message', 'from': { 'id': 'sampleBotId', 'name': 'SampleBot' }, 'recipient': { 'id': 'sampleUserId', 'name': 'Sample User' }, 'text': 'Sample Message' }, headers = { 'Authorization': '...' })

  return ''

Bot Framework API w/ Ruby

require 'rest-client'
require 'sinatra'

post '/' do
  ...

  RestClient.post 'https://host/v3/conversations/sampleConversationId/activities/sampleActivityId', '{ "type": "message", "from": { "id": "sampleBotId", "name": "SampleBot" }, "recipient": { "id": "sampleUserId", "name": "Sample User" }, "text": "Sample Message" }', :authorization => '...', :content_type => 'application/json'
end

Bot Framework Java SDK

import java.util.concurrent.CompletableFuture;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.microsoft.bot.builder.Activity;
import com.microsoft.bot.builder.ActivityHandler;
import com.microsoft.bot.builder.BotFrameworkAdapter;
import com.microsoft.bot.builder.TurnContext;

@WebServlet(name = "SampleTeamsServlet", value = "/")
public class SampleTeamsServlet extends HttpServlet {
  private BotFrameworkAdapter adapter;

  @Override
  public void init() {
    adapter = ...
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    Jsonb jsonb = JsonbBuilder.create();

    adapter.processIncomingActivity(req.getHeader("Authorization"), jsonb.fromJson(request.getInputStream(), Activity.class), new ActivityHandler() {

      @Override
      public CompletableFuture<Void> onTurn(TurnContext context) {
        context.sendActivity("Sample Message");
      }

    });
  }

}

Bot Framework Node.js SDK

const fs = require('fs')
const https = require('https')

const express = require('express')

var options = {
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem')
}

var app = express()

var adapter = ...

app.post('/', (req, res) => {
  ...

  adapter.processActivity(req, res, (context) => {
    context.sendActivity('Sample Message')
  })
})

https.createServer(options, app).listen(8443)

Bot Framework Python SDK

from botbuilder.schema import Activity
from flask import Flask, request

app = Flask(__name__)

adapter = ...

def on_turn(context):
  context.send_activity('Sample Message')

@app.route('/', methods = [ 'POST' ])
def do_post():
  ...

  adapter.process_activity(Activity.deserialize(request.json), request.headers['Authorization'], on_turn)

  return ''