Paiza Engineering Blog

Engineering blog of browser-based web development environment PaizaCloud Cloud IDE ( https://paiza.cloud/ ), online compiler and editor Paiza.IO( https://paiza.IO/ )

Web development on iPad using PaizaCloud Cloud IDE as iPad IDE

f:id:paiza:20180403161451p:plain
(Japanese article is here)

f:id:paiza:20151217152725j:plainHello, I'm Tsuneo!(@).

Do you have an iPad?

With iPad, we can edit e-mail, browse the web, create documents or spreadsheets or presentation, browser photos or movies quite handy. With millions of applications on App Store, iPad can even be more useful than PC.

Isn't it more useful if we can develop web or other applications on iPad?

So, here comes PaizaCloud Cloud IDE. PaizaCloud is a browser-based web development environment in the Cloud. With PaizaCloud, we can develop web applications or other applications on iPad!

PaizaCloud supports iPad, and have browser-based editor, terminal, browser-in-browser, file manager for building applications. PaizaCloud has development environments like Ruby on Rails, Django, Node.js, Laravel, PHP, Java(tomcat), MySQL, Jupyter Notebook... You don't need to struggle with annoying installing and setting up development environment.

As you can use the same environment from any devices, you can develop on PC today, and continue development on a cafe using iPad tomorrow.

In this article, we actually build a BBS application on iPad using PaizaCloud and Ruby on Rails. We can build the application just in 10 seconds just following the instruction.

Getting started with PaizaCloud Cloud IDE

So, here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and tap a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Tap "new server" to open a dialog to set up the server.

Here, you can choose "Ruby on Rails", "phpMyAdmin", and "MySQL", and tap "New Server" button.

f:id:paiza:20171214154330p:plain

Just in 3 seconds, you'll get a browser-based development environment for Ruby on Rails.

Create an application

Then, let's create your Ruby on Rails application.

You can use "rails new" command to create Ruby on Rails application.

On PaizaCloud Cloud IDE, you can use PaizaCloud's "Terminal" application to run the commands in your browser.

Let's tap the "Terminal" button at the left side of the page.

f:id:paiza:20171214154805p:plain

Now, the "Terminal" application launch. So, let's type "rails new [application name]" command in the Terminal.

f:id:paiza:20171213234417p:plain

The '[application name]' is the name of the application you are creating. You can choose whatever you want, like "music-app" or "game-app". Here, I'll choose the application name "myapp", where I can manage the list of posts.

Also, let's add "--database=mysql" to use MySQL database.

So, lets type:

$ rails new myapp --database=mysql

f:id:paiza:20180403160018p:plain

In the file finder view at the left side of the page, you'll see the "myapp" directory. Tap the folder to open it to see inside the directory.

f:id:paiza:20180402171847p:plain

You'll see a bunch of files for the Ruby on Rails application.

You'll already have a MySQL server running because you checked it on the server setting. But if not, you can always manually start like:

$ sudo systemctl enable mysql
$ sudo systemctl start mysql

On PaizaCloud Cloud IDE, you can install packages on root privilege.

Start Ruby on Rails server

Now, you can already run the application. Let's start the application.

Change the directory by "cd myapp", and type "rails server" to start the server!

$ cd myapp
$ rails server

f:id:paiza:20171213234757p:plain

You'll get a new button with text "3000" on the left side of the page.

f:id:paiza:20171213234820p:plain

Ruby on Rails server runs on port 3000. PaizaCloud Cloud IDE detects the port number(3000), and automatically adds the button to open a browser for the port.

Tap the button, and you'll get Browser application(a Browser application in the PaizaCloud). Now, you'll see web page about Ruby on Rails, that is your application!

f:id:paiza:20171213234947p:plain

Create new database table

Next, let's use database on the application.

On Ruby on Rails, you can just use "rails generate scaffold" command to create all files or a database table, a model, a controller, or a routing.

Here, we create a table "posts" with fields "title", "body", and "published".

Now, open another terminal(or, type 'Ctrl-C' to exit "rails server") and type:

$ rails generate scaffold post title:string body:text published:boolean

f:id:paiza:20180402171820p:plain

After that, run commands for creating and migrating database table.

$ rake db:create
$ rake db:migrate

f:id:paiza:20180402171806p:plain

Done! Put "http://localhost:3000/posts/" in the URL bar of the PaizaCloud browser application.

Then, you'll get the list of the board game. Let's try to add or delete the posts.

f:id:paiza:20180403160110p:plain

You can see the database table using phpMyAdmin.

On PaizaCloud browser application, put "http://localhost/phpmyadmin/" in the URL bar.

f:id:paiza:20180403160134p:plain

Edit files

Now, let's change the title by editing the file.

To edit a file, double-tap the file on the file finder view.

Open "boardgame-app/app/views/games/index.html.erb" for editing.

f:id:paiza:20180402171658p:plain

Then, change the title inside <h1>.

myapp/app/views/posts/index.html.erb:

<h1>Welcome to My BBS!</h1>

f:id:paiza:20180403160213p:plain

Then, click "Save" button, or push "Command-S", or "Ctrl-S".

f:id:paiza:20171213235606p:plain

To see the list from top page, let's redirect from top page to the "/posts/" page.

Open "config/route.rb", and append routing for the root page like below.

config/route.rb:

  root to: redirect('/posts/')

f:id:paiza:20171214000215p:plain

Now, the basics of the application is done!

Adding CSS framework

To make the page beautiful, let's add a minimalist CSS framework Milligram.

app/views/layouts/aplication.html.erb

  <head>
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
    <link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
    <link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">

f:id:paiza:20171214001352p:plain

Now, it's done! Isn't it cool!?

f:id:paiza:20180403161451p:plain

Although we used PaizaCloud on floating window mode, you can switch to tab windows mode for full-screen editing by tapping window bar's maximize button, or by tapping blue button with PaizaCloud button to open a menu and choose "Tab Window Mode".

f:id:paiza:20180403160725p:plain

Summary

With PaizaCloud Cloud IDE, we created a Ruby on Rails application on iPad. Now, let's create your own Ruby on Rails application!


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud


Go/Revel Tutorial: How to create Go(golang) web framework Revel app in browser with PaizaCloud Cloud IDE

f:id:paiza:20180323134353p:plain
(Japanese article is here)

f:id:paiza:20151217152725j:plainHello, I'm Tsuneo!(@)

Go language(golang) have features like: - Standard library has many features including networking. - Easy to write concurrent programs. - Easy to manage executable files as it is only one file.

With these features, Go language is also getting popular for web development.

We can see the popularity from Google Trends below.

f:id:paiza:20180323105259p:plain From google trends

Although we can build web applications only by using Go's rich standard library, web application frameworks make it easier to develop the full-fledged web applications.

There are many Go web application frameworks like Revel, Echo, Gin, Iris, Revel is one of the most popular full-stack web application framework.

Go framework Revel has features for web development like routing, MVC, generator. By building the application following Revel rules, you can naturally create readable and extensible Web Applications. You can also use OR mapper library like Gorm with the Revel.

But, to develop Revel application in practice, you need to install and setup Go, Revel, Gorm, or databases. These installation and setting up can be frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedback from your friends or others will motivate you. But, this requires "deployment" of the service. The "deployment" also frustrates us...

So, here comes PaizaCloud Cloud IDE, a browser-based online web and application development environment.

As PaizaCloud have Go/Revel application development environment, you can just start coding for the Go/Revel application program in your browser.

And, as you can develop in the cloud, you can just run the Go/Revel application on the same machine without setting up another server and deploying to it.

Here, we develop a Task List application using Go and Revel on the PaizaCloud Cloud IDE.

Following the instruction below, you'll create and run the Google Home application just in 10 minutes.

Getting started with PaizaCloud Cloud IDE

So, here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Click "new server" to open a dialog to set up the server.

Here, you can choose "PHP", "phpMyAdmin", and "MySQL", and click "New Server" button.

f:id:paiza:20171214154330p:plain

Just in 3 seconds, you'll get a browser-based development environment for Go and Revel.

You'll see editor or browser windows in the page, but we can close those for now.

Setup environment

Let's set up the environment. As PaizaCloud already have Go language or MySQL installed, you can just run "go get" command to install additional packages.

On PaizaCloud Cloud IDE, you can use PaizaCloud's "Terminal" application to run the commands in your browser.

Let's click the "Terminal" button at the left side of the page.

f:id:paiza:20171214154805p:plain

Now, the "Terminal" application launch. So, let's type "go get [package name]" command in the Terminal.

The '[package name]' is the name of the package to install. Here, we install packages for Revel and Gorm.

So, lets type:

$ go get github.com/revel/revel
$ go get github.com/revel/cmd/revel
$ go get github.com/jinzhu/gorm
$ go get github.com/go-sql-driver/mysql

f:id:paiza:20180323105536p:plain

Now, we have installed the packages to "~/go/bin" .

Create an application

Then, let's create your Go/Revel application.

You can use "revel new" command to create Go/Revel application.

On PaizaCloud Cloud IDE, you can use PaizaCloud's "Terminal" application to run the commands in your browser.

Let's click the "Terminal" button at the left side of the page.

f:id:paiza:20171214154805p:plain

Now, the "Terminal" application launch. So, let's type "revel new [application name]" command in the Terminal.

The '[application name]' is the name of the application you are creating. You can choose whatever you want, like "music-app" or "game-app".

Here, I'll choose the application name "myapp", where I can manage the Task List.

So, lets type:

$ revel new myapp

f:id:paiza:20180323111349p:plain

In the file manager view at the left side of the page, you'll see the "go/src/myapp" directory. Click the folder to open it to see inside the directory.

f:id:paiza:20180323110203p:plain

You'll see a bunch of files for the Go/Revel application.

Start Revel server

Now, you can already run the application. Let's start the application.

Change the directory by typing "cd ~/go" command, and type "revel run myapp" command to start the server!

$ cd ~/go
$ revel run myapp

f:id:paiza:20180323111505p:plain

You'll get a new button with text "9000" on the left side of the page.

f:id:paiza:20180323111533p:plain

Revel server runs on port 9000. PaizaCloud Cloud IDE detects the port number(9000), and automatically adds the button to open a browser for the port.

Click the button, and you'll get Browser application(a Browser application in the PaizaCloud). Now, you'll see web page about the Revel, that is your application!

f:id:paiza:20180323111629p:plain

(Although Revel runs as HTTP server, PaizaCloud can convert from HTTP to HTTPS.)

Editing file

What you see on the application page is an HTML file "~/go/src/myapp/app/views/App/Index.html". Let's try to change the title by editing the file.

On file manager view, double-click the file "~/go/src/myapp/app/views/App/Index.html" for editing.

f:id:paiza:20180323111814p:plain

Edit the title part by replacing 'It works!' like below:

go/src/myapp/app/views/App/Index.html:

      <h1>Hello Go and Revel!</h1>

f:id:paiza:20180326143312p:plain

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

If the server is not running, start the server by typing:

$ revel run myapp

The, click the browser icon with text "9000" on the left-side of the page. If you already have the running browser, click reload button.

f:id:paiza:20180326143503p:plain

You got the message you just wrote on the page!

Create database

You'll already have a MySQL server running because you checked it on the server setting. But if not, you can always manually start like:

$ sudo systemctl enable mysql
$ sudo systemctl start mysql

On PaizaCloud Cloud IDE, you can install packages on root privilege.

Next, create a database for the application. Here, we create a database "mydb" using "mysql" command. Type the command below to create the "mydb" database.

$ mysql -u root
create database mydb;

f:id:paiza:20180216010049p:plain

You created the database.

Then, set the application to use the database. Database configuration file is "conf/app.conf" under the project directory.

Setting for development mode can be written in "[dev]" section. Database settings can be written as "db.info = [DB user]:[DB password]@/[DB name]?[DB options]"

Here, we set DB user as "root", empty password, DB name as "mydb", and some options. So we write the "db.info" setting like below under "[dev]" section.

go/src/myapp/conf/app.conf:

[dev]
db.info = root:@/mydb?charset=utf8&parseTime=True

Then, we create a file "app/controllers/gorm.go" to write code to use the database.

On file manager view, right-click "go/src/myapp/app/controllers" directory to open the context menu, and choose "New File" menu.

f:id:paiza:20180326143634p:plain

Input filename as "gorm.go", and click "Create" button to create the file.

f:id:paiza:20180326143715p:plain

An editor opens, let's write the code like below:

go/src/myapp/app/controllers/gorm.go:

package controllers

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
    "github.com/revel/revel"
    "myapp/app/models"
    "log"
    )

var DB *gorm.DB

func InitDB() {
    dbInfo, _ := revel.Config.String("db.info")
    db, err := gorm.Open("mysql", dbInfo)
    if err != nil {
        log.Panicf("Failed gorm.Open: %v\n", err)
    }

    db.DB()
    db.AutoMigrate(&models.Post{})
    DB = db
}

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

Let's see the code.

On "InitDB()" function, it reads the DB settings from "db.info" line of the configuration file, and open the database using Gorm library. Then, "db.AutoMigrate()" creates a table from Post model we'll create later. It assigns the database handle to "DB" variable so that other files can access the database as "controllers.DB".

Next, edit "app/init.go" to call the InitDB() function.

go/src/myapp/app/init.go:

package app

import (
  "github.com/revel/revel"
  "myapp/app/controllers"
)

...

func init() {
  ...
  revel.OnAppStart(controllers.InitDB)
}

...

There are two lines to add. The first change is to add "myapp/app/controllers" to "imports", and the second change is to add "revel.OnAppStart(controllers.InitDB)" at the end of init() function to call "InitDB()" on "germ.go" we just created.

Create table, model, etc.

Next, let's create a database table.

With Gorm library, we can manipulate the database using model information written in Go struct.

Here, we manipulate the "post" table stored Todo list information, using "Post" model.

We create the "Post" model on "app/models/post.go" file.

Right-click the "go/src/myapp/app" directory to open the context menu, and choose "New directory" menu, and create "models" directory. Right-click the "go/src/myapp/app/models" directory to open the context menu, and choose "New File" menu, and create "post.go" file. Then, edit the created "app/models/post.go" file like below.

go/src/myapp/app/models/post.go:

package models

type Post struct {
    Id  uint64 `gorm:"primary_key" json:"id"`
    Body string `sql:"size:255" json:"body"`
}

Let's see the code. "Post" struct have an integer type field "Id", and a string type field "Body". These represent "id" column and "body" column of the "posts" database table.

Exit and restart the server.

$ cd ~/go
$ revel run myapp

On the application startup, database migration is executed to create "posts" table. We can see the table data using "phpMyAdmin".

On browser on PaizaCloud, type "http://localhost/phpmyadmin/" on the URL field.

f:id:paiza:20180323132256p:plain

We can see the "posts" table. Here, we can add, edit or delete the database records.

Routing settings

The Todo List application has 3 actions: listing todos, adding a todo, or deleting a todo. We set 3 routing for those like below.

Method Path Action
GET /posts List tasks
POST /posts Add a task
DELETE /posts/{id} Delete a task

We set those routing on "routes/web.php" file. At first, remove all the default routings on the file. For about top page "/", set to redirect to "/tasks".

Edit "conf/routes" file like below.

go/src/myapp/conf/routes:

GET     /                                       Post.RedirectToPosts
GET     /posts                                  Post.Index
POST    /posts                                  Post.Create
POST    /posts/:id/delete                       Post.Delete

Let's see the code. "GET /" request calls RedirectToPosts method of Post controller. "GET /posts", "POST /posts", "POST /posts/:id/delete" requests calls "Index", "Create", "Delete" methods of Post controller. The controller methods can refer ":id" part as a parameter.

Controller settings

Create a Post controller referred by the router as "app/controllers/post.go".

Right-click the "app/controllers" directory to open the context menu, and choose "New file" to create "post.go" file.

Define Index(), Create(), Delete() methods for listing, adding, deleting todos.

go/src/myapp/app/controllers/post.go:

package controllers

import (
    "github.com/revel/revel"
    "myapp/app/models"
    "errors"
)

type Post struct {
    *revel.Controller
}

func (c Post) Index() revel.Result {
    posts := []models.Post{}

    result := DB.Order("id desc").Find(&posts);
    err := result.Error
    if err != nil {
        return c.RenderError(errors.New("Record Not Found"))
    }
    return c.Render(posts)
}
func (c Post) Create() revel.Result {
    post := models.Post{
        Body: c.Params.Form.Get("body"),
    }
    ret := DB.Create(&post)
    if ret.Error != nil {
        return c.RenderError(errors.New("Record Create failure." + ret.Error.Error()))
    }
    return c.Redirect("/posts")    
}
func (c Post) Delete() revel.Result {
    id := c.Params.Route.Get("id")
    posts := []models.Post{}
    ret := DB.Delete(&posts, id)
    if ret.Error != nil {
        return c.RenderError(errors.New("Record Delete failure." + ret.Error.Error()))
    }
    return c.Redirect("/posts")    
}

func (c Post) RedirectToPosts() revel.Result {
    return c.Redirect("/posts")    
}

Let's see the code.

Add "myapp/app/models" to "import" so that we can access the Post model. Create Post controller at "type Post struct".

"func (c Post) Index() revel.Result" is a Index() method of the Post controller to return the Todo list. "posts := []models.Post{}" create "posts", an array of Post model. 'DB.Order("id desc").Find(&posts)' retrieve all the "posts" table records, and store them to the "posts" array. Then, if there is no error, call Render() method to create the HTML file. The HTML file is created from the HTML template we will create later on. By setting "posts" to Render() argument, the template file can refer the "posts" table.

"func (c Post) Create() revel.Result" is Create() method of the Post controller to create a Todo. "models.Post{...}" creates a model, retrieve the "body" parameter of the submitted form using "c.Params.Form.Get()", and set it to "Body" field of the model. "DB.Create(&post)" create a database record from the model. Then, redirect to the Todo list page using 'c.Redirect("/posts")'.

"func (c Post) Delete() revel.Result" is a Delete() method of the Post controller to delete a todo. 'c.Params.Route.Get("id")' get the ":id" part of the URL: "/posts/:id/delete". "DB.Delete(&posts, id)" deletes an record of the "id". Then, 'c.Redirect("/posts")' redirects to the Todo list page.

"func (c Post) RedirectToPosts() revel.Result" is to redirect from the top page to Todo list page.

Create HTML template

Next, let's create HTML a template. An HTML template is an HTML file with embedded code.

Create an HTML template file to list, add, and delete Todo as "app/views/Post/index.html".

Right-click "go/myapp/app/views" directory to open the context menu, choose "New Directory" menu, and create "Post" directory. Right-click "go/myapp/app/views/Post" directory to open the context menu, choose "New File" menu, and create "index.html" file.

Edit the created "app/views/Post/index.html" file as below.

go/myapp/app/views/Post/index.html:

{{set . "title" "Todo list"}}
{{template "header.html" .}}

<header class="jumbotron" style="background-color:#A9F16C">
  <div class="container">
    <div class="row">
      <h1>Todo list</h1>
      <p></p>
    </div>
  </div>
</header>

<div class="container">
  <div class="row">
    <div class="span6">
      {{template "flash.html" .}}
    </div>
  </div>
</div>

<div class="container">
    <form action="/posts" method="post">
        <div class="form-group">
            <div class="row">
                <label for="todo" class="col-xs-2">Todo</label>
                <input type="text" name="body" class="col-xs-8">
                <div class="col-xs-2">
                    <button type="submit" class="btn btn-success">
                        <i class="fa fa-plus"></i> Add Todo
                    </button>
                </div>            
            </div>
        </div>
    </form>

    <h2>Current Todos</h2>
    <table class="table table-striped todo-table">
        <thead>
            <th>Todos</th><th>&nbsp;</th>
        </thead>

        <tbody>
            {{ range .posts }}
                <tr>
                    <td>
                        <div>{{ .Body }}</div>
                    </td>
                    <td>
                        <form action="/posts/{{.Id}}/delete" method="post">
                            <button class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            {{ end }}
        </tbody>
    </table>
    
</div>


{{template "footer.html" .}}

Let's see the template file. On the HTML template, a part between "{{" and "}}" is to describe actions which creates HTML.

'{{set . "title" "Todo list"}}' sets "title" variable as "Todo list".

'{{template "header.html" .}}' creates HTML file from a template file "header.html". By calling other HTML templates like this, we can share common parts for multiple template files as the one template file. Here, "header.html" have common HTML header part.

'<form action="/posts" method="post">' is to create a Todo form.

'<input type="text" name="body" class="col-xs-8">' shows a text input form to input a Todo. Set form name to "body" so that "body" parameter of the submitted request has the inputted Todo.

The part between '{{ range .posts }}' and '{{ end }}' is read through posts array, and create HTML from HTML template inside repeatedly for each post.

'{{ .Body }}' shows the "Body" field of each post. '{{.ID}}' shows the Id field of each post.

And, '{{template "footer.html" .}}' shows the HTMP footer from the "footer.html" template.

Run the application

Now, we wrote all the code. Let's see.

Click the browser icon(9000) to open the browser in PaizaCloud.

We see the "Task List" page with the empty task.

Let's add or delete the tasks.

f:id:paiza:20180326144011p:plain

It works! We successfully created the Task List application with Go/Revel!

Note that on PaizaCloud free plan, the server will be suspended. To run the bot continuously, please upgrade to the BASIC plan.

Summary

With PaizaCloud Cloud IDE, we created a Go/Revel application just in your browser, without installing or setting up any development environments. We can even publish the application just on the PaizaCloud. Now, let's create your own Go/Revel application!


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud


Django2.0 Tutorial - How to create Django2.0 ToDo app in browser with PaizaCloud Cloud IDE

f:id:paiza:20180228111025p:plain
(English article is here)

f:id:paiza:20151217152725j:plainHello, I'm Tsuneo!(@)

Python is one of the most popular programing languages. With libraries for machine learning, Python is getting more popular.

Python is a script language. As the Python code can run from one line, it is quite suitable for learning programming. Actually, there is a data that Python is the most popular language to teach in the US universities.

To develop web application with Python, there are several web application frameworks like Django, Pyramid, Flask, Bottle, etc. But among that, Django is obviously the most famous web application framework in Python.

Django is a full stack web application framework with MVC, ORM, generator, etc. By following Django way, you can easily build a well-structured web application.

The latest Django2.0 was just released on Dec 2017. It used to be bothering to think which of Python2 or Python3 to use. But, now, as Django2.0 only support Python3.0, there is nothing to worry about Python version. Now is the good time to start Django!

But, to develop Django application in practice, you need to install and setup Python, Django, or databases. These installation and setting up can be frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedbacks from your friends or others will motivate you. But, this requires "deployment" of the service. The "deployment" also frustrates us...

So, here comes PaizaCloud Cloud IDE, a browser-based online web and application development environment.

As PaizaCloud have Django application development environment, you can just start coding for the Django application program in your browser.

And, as you can develop in the cloud, you can just run the Django application on the same machine without setting up another server and deploying to it.

Here, we develop a Todo List application using Django2.0 on the PaizaCloud Cloud IDE.

Following the instruction below, you'll create and run the Django2.0 application just in 10 minutes.

Getting started with PaizaCloud Cloud IDE

So, here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Click "new server" to open a dialog to set up the server.

Here, you can choose "phpMyAdmin", and "MySQL", and click "New Server" button.

f:id:paiza:20180306171813p:plain

Just in 3 seconds, you'll get a browser-based development environment for Django.

You'll see editor or browser windows in the page, but we can close those for now.

Create an application

Then, let's create your Django application.

You can use "django-admin startproject" command to create Ruby on Rails application.

On PaizaCloud Cloud IDE, you can use PaizaCloud's "Terminal" application to run the commands in your browser.

Let's click the "Terminal" button at the left side of the page.

f:id:paiza:20171214154805p:plain

Now, the "Terminal" application launch. So, let's type "django-admin startproject [project name]" command in the Terminal.

Here, I'll choose the project name "myapp", where I can manage the Todo List.

So, lets type:

$ django-admin startproject mysite

f:id:paiza:20180228111313p:plain

In the file manager view at the left side of the page, you'll see the "mysite" directory. Click the folder to open it to see inside the directory.

f:id:paiza:20180228111355p:plain

You'll see a bunch of files for the Django application.

Editing file

To run Django on PaizaCloud, you need to edit a file "setting.py". On file manager view, double-click the file "mysite/mysite/settings.py" for editing.

f:id:paiza:20180228111523p:plain

Edit the line "ALLOWED_HOST = []" as following.(By this setting, you can connect the application with host name other than "localhost". Even if you change the line, for the server listening on "127.0.0.1", other than the owner user of the server cannot connect to the server.)

ALLOWED_HOSTS = ['*']

f:id:paiza:20180306172249p:plain

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

Start Django server

Now, you can already run the project. Let's run the project!

Change the directory by typing "cd mysite" command, and type "python3 manage.py runserver" command to start the server!

$ cd mysite
$ pyhton3 manage.py runserver

f:id:paiza:20180228111743p:plain

You'll get a new button with text "8000" on the left side of the page.

f:id:paiza:20180216005220p:plain

Django server runs on port 8000. PaizaCloud Cloud IDE detects the port number(8000), and automatically adds the button to open a browser for the port.

Click the button, and you'll get Browser application(a Browser application in the PaizaCloud). Now, you'll see web page about the Laravel, that is your application!

f:id:paiza:20180228111912p:plain

If you see the error message "DisallowedHost at /, Invalid HTTP_HOST header" on the page, check that "mysite/mysite/settings.py" have a line "ALLOWED_HOSTS = ['*']".

f:id:paiza:20180228111834p:plain

Note: While the Django server runs as an HTTP server, PaizaCloud convert it to HTTPS. And, while the server runs on localhost("127.0.0.1"), PaizaCloud allowed us to access the server with URL "https://localhost-SERVERNAME.paiza-user.cloud:PORT/" .

Creating appliation

On Django, a project has applications as sub directories so that we can have multiple applications on one project.

Let's create an application. We use the command "python3 manage.py startapp" to create the application. Here, we create an application named "todo".

Open the Terminal on PaizaCloud, and run the command below on the project directory("mysite") to create the application.

$ python3 manage.py startapp todo

f:id:paiza:20180228112031p:plain

The directories and files for the application are created. Let's see using the file manager view.

f:id:paiza:20180228112309p:plain

Show a message

At first, we'll show a message on the application. The page view is created on the file "mysite/todo/views.py". So, let's edit the file.

On file management view, double-click the file to edit.

f:id:paiza:20180228112428p:plain

Edit the file as below to show the message "Hello Django World".

mysite/todo/views.py:

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello Django world!")

f:id:paiza:20180306172609p:plain

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

On Django, the action to show the page is created as a view function. The view function returns the contents of the page. To show the simple text, we can use "HttpResponse()" function to specify the message to show.

Then, we create a file "urls.py" to set the relations(routings) between URL and view function. The URL routing file for the ToDo application is "mysite/todo/urls.py".

Let's create the file "mysite/todo/urls.py". On PaizaCloud file management view, right-click the directory "mysite/todo", and choose "New File" menu.

f:id:paiza:20180306172656p:plain

As the file creation dialog is shown, create the file with name "urls.py".

f:id:paiza:20180306172727p:plain

Edit the created "mysite/todo/urls.py" as below.

mysite/todo/urls.py:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Let's see the code. On "urlpatterns" list, we call path() function to set URL, view function, and the name of the routing. Here, we set ''(empty string) to URL, "index" function to the view function, and the name to the "index".

Next, to use the application on the project, set the URL routing for the project. URL routing file for the project is "mysite/urls.py", so let's edit the file.

mysite/urls.py:

from django.urls import include, path
from django.contrib import admin
from django.views.generic import RedirectView

urlpatterns = [
    path('todo/', include('todo.urls')),
    path('admin/', admin.site.urls),
    path('',  RedirectView.as_view(url='/todo/')),
]

Let's see the code. On the first item of the "urlpatterns" list, we set the routing for the path '/todo' to "include('todo.urls')" so that the routing settings under '/todo' path can be specified on the file "mysite/todo/urls.py".

On the third item, we set to redirect the top page('/') to "/todo". We use "RedirectView.as_view()" function to set the redirection. We are importing the RedirectView on the third line.

Then, to use the application on the project, edit the settings file("mysite/mysite/settings.py") to add "todo.apps.TodoConfig" to the INSTALLED_APPS list.

mysite/mysite/settings.py

INSTALLED_APPS = [
    'todo.apps.TodoConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Now, the application settings are done. Let's run the application.

If you have not run the server, type command below to start the server.

$ python3 manage.py runserver

Click the browser icon with text "8000" on the left side of the page.

f:id:paiza:20180228113053p:plain

The message is shown! You application creating is running successfully!

Create database

By default, Django uses SQLite as a database. So, you don't need to set up for the database. Now, let's use the more practical database MySQL. (You can skip the setting if you use SQLite.)

You'll already have a MySQL server running because you checked it on the server setting. But if not, you can always manually start like:

$ sudo systemctl enable mysql
$ sudo systemctl start mysql

On PaizaCloud Cloud IDE, you can install packages on root privilege.

Next, create a database for the application. Here, we create a database "mydb" using "mysql" command. Type the command below to create the "mydb" database.

$ mysql -u root
create database mydb;

f:id:paiza:20180216010049p:plain

You created the database.

Then, set the application to use the database.

Database configuration can be set on "mysite/mysite/settings.py".

Open and edit the file to change database engine from SQLite to MySQL. Don't forget to add "import pymysql", "pymysql.install_as_MySQLdb()" to use the MySQL.

mysite/mysite/settings.py:

# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
import pymysql
pymysql.install_as_MySQLdb()

DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#    }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

Create table, model, etc.

Now, let's make application to use the database.

On Django, we can create the table using migration file.

By explicitly writing the table structure on the file, we can easily check, change the table structure and re-create, rollback the table.

Let's create the migration file.

At first, create a Model file for the table. With the model, we can access table column just like a variable.

Edit the file "mysite/todo/models.py" to create the model.

mysite/todo/models.py:

from django.db import models


class Post(models.Model):
    body = models.CharField(max_length=200)

Here, we create Post class with "body" text field related to the "post" table.

Next, run the following command to create the migration file from the model.

$ python3 manage.py makemigrations todo

Then, execute the migration file.

$ python3 manage.py migrate

The "post" table is created, we can also see the database table on "phpMyAdmin".

On the browser on PaizaCloud, type "http://localhost/phpmyadmin/" to open the "phpMyAdmin".

f:id:paiza:20180228120501p:plain

Django management server

Django has a built-in database management UI. Let's use it.

At first, create a management account with commands below.

$ python3 manage.py createsuperuser
Username: admin
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.

Then, edit the "admin.py" file to allow the management server to access the "post" table created.

mysite/todo/admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Let's open the management UI, open the browser on PaizaCloud and type URL "http://localhost:8000/admin/".

f:id:paiza:20180228114500p:plain

As we can see the login page, login using the admin account created.

f:id:paiza:20180228114646p:plain

The management UI is open! We can edit the table here.

f:id:paiza:20180228114918p:plain

Routing settings

On the ToDo list, we have 3 actions: listing ToDos, adding ToDo, deleting ToDo. We assign the routings for those actions like below.

Method Path Action
GET /todo List ToDos
POST /todo/create Add a ToDo
POST /todo/<int:id>/delete Delete a ToDo

We set the routing on "mysite/todo/urls.py" like below.

mysite/todo/urls.py:

from django.urls import path

from . import views

app_name = 'todo'

urlpatterns = [
    path('', views.index, name='index'),
    path('create', views.create, name='create'),
    path('<int:id>/delete', views.delete, name='delete'),
]

Let's see the code. "app_name" need to set to the ToDo application name('todo').

On "urlpatterns" list, we set the routings. On the first item, we set the path '/todo' to call "index" function of "mysite/views.py". On the second item, we set the path '/todo/create' to call "create" function of "mysite/views.py". On the third item, we set the path '/todo/<int:id>' to call "delete" function of "mysite/views.py". By writing the part of the path like "<int:id>'", we can retrieve the part from the program. For example, for the path "/todo/1", we can get the "1" as variable "id".

View settings

Let's write the view code called from the routing. Write functions for listing, adding, and deleting the item as index(), store() and destroy().

mysite/todo/views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from .models import Post
from .forms import PostForm

# Create your views here.
def index(request):
    posts = Post.objects.all()
    form = PostForm()
    context = {'posts': posts, 'form': form, }
    return render(request, 'todo/index.html', context)
    
def create(request):
    form = PostForm(request.POST)
    form.save(commit=True)
    return HttpResponseRedirect(reverse('todo:index'))

def delete(request, id=None):
    post = get_object_or_404(Post, pk=id)
    post.delete()
    return HttpResponseRedirect(reverse('todo:index'))

Let's see the code. On line 4 and 5, we import the model and form class from "models.py", "forms.py".

On the index() function, we call the Post.objects.all() function to retrieve all the ToDo items from the database. The retrieved data is set to the dictionary "context" with the key "posts" so that HTML templates can access the ToDo list as "posts" variable. On the "form" key, we set the empty PostForm object as a value for the submitting form.

On the create() function, we create a PostForm object from the parameter submitted, and call form.save() to save the data to the database. Then, we redirect the request to '/todo' for listing ToDos. We use HttpResponseRedirect() for the redirection. We use reverse() function to convert from the routing name to the URL.

On the delete() function, we call get_object_or_404() function to retrieve the object for the ToDo ID(id). We use post.delete() to delete the object, and redirect to '/todo' like create() method.

Creating HTML template

Then, let's create HTML templates. On HTML templates, we embed the code on the HTML file.

The HTML file can be written in one file. But, as it is more easy to have a common layout file for multiple template files, we create the layout file.

We create the layout file as "mysite/todo/templates/todo/base.html".

On file management view, right-click the directory "mysite/todo", and choose "New Directory" menu, and create the directory with the name "templates".

Next, right-click the directory "mysite/todo/templates" and choose "New Directory", and create the directory with name "todo".

Then, right-click the "mysite/todo/templates/todo" directory and choose "New file" menu, and create the file with name "base.html".

Edit the created layout file like below.

mysite/todo/templates/todo/base.html:

{% load staticfiles %}
<!DOCTYPE html>
<html>
    <head>
        <title>Todo List</title>
        <!-- CSS And JavaScript -->
        <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
        <link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
        <link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
        <link rel="stylesheet" href="{% static 'css/todo.css' %}">
    </head>
    <body>
        <div class="container">
            {% block content %}
            {% endblock %}
        </div>
    </body>
</html>

Let's see the file. We use the simple CSS framework "Milligram" to make the HTML more beautiful. Milligram allows us to make the HTML beautiful without adding CSS class names.

On the body tag, we see "{% block content %}{% endblock %}". Here is the placeholder replaced with each page templates.

Next, let's create an HTML template "mysite/todo/templates/todo/index.html" for listing, adding, and deleting ToDos.

Right-click a directory "mysite/todo/templates/todo", and choose "New File" menu, and create a file with name "index.html". Edit the file like below.

mysite/todo/templates/todo/index.html:

{% extends 'todo/base.html' %}

{% block content %}
    <h1>Todo List</h1>

    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
    <form action="{% url 'todo:create' %}" method="post">
        {% csrf_token %}
        <!-- Todo Name -->
        <div class="form-group">
            <label for="todo" class="col-sm-3 control-label">Todo</label>
            <div class="col-sm-6">
                {{ form.body }}
            </div>
        </div>

        <!-- Add Todo Button -->
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-6">
                <button type="submit" class="btn btn-default">
                    <i class="fa fa-plus"></i> Add Todo
                </button>
            </div>
        </div>

    </form>
    

    <!-- Current Todos -->
    <h2>Current Todos</h2>
    <table class="table table-striped todo-table">
        <thead>
            <th>Todos</th><th>&nbsp;</th>
        </thead>

        <tbody>
            {% for post in posts %}
                <tr>
                    <!-- Todo Name -->
                    <td>
                        <div>{{ post.body }}</div>
                    </td>
                    <td>
                        <form action="{% url 'todo:delete' post.id %}" method="post">
                            {% csrf_token %}
                            <button>Delete</button>
                        </form>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    
{% endblock %}

Let's see the HTML template.

The line "{% extends 'todo/base.html' %}" specify to use the layout file('todo/base.html').

The contents between "{% block content %}" and "{% endblock content %}" is for the page contents. The contents replace the "{% block content %}{% endblock %}" part of the layout file("todo/base.html").

The first form is for adding to ToDo. On Django, the form need to have like "{% csrf_token %}" to protect from CSRF attack.

The "input" tag can be generated by writing the field of PostForm object like "{{ form.body }} ". The like will generate the input form like '<input type="text" name="body" id="id_body" maxlength="200">'.

The form is set to submit to "POST /todo".

On the ToDo listing, we can use "posts" list to access the ToDo items. By writing "{% for post in posts %} ... {% endfor %}", we can set each ToDo item to "post" variable.

"{{ post.body }}" is the Django HTML template format to show the contents of "{{}}". Here, we are accessing "body" property of the "post" object to show the "body" column on the database.

On the "Delete" button, we call "POST /todo/{id}/delete" to delete the specified task.

Creating Model Form

To handle a submitting form, we create a model form class "PostForm".

Create a file "mysite/todo/forms.py", and edit like below.

mysite/todo/forms.py:

from django import forms

from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('body',)

The "field" property is set for the form fields.

Run the application

Now, we wrote all the code. Let's see.

Click the browser icon(8000) to open the browser in PaizaCloud.

We see the "ToDo List" page with the empty task.

Let's add or delete the ToDos.

f:id:paiza:20180306173021p:plain

It works! We successfully created the ToDo List application with Django2.0!

Summary

With PaizaCloud Cloud IDE, we created a Django2.0 application just in your browser, without installing or setting up any development environments. Now, let's create your own Django application!


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud


Laravel5.6: How to create Laravel app in browser with PaizaCloud Cloud IDE

f:id:paiza:20180216002650p:plain
(Japanese article is here)

f:id:paiza:20151217152725j:plainHello I'm Tsuneo!(@)

PHP is a language for Web development, and can runs on HTML by embedding the code. As PHP program can build and run from the small part, it fits for the Web development beginner.

But, if you want to build a full-fledged application, you probably need to use a Web Application Framework on the PHP.

There are several Web Application Frameworks like Laravel, CakePHP, Symfony, Zend Framework, or CodeIgniter. Among those, Laravel is the most popular and growing PHP framework, nowadays.

We can see the popularity from Google Trends below.

f:id:paiza:20180216013143p:plain

Laravel has features for web development like routing, MVC, ORM, generator. By building the application following Laravel rules, you can naturally create readable and extensible Web Applications.

But, to develop Laravel application in practice, you need to install and setup PHP, Laravel, or databases. These installation and setting up can be a frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedbacks from your friends or others will motivate you. But, this requires "deployment" of the service. The "deployment" also frustrates us...

So, here comes PaizaCloud Cloud IDE, a browser-based online web and application development environment.

As PaizaCloud have Laravel application development environment, you can just start coding for the Laravel application program in your browser.

And, as you can develop in the cloud, you can just run the Laravel application on the same machine without setting up another server and deploying to it.

Here, we develop a Task List application using Laravel on the PaizaCloud Cloud IDE.

Following the instruction below, you'll create and run the Laravel application just in 10 minutes.

Getting started with PaizaCloud Cloud IDE

So, here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Click "new server" to open a dialog to set up the server.

Here, you can choose "PHP", "phpMyAdmin", and "MySQL", and click "New Server" button.

f:id:paiza:20171214154330p:plain

Just in 3 seconds, you'll get a browser-based development environment for Laravel.

You'll see editor or browser windows in the page, but we can close those for now.

Create an application

Then, let's create your Laravel application.

You can use "laravel new" command to create Laravel application.

On PaizaCloud Cloud IDE, you can use PaizaCloud's "Terminal" application to run the commands in your browser.

Let's click the "Terminal" button at the left side of the page.

f:id:paiza:20171214154805p:plain

Now, the "Terminal" application launch. So, let's type "laravel new [application name]" command in the Terminal.

The '[application name]' is the name of the application you are creating. You can choose whatever you want, like "music-app" or "game-app".

Here, I'll choose the application name "myapp", where I can manage the Task List.

So, lets type:

$ laravel new myapp

f:id:paiza:20180216003112p:plain

In the file manager view at the left side of the page, you'll see the "myapp" directory. Click the folder to open it to see inside the directory.

f:id:paiza:20180216005011p:plain

You'll see a bunch of files for the Laravel application.

Note that you can also create the Laravel project by using composer command below.

$ composer create-project laravel/laravel myapp --prefer-dist

And, by running the command below, your "laravel new" command will be faster.

$ composer config -g repositories.packagist composer 'https://packagist.jp'
$ composer global require hirak/prestissimo

Start Laravel server

Now, you can already run the application. Let's start the application.

Change the directory by typing "cd myapp" command, and type "php artisan serve" command to start the server!

$ cd myapp
$ php artisan serve

f:id:paiza:20180216005150p:plain

You'll get a new button with text "8000" on the left side of the page.

f:id:paiza:20180216005220p:plain

Laravel server runs on port 8000. PaizaCloud Cloud IDE detects the port number(8000), and automatically adds the button to open a browser for the port.

Click the button, and you'll get Browser application(a Browser application in the PaizaCloud). Now, you'll see web page about the Laravel, that is your application!

f:id:paiza:20180216005704p:plain

Editing file

What you see on the application page is a PHP file "resources/view/welcome.blade.php" under the project directory("myapp"). Let's try to change the title by editing the file.

On file manager view, double click the file "myapp/resources/view/welcome.blade.php" for editing.

f:id:paiza:20180216005750p:plain

Edit the title part inside '<div class="title m-b-md">' tag

myapp/resources/view/welcome.blade.php:

                <div class="title m-b-md">
                    Hello Laravel on PaizaCloud!
                </div>

f:id:paiza:20180216181250p:plain

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

Create database

You'll already have a MySQL server running because you checked it on the server setting. But if not, you can always manually start like:

$ sudo systemctl enable mysql
$ sudo systemctl start mysql

On PaizaCloud Cloud IDE, you can install packages on root privilege.

Next, create a database for the application. Here, we create a database "mydb" using "mysql" command. Type the command below to create the "mydb" database.

$ mysql -u root
create database mydb;

f:id:paiza:20180216010049p:plain

You created the database.

Then, set the application to use the database. Database configuration file is ".env" under the project directory. Files begin with a dot('.') is hidden files that are not visible in the file manager view by default. To make it visible, right click on file manager view and choose "Show Hidden files..." menu.

f:id:paiza:20180216181332p:plain

Then, open the ".env" file and edit 3 lines for "DB_DATABASE"、"DB_USERNAME"、"DB_PASSWORD" settings. As there is no password for the MySQL, comment out for "DB_PASSWORD" setting.

myapp/.env:

DB_DATABASE=mydb
DB_USERNAME=root
# DB_PASSWORD=secret

Create table, model, etc.

Now, let's make application to use the database.

On Laravel, we can create a database table, a model class, and a controller class with "php artisan make:model" command.

Run the command below. The "-m" option is for creating a migration file, the "-c" option is for creating a controller file, and the "-r" option is for creating controller methods related to resource handling.

$ php artisan make:model Task -m -c -r

The command creates following files.

Filename Role
database/migrations/2018_xx_xx_xxxxxxxx_create_tasks_table Migration file
app/Task.php Model
app/Http/Controllers/TaskController.php Controller

The migration file has settings to create a table. Now, let's add a column "name" for the task name. Add "$table->string('name')" to Schema::create() calling like below.

database/migrations/2018_xx_xx_xxxxxxxx_create_tasks_table:

    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

f:id:paiza:20180216010508p:plain

After editing the file, run migration to create the table.

$ php artisan migrate

Now, the "tasks" table is created. If you want to re-run all migration from scratch, you can run "php artisan migrate:refresh" command. We can browse the table using "phpMyAdmin".

On PaizaCloud, open a browser(in browser) and type "http://localhost/phpmyadmin" to the URL field.

f:id:paiza:20180216010802p:plain

Routing settings

The Task List application has 3 actions: listing tasks, adding a task, or deleting a task. We set 3 routing for those like below.

Method Path Action
GET /tasks List tasks
POST /tasks Add a task
DELETE /tasks/{id} Delete a task

We set routing on "routes/web.php" file. At first, remove all the default routings on the file. For about top page "/", set to redirect to "/tasks".

Set "routes/web.php" file like below.

routes/web.php:

Route::get('/', function(){return redirect('/tasks');});
Route::get('/tasks', 'TaskController@index');
Route::post('/tasks', 'TaskController@store');
Route::delete('/tasks/{id}', 'TaskController@destroy');
\URL::forceScheme('https');

Let's see the code. Rout::get is for GET method. The second argument is for setting action using the callback function, or the controller class and action name. For about 'GET /' request, redirect to '/tasks' using the redirect() function. For about 'GET /tasks' request, set the action to call TaskController's index() method. For about 'POST /tasks' request, set the action to call TaskController's store() method. And for about 'DELETE /tasks/{id}' request, set the action to call TaskController's destroy() method. By writing like "{id}", we can get the part from the PHP code. For example, for about "/task/1" request, we get "1" as $id .

And, as PaizaCloud uses HTTPS protocol to access the server, add "\URL::forceScheme('https')". Without this setting, redirect() does not work.

To make sure, let's set to use HTTPS in the application settings. As we can set application wide settings on "AppServiceProvider.php"'s boot() method, add "\URL::forceScheme('https')" to the file like below.

Providers/AppServiceProvider.php;

class AppServiceProvider extends ServiceProvider
{
    ...
    public function boot()
    {
        \URL::forceScheme('https');
    }
    ...
}

Controller settings

Create controller methods code called from the routing.

Write index()、store()、destroy() method for listing tasks, creating a task, or deleting a task like below,

app/Http/Controllers/TaskController.php:

<?php

namespace App\Http\Controllers;

use App\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    public function index()
    {
        $tasks = Task::all();
        return view('tasks', ['tasks' => $tasks]);
    }

    public function store(Request $request)
    {
        $task = new Task;
        
        $task->name = request('name');
        $task->save();
        return redirect('/tasks');
    }

    public function destroy(Request $request, $id, Task $task)
    {
        $task = Task::find($id);
        $task->delete();
        return redirect('/tasks'); 
    }
}

Let's see the code.

"use App\Task" is written to use Task class. Without the "use", we need to write "Task" as "\App\Task".

On index() method for listing tasks, use Task model's Task::all() method to retrieve all the tasks from the database table. Call view() function to render the page. The first argument is setting view file, and the second argument is to set variable names referred on the view file. We set the retrieved tasks to the value of 'tasks' key on the associated array so that the view file can refer tasks as $tasks variable.

On store() method for adding a task, create a Task object and set the submitted name parameter to name property of the Task object, and call $task->save() to save the task to the database. Then, redirect to '/tasks' to show the Task listing page.

On destroy() method for deleting a task, call Task model's Task::find() method to retrieve a task for the task id($id). Call $task->delete() to delete the task, and redirect to '/tasks' to show the Task listing page.

Create view(HTML)

Next, let's create view files. The views are HTML files with embedded PHP code. Laravel uses Blade template engine to make the PHP code more concise.

The view can be just one file. But, as we can have a shared layout for multiple view files, let's create the layout file for now.

Now, we create the layout file with the filename "resources/views/layout.blade.php". To create the file, right-click on the "resources/views" folder and choose "New file" menu, then set filename to "layout.blade.php".

Write the code below on the layout file.

resources/views/layout.blade.php:

<!DOCTYPE html>
<html>
    <head>
        <title>Task List</title>
        <!-- CSS And JavaScript -->
        <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
        <link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
        <link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
    </head>
    <body>
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

On the file, we use simple CSS framework "Milligram". Milligram makes HTML files beautiful without writing additional class names. On "body" tag, there is a line "@yield('content')", here is the place to replace with the page content.

Then, create a file for listing tasks, creating or deleting a task with the filename "resources/views/tasks.blade.php".

Right-click the "resources/views" folder and choose "New file" menu to create a "tasks.blade.php" file.

resources/views/task.blade.php:

@extends('layout')

@section('content')
    <h1>Task List</h1>
    <form action="/tasks" method="POST" class="form-horizontal">
        {{ csrf_field() }}
        <!-- Task Name -->
        <div class="form-group">
            <label for="task" class="col-sm-3 control-label">Task</label>
            <div class="col-sm-6">
                <input type="text" name="name" id="task-name" class="form-control">
            </div>
        </div>

        <!-- Add Task Button -->
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-6">
                <button type="submit" class="btn btn-default">
                    <i class="fa fa-plus"></i> Add Task
                </button>
            </div>
        </div>
    </form>

    <!-- Current Tasks -->
    <h2>Current Tasks</h2>
    <table class="table table-striped task-table">
        <thead>
            <th>Task</th><th>&nbsp;</th>
        </thead>

        <tbody>
            @foreach ($tasks as $task)
                <tr>
                    <!-- Task Name -->
                    <td>
                        <div>{{ $task->name }}</div>
                    </td>
                    <td>
                        <form action="/tasks/{{ $task->id }}" method="POST">
                            {{ csrf_field() }}
                            {{ method_field('DELETE') }}                    
                            <button>Delete Task</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
@endsection

After editing the file, click "Save" button to save the file.

Let's see the file. The line "@content('layout')" is to specify to use the layout file('layout.blade.php'). The area between "@section('content')" and "@endsection" is for the content of the page. The layout file's "@yield('content')" part will be replaced with this content.

The first form is to create a task. On Laravel, we need to add "{{ csrf_field() }}" for CSRF prevention.

On the "input" tag, we set the name to "name" for the task name. The form is set to submit to "POST /tasks".

On the task list, we can refer the task list object as $tasks array. "@foreach ($tasks as $task)" is Blade syntax. It can be written in PHP as "<?php foreach($task as $task){ %>" where we can get each task as $task variable from $tasks array.

The "{{ $task->name }}" is also Blade syntax. "{{...}}" is to show the value inside braces. It can be written in PHP as "<?= $task->name ?>". Here, we refer name property of the $task object to access the "name" column of the "tasks" table on the database.

On "Delete Task" button, set the form to call "DELETE /tasks/{id}" to delete the task. As HTML cannot handle the DELETE method directly, we use "method_field('DELETE')" to emulate the DELETE method.

Model file

Let's see the model file. The model class is empty like below.

Actually, we don't need to set anything. Laravel provides ORM called Eloquent, where table column can be referred as model's property automatically. Isn't it cool?

app/Task.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    //
}

Run the application

Now, we wrote all the code. Let's see.

Click the browser icon(8000) to open the browser in PaizaCloud.

We see the "Task List" page with the empty task.

Let's add or delete the tasks.

f:id:paiza:20180216181609p:plain

It works! We successfully created the Task List application with Laravel!

Note that on PaizaCloud free plan, the server will be suspended. To run the bot continuously, please upgrade to the BASIC plan.

Summary

With PaizaCloud Cloud IDE, we created a Laravel application just in your browser, without installing or setting up any development environments. Now, let's create your own Laravel application!


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud


Alexa Application Development Tutorial in Ruby and PaizaCloud

f:id:paiza:20180207131334j:plain
(Japanese article is here)

f:id:paiza:20151217152725j:plainHello, I'm Tsuneo(@).

Are you using smart speaker?

I just started using Amazon Echo(Alexa). At first, I thought I don't need such a device. But, once start using Alexa, I cannot go back the life without the Alexa.

With Amazon Echo(Alexa), I don't need to pick up my mobile phone but I can just speak to use it without using hands. As the result of evolving machine learning and AI technology, I feel the speech recognition is practical level.

On a research, 18% of the adults in the US have a smart speaker, and 65% of that wouldn't go back to life without one. (Ref: National Public Media The Smart Audio Report from NPR and Edison Research).

And, we can write programs for the Amazon Echo(Alexa) to extend and add features!

Amazon Echo(Alexa) itself is quite useful, but by adding your own feature, it becomes more fun and useful!

As platform handle speech recognition, you can easily write code just by handling simple string.

Everyone can use the smart speaker just by voice. It is fun that your family, friends, or colleague can use your voice application right away.

But, creating and running the Amazon Echo(Alexa) application requires installing and setting up the development environment, and a server to run the Alexa application. Those can be annoying when we just want to create a simple Alexa program.

So, here comes PaizaCloud Cloud IDE, a browser-based online web and application development environment.

As PaizaCloud have Amazon Echo(Alexa) application development environment, you can just start coding for the Alexa application program in your browser.

And, as you can develop in the cloud, you can just run the Alexa application on the same machine without setting up another server and deploying to it.

Here, we develop an Amazon Echo(Alexa) application reading tweets on Twitter using Ruby on the PaizaCloud Cloud IDE.

Following the instruction below, you'll create and run the Amazon Echo(Alexa) application just in 10 minutes.

Getting started with PaizaCloud Cloud IDE

Let's start!

Here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Click "new server" to open a dialog to set up the server. Just click "New Server" button in the dialog without any settings.

f:id:paiza:20171219143410p:plain

Just in 3 seconds, you'll get a browser-based online development environment for creating Alexa application using Ruby.

f:id:paiza:20180116171931p:plain

Create Amazon developer account

Alexa's voice conversation application is called as Alexa Skill.

You can create the Alexa Skill on Amazon Developer site.

Open the Amazon Developer site below.

https://developer.amazon.com/

f:id:paiza:20180207182335p:plain

To develop Alexa application, you need the Amazon developer account. So, let's create it.

Click "Sign In" button at the top of the page.

f:id:paiza:20180207182411p:plain

The Sign In page opens. You can see the logo of the page, and find that the page is not for the Amazon shopping site, but for the developer site.

Here, you can sign in using your Amazon account. You can also create the "Create your Amazon Developer account" link, but it will create the Amazon account for your country, but for US(amazon.com).

Input your profile, and agree to the license. You don't need to change payment settings.

Now, you have your Amazon developer account.

Go to Amazon developer site(https://developer.amazon.com), and click "Sign In" to sign in the developer site.

After the sign in, click "Developer Console" on the top of the page, or just go to the URL below to open the developer console.

https://developer.amazon.com/home.html

f:id:paiza:20180207182510p:plain

Create Alexa Skill

Next, let's create the Alexa Skill.

On the developer site, go to tab menu, and click "ALEXA" tab.

f:id:paiza:20180207182544p:plain

Click "Get Started" button in the "Alexa Skill Kit" box.

f:id:paiza:20180207182630p:plain A page "Building Alexa Skills with the Alexa Skills Kit" opens. Click "Add a new skill".

f:id:paiza:20180207182700p:plain A page to create a new Alexa Skill opens. Here, you can create the Alexa Skill.

Skill: Skill information

At first, set the skill information.

On Skill Type, choose "Custom Interaction Model". And set Language to your language. You can choose from English, German, or Japanese.

Set Name to your Alexa application name. Here, we set it to "My Twitter".

Invocation name is the words to launch your application. Here, we set it to "My Twitter", too. Now, we can launch your application by saying "Alexa ask My Twitter.".

f:id:paiza:20180207182756p:plain Click "Save" button, and then click "Next" button.

Skill: Interaction Model

Next, set the Interaction Model. Here, we set how to recognize the user's voice.

f:id:paiza:20180207182925p:plain At first, let's create the interaction model just greeting without doing anything.

On Intent Schema, set the user's intents. Here, we just create one intent for greeting. Input the intents in JSON format with a GreetIntent intent for greeting.

{
  "intents": [
    {
      "intent": "GreetIntent"
    }
  ]
}

f:id:paiza:20180207182952p:plain

On Custom Slot Types, we have nothing to do.

On Sample Utterance, we set the pair of intent and the user's voice. For now, we only have on intent and nothing to recognize, we input one pair with a placeholder word "Hi" below.

GreetIntent Hi

f:id:paiza:20180207183019p:plain

After the settings, click "Save", and "Next" button.

Skill: Configuration

Now, we open the Configuration.

f:id:paiza:20180207183143p:plain

Here, we set the service endpoint which is the program to response to the user's saying. As the program is called in HTTPS, the program needs to run as a web server on the Internet.

We can choose "Service Endpoint Type" from "AWS Lambda" or "HTTPS". As we run the program on PaizaCloud, we choose "HTTPS".

Although AWS Lambda is scalable, there is limitation on the program languages or flexibility, and it may be difficult for debugging the program.

On Default field, we set the service URL.

Alexa's application program need to run on HTTPS default port with the certificate. As PaizaCloud already have HTTPS(SSL) settings and can run on the arbitrary port, you don't need to set up servers.

On PaizaCloud, the server name is "[SERVER NAME].paiza-user.cloud". The port number of "Sinatra" application we'll create is "80". As you can automatically use HTTPS instead of HTTP on PaizaCloud, the protocol of the URL is HTTPS. On PaizaCloud, the server running on HTTP port 80, can also listen on HTTPS port 443, without any settings, on PaizaCloud. And, we'll use path name '/endpoint'.

So, the URL is " https://[SERVER-NAME].paiza-user.cloud/endpoint "(Replace "[SERVER-NAME]" to your server name on PaizaCloud).

f:id:paiza:20180207183213p:plain

After the setting, click "Save" button, and "Next" button.

Skill: SSL certificate

Next, let's set for SSL certificate. As PaizaCloud have the wildcard certificate, choose the second option "My development endpoint is a sub-domain of a domain that has a wildcard certificate from a certificate authority". Choosing other will cause the connection error.

f:id:paiza:20180207183330p:plain

After the setting, click "Next" button.

Now, you see the "Test" page.

Check that the "This skill is enabled for testing on your account" is enabled. By enabling the setting, you can call your application from your Amazon Echo.

Let's talk to Amazon Echo: "Alexa ask My Twitter".

You got the reply "You cannot access the requested skill". Yes, you have not created the program to answer to user's saying.

So, next, let's create your application program.

Create server program

Now, we create a program on PaizaCloud. Here, we use Ruby and Sinatra to create the server.

On PaizaCloud, you can create and edit the file in the browser. On PaizaCloud, click "New File" button at the left-side of the page.

f:id:paiza:20171219143513p:plain

As a dialog box to put filename is shown, type a filename "server.rb" and click "Create" button.

f:id:paiza:20180131175926p:plain

The file is created!

Let's write a simple application just return the fixed message. Write a Ruby program like below.

server.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/json'

post '/endpoint' do
    return json({
        "version": "1.0",
        "response": {
            "outputSpeech": {
                "type": "PlainText",
                "text": "Here is the server program.",
            },
        }
    })
end

get '/' do
    return "Hello World"
end

f:id:paiza:20180207184132p:plain

After writing the code, click "Save" button to save the file.

Let's see the code. On "post /endpoint'" block, we write the action for the POST "/endpoint" request. The return value for the block will be the HTTP response.

As Alexa endpoint requires the response message on JSON format, we use json() method here.

"speech" field of the return object is the message the application speech. Here, we set the fixed message "Here is the server program.".

Also, to test the program, we write the action for GET '/' request to "get '/'" block. Here, we just return a text "Hello World".

Then, let's run the Slack bot program we created. To run the program, run a command "sudo ruby ./server.rb -o 0 -p 80". As Sinatra listen only on localhost and does not accept connection from out of the server by default, we add "-o 0"(or, "-o 0.0.0.0") option to listen on the global address to accept connection from the clients. And, as you need to run the server on the default port, we add "-p 80" option to listen on the port 80. On PaizaCloud, the server listening on HTTP on the default port(80) can also accept connections from HTTPS on the default port(443). To run the server on the port 80, you need to run the program on root privilege.

On PaizaCloud, you can use a Terminal application in the browser to run the command.

Click "Terminal" button at the left side of the PaizaCloud page.

f:id:paiza:20171214154805p:plain

The Terminal launched. Type the command "sudo ruby ./server.rb -o 0 -p 80", and type enter key.

$ sudo ruby ./server.rb -o 0 -p 80

f:id:paiza:20180115171054p:plain

The command started. The text "tcp://0:80" means that the server is running on port 80.

Now, you see a button with a label "80" at the left-side of the PaizaCloud page.

f:id:paiza:20180207183549p:plain

Sinatra listens on port 80. PaizaCloud detects the port number 80, and add the button for the port 80 to launch browser automatically. On PaizaCloud, you can also connect to the server running on HTTP port 80 with HTTPS port 443.

By clicking the button, browser(a browser on PaizaCloud) launch and you see the message from the server "Hello World".

f:id:paiza:20180115171236p:plain

Now, let's test the program.

Skill: Test

You can test using Amazon Echo. But, on the Amazon developer site, there are simulators where you can test your application in the browser. So, let's use the simulator.

Go to the Amazon developer site below.

https://developer.amazon.com/edw/home.html#/skills

Click "Getting Start" button in "Alexa Skills Kit" box, and choose your application("My Twitter") from the list to open the Skill settings page. From the menu on the left side of the page, choose "Test".

f:id:paiza:20180207183647p:plain

There are some simulators on the page.

On Test Simulator, you can test the dialogue between user and Alexa. But, it looks not working for other than US account.

On Service Simulator, you can test the endpoint and see the request and response JSON message. Let's use the Service Simulator for now.

On the Service Simulator, input something to "Enter Utterance" input box, and click "Ask My Twitter" button.

f:id:paiza:20180207183813p:plain You got the response.

f:id:paiza:20180207183857p:plain

Service Request is the JSON data sent to your Ruby server program that you just created. Service Response is the response from the server program.

You see the message from the server. "Here is the server program". You got the reply!

Then, let's talk to Amazon Echo.

You: "Alexa, ask My Twitter".

Alexa: "Here is the server program".

Yeah! It is succeeded! Your Alexa application works!

Retrieving tweets on Twitter

Then, let's the application read tweets on Twitter.

To read tweets from Twitter on the program, we need Twitter API key. Create the Twitter API key following the article below.

http://paiza.hatenablog.com/entry/paizacloud_twitter_bot_ruby/2018/01/10#twitter_apikey

Then, create a configuration file(twitter-config.rb) on PaizaCloud, and set API keys like below.

Here, replace YOUR_CONSUMER_KEY / YOUR_CONSUMER_SECRET / YOUR_ACCESS_TOKEN / YOUR_ACCESS_SECRET to your application's API key you just created.

twitter-config.rb:

require 'twitter'

config = {
    consumer_key: "YOUR_CONSUMER_KEY",
    consumer_secret: "YOUR_CONSUMER_SECRET",
    access_token: "YOUR_ACCESS_TOKEN",
    access_token_secret: "YOUR_ACCESS_SECRET",
}

$twitterRestClient = Twitter::REST::Client.new(config)
$twitterStreamingClient = Twitter::Streaming::Client.new(config)

Then, change the server program to read tweets.

server.rb:

require 'sinatra/json'
require './twitter-config'

post '/endpoint' do
    tweets = $twitterRestClient.home_timeline
    text = tweets[0].text
    return json({
        "version": "1.0",
        "response": {
            "outputSpeech": {
                "type": "PlainText",
                "text": "I'm reading the latest tweet. " + text,
            },
        }
    })
end

get '/' do
    return "Hello World"
end

Let's see the program. "$twitterRestClient.home_timeline" is to get the latest tweets from your time line using Twitter API. The tweet text can get using "text" method of the Twitter object, it read the latest tweet text using "tweets[0].text". Then, return the message in JSON format.

Exit the running server program(server.rb) by typing Ctrl-C, and re-run.

$ sudo ruby ./server.rb -o 0 -p 80

Let's test the application.

On service simulator, type "ask to My Twitter".

You got the latest tweet message!

Then, let's talk to Amazon Echo.

You: "Alexa, ask My Twitter".

Alexa: "I'm reading the latest tweet. xxx... "

Alexa read the latest tweet. It is succeeded!

Search Tweet on Twitter

Next, let's the application search tweet on Twitter. So, the application will response to the message "Search by xxx".

On developer console(https://developer.amazon.com/edw/home.html#/skills), choose your skill to open Skill settings page.

From the menu on the left side of the page, choose "Interaction Model".

On Intent Schema, set the intents.

Here, we create an intent "SearchIntent" for searching. To handle the variable message like "Search by xxx", we use "slot".

The "slot" is like the variable in programming. The value of the slot is set based on user's saying. Here, we create a slot named "Keyword". The slot requires type. Here, we create a type with name "KEYWORD_TYPE".

{
  "intents": [
     {
      "intent": "SearchIntent",
      "slots": [
        {
          "name": "Keyword",
          "type": "KEYWORD_TYPE"
        }
      ]
    }
  ]
}

Next, on Custom Slot Type, we set slot type. For KEYWORD_TYPE slot, we set the list of possible words user say. By setting the possible user's words, Alexa recognize user's voice accurately. (On English, you can also use type AMAZON.LITERAL to accept all the saying.)

Here, we set the list of sports.

Football
Baseball
Tennis
Swimming
Skiing

f:id:paiza:20180207184025p:plain

After the saving, click "Update" button.

f:id:paiza:20180207184044p:plain

Next, set Sample Utterance. Here, we assign the message "Search by xxx" to KeywordIntent intent. So, let's input like below. {Keyword} is for the slot to accept variable words. (Note: You need white space before the {Keyword}).

SearchIntent Search by {Keyword}

Change the server program "server.rb" like below.

server.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/json'
require './twitter-config'

post '/endpoint' do
    obj = JSON.parse(request.body.read)
    puts "REQUEST:", JSON.pretty_generate(obj)
    message = 'Say "search by something"'
    if obj['request']['intent'] && obj['request']['intent']['slots']['Keyword']
        keyword = obj['request']['intent']['slots']['Keyword']['value']
        
        tweets = $twitterRestClient.search(keyword).take(5)
        if tweets[0]
            text = tweets[0].text
            message = "I read the tweet for keyword #{keyword}." + text
        else
            message = "I could not find any tweet for keyword #{keyword}."
        end        
    end

    return json({
        "version": "1.0",
        "response": {
            "outputSpeech": {
                "type": "PlainText",
                "text": message,
            },
            "shouldEndSession": false,
        }
    })
end

get '/' do
    return "Hello World"
end

Let's see the program. For user's saying "Search by xxx", the part "xxx" is sent in HTTP request body by JSON format. So, use JSON.parse() to parse the request body. Set the initial message to 'Say "search by something"'. The search keyword is stored in request/intent/slots/Any field, retrieve "Keyword" parameter. Use $twitterRestClient.search method to search from Twitter, and return the tweet in JSON format.

Exit the server program with Ctrl-C, and re-run the program(server.rb).

$ sudo ruby ./server.rb -o 0 -p 80

Let's test the program.

Open Service simulator and, type "Search by Football". Do you get the answer?

Then, let's talk with Amazon Echo.

You: "Alexa, ask My Twitter".

Alexa: Say "search by something".

You: "Search by football".

Alexa: I read the tweet for keyword football. xxx..."

Yeah! You are talking with Alexa! You created your Alexa application!

Note that on PaizaCloud free plan, the server will be suspended. To run the bot continuously, please upgrade to the BASIC plan.

Summary

We created an Amazon Echo(Alexa) application on PaizaCloud using Ruby, and run it on the same environment.

We can create Amazon Echo(Alexa) applications without implementing speech recognition. It is fascinating that everyone can easily use the voice application. It is quite fun to create the application thinking what to response to the user's message. Now, it is the time to create your own application!

 


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud


Google Home Development Tutorial with Ruby, PaizaCloud

f:id:paiza:20180119011449j:plain
(Japanese article is here)

f:id:paiza:20151217152725j:plainHello, I'm Tsuneo(@).

Are you using smart speaker?

I just started using Google Home. At first, I thought I don't need such a device. But, once start using Google Home, I cannot go back the life without the Google Home.

With Google home, I don't need to pick up my mobile phone but I can just speak to use it without using hands. As the result of evolving machine learning and AI technology, I feel the speech recognition is practical level.

On a research, 18% of the adults in the US have a smart speaker, and 65% of that wouldn't go back to life without one. (Ref: National Public Media The Smart Audio Report from NPR and Edison Research).

And, we can write programs for the Google Home to extend and add features!

Google Home itself is quite useful, but by adding your own feature, it becomes more fun and useful!

As platform handle speech recognition, you can easily write code just by handling simple string.

Everyone can use the smart speaker just by voice. It is fun that your family, friends, or colleague can use your voice application right away.

But, creating and running the Google Home application requires installing and setting up the development environment, and a server to run the Google Home application. Those can be annoying when we just want to create a simple Google Home program.

So, here comes PaizaCloud Cloud IDE, a browser-based online web and application development environment.

As PaizaCloud have Google Home application development environment, you can just start coding for the Google Home application program in your browser.

And, as you can develop in the cloud, you can just run the Google Home application on the same machine without setting up another server and deploying to it.

Here, we develop a Google Home application reading tweets on Twitter using Ruby on the PaizaCloud Cloud IDE.

Following the instruction below, you'll create and run the Google Home application just in 10 minutes.

Getting started with PaizaCloud Cloud IDE

Let's start!

Here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Click "new server" to open a dialog to set up the server. Just click "New Server" button in the dialog without any settings.

f:id:paiza:20171219143410p:plain

Just in 3 seconds, you'll get a browser-based online development environment for creating Google Home application using Ruby.

f:id:paiza:20180116171931p:plain

Create Google Assistant application

We can add features to Google Home by creating a Google Assistant application.

The Google Assistant application can be built on a web site called Actions on Google.

Open the Actions on Google page below:

https://console.actions.google.com/

f:id:paiza:20180119104802p:plain

Click "Add/import project" button.

f:id:paiza:20180119104824p:plain

As "Add project" dialog box is shown, input your project name and the country name. Here, we input "MyTweet" to the project name, and set country to "Japan". Then, click "CREATE PROJECT" button.

f:id:paiza:20180119105027p:plain

A project is created on the Actions on Google. To build speech application for the project, we use Dialogflow.

Click "BUILD" button on "Dialogflow".

f:id:paiza:20180119105054p:plain f:id:paiza:20180119105155p:plain Click "CREATE ACTIONS ON DIALOGFLOW" button to create a Dialogflow action.

If you are required to login or authenticate, login to the service.

f:id:paiza:20180119105117p:plain

Switch "DEFAULT LANGUAGE" to your language(Ex: Japanese), and click "CREATE" button.

f:id:paiza:20180119105330p:plain

An agent for the conversation application is created on the Dialogflow.

The first conversation

At first, let the Google assistant application say something!

On Dialogflow menu, click "Intents".

f:id:paiza:20180131174517p:plain

Click "Default Welcome Intent", which is the place to write action just after the application starts.

Go "Response" section. "Text response" is the place to set what the application says. Click trash icon to remove the default message. Click "ADD MESSAGE CONTENT" button and choose "Text response" to add a message. Here, we set the message to "Welcome to My Twitter".

Then, click "SAVE" button on the top of the page to save the configuration.

f:id:paiza:20180131174714p:plain

Next, we set up Google Assistant application on Actions on Google.

Open https://console.actions.google.com/ , and click the project we created(My Twitter).

f:id:paiza:20180119110016p:plain

We set up the application on "Overview" page. While we need to set up correctly when we publish the application. For now, we just need to put something on the all required fields.

Go "App information" and click "EDIT".

To change the language, you can click "Add Language" to choose the language(Ex: "Japanese").

f:id:paiza:20180119110125p:plain

Set the application name and the pronunciation for that. Here, we can set "My Twitter" to both application name and pronunciation field, and click "NEXT" button.

As we launch the application by talking "OK Google, talk to My Twitter", you need to set the name easy to pronounce.

f:id:paiza:20180131174912p:plain

On "Details" section, set "Assistant app introduction"、"Short description"、"Full description". We can set like "Read tweets on Twitter". Then, click "NEXT" button.

f:id:paiza:20180131175115p:plain

On "Images" section, set the application images. For now, we can set any image files as placeholders.

f:id:paiza:20180119110752p:plain

On "Contact details" section, set your e-mail address.

f:id:paiza:20180119110821p:plain

On "Privacy and consent" section, set the application's privacy policy("Privacy Policy"). you can set something like "https://privaci.policy/" as a placeholder for now.

f:id:paiza:20180119110834p:plain

On "Additional Information", choose the category(Category) for your application. Set "Social & comminication", and click "Save" button.

f:id:paiza:20180119110924p:plain

After setting up everything for the application, click "TEST DRAFT" button. The actions Simulator launches.

f:id:paiza:20180131175612p:plain

Let's type "Talk to My Twitter".

f:id:paiza:20180131175810p:plain

A message "Welcome to My Twitter" we set was written, and was speeched.

Now, we can use the application from your Google Home. Let's talk to your Google Home like "OK Google, talk to My Twitter".

Now, Google Home says the response message!

Call conversation program

Next, let's the application read tweets from Twitter.

Open Dialogflow console( https://console.dialogflow.com/ ).

To call external service from Dialogflow, we use Fulfillment.

On menu, choose Fulfillment.

f:id:paiza:20180119111425p:plain

Now, we set the URL of the external service to the URL field. The service runs on PaizaCloud have hostname "[SERVER-NAME".paiza-user.cloud".

On PaizaCloud, the server name is "[SERVER NAME].paiza-user.cloud". The port number of "Sinatra" application we'll create is "4567". As you can automatically use HTTPS instead of HTTP on PaizaCloud, the protocol of the URL is HTTP. And, we'll use path name '/webhook' .

So, the URL is " https://[SERVER-NAME].paiza-user.cloud:4567/webhook "(Replace "[SERVER-NAME]" to your server name on PaizaCloud).

f:id:paiza:20180119111600p:plain

Click "SAVE" button to save the settings.

Next, on the menu, choose "Intents", and "Default Welcome Intent". Now, we can see "Fulfillment" section, so click the "Fullfillment" to open, and click "User webhook". Now, when the application launch, the Google Home application connect to the server running on the PaizaCloud.

f:id:paiza:20180119111642p:plain

Create server program

Now, we create a program on PaizaCloud. Here, we use Ruby and Sinatra to create the server.

On PaizaCloud, you can create and edit the file in the browser. On PaizaCloud, click "New File" button at the left-side of the page.

f:id:paiza:20171219143513p:plain

As a dialog box to put filename is shown, type a filename "server.rb" and click "Create" button.

f:id:paiza:20180131175926p:plain

The file is created!

Let's write a simple application just return the fixed message. Write a Ruby program like below.

server.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/json'

post '/webhook' do
  return json({
      speech: "Here is the server program."
  });
end

get '/' do
  return "Hello World"
end

f:id:paiza:20180131180151p:plain

Then, click "Save" button to save the file.

Let's see the code. On "post /webhook'" block, we write the action for POST "/webhook" request. The return value for the block will be the HTTP response.

As Dialogflow's Fulfillment Webhook requires the response message on JSON format, we use json() method here.

"speech" field of the return object is the message the application speech. Here, we set the fixed message "Here is the server program.".

Also, to test the program, we write the action for GET '/' request to "get '/'" block. Here, we just return a text "Hello World".

Then, let's run the Slack bot program we created. To run the program, run a command "ruby ./server.rb -o 0". As Sinatra listen only on localhost and does not accept connection from out of the server by default, we add "-o 0"(or, "-o 0.0.0.0") option to listen on the global address to accept connection from the clients.

On PaizaCloud, you can use a Terminal application in the browser to run the command.

Click "Terminal" button at the left side of the PaizaCloud page.

f:id:paiza:20171214154805p:plain

The Terminal launched. Type the command "ruby ./server.rb -o 0", and type enter key.

$ ruby ./server.rb -o 0

f:id:paiza:20180115171054p:plain

The command started. The text "tcp://0:4567" means that the server is running on port 4567.

Now, you see a button with a label "4567" at the left-side of the PaizaCloud page.

f:id:paiza:20180115171204p:plain

Sinatra listens on port 4567. PaizaCloud detects the port number 4567, and add the button for the port 4567 to launch browser automatically.

By clicking the button, browser(a browser on PaizaCloud) launch and you see the message from the server "Hello World".

f:id:paiza:20180115171236p:plain

Now, let's test the program.

On Dialogflow, see the right side of the page and click "See how it works in Google Assistant." to run the action Simulator. (Or, on "Actions on Google" project menu, click "Simulator")

f:id:paiza:20180119112015p:plain

Type "talk to My Twitter". The message "Here is the server program." was written. We got the response message from the Ruby server program we just created!

Now, let's talk to Google Home.

Say "talk to My Twitter" to the Google Home.

f:id:paiza:20180131181225p:plain

The Google Home says "Here is the server program"! Yeah, it just works!

Retrieving tweets on Twitter

Then, let's the application read tweets on Twitter.

To read tweets from Twitter on the program, we need Twitter API key. Create the Twitter API key following the article below.

http://paiza.hatenablog.com/entry/paizacloud_twitter_bot_ruby/2018/01/10#twitter_apikey

Then, create a configuration file(twitter-config.rb) on PaizaCloud, and set API keys like below.

Here, replace YOUR_CONSUMER_KEY / YOUR_CONSUMER_SECRET / YOUR_ACCESS_TOKEN / YOUR_ACCESS_SECRET to your application's API key you just created.

twitter-config.rb:

require 'twitter'

config = {
    consumer_key: "YOUR_CONSUMER_KEY",
    consumer_secret: "YOUR_CONSUMER_SECRET",
    access_token: "YOUR_ACCESS_TOKEN",
    access_token_secret: "YOUR_ACCESS_SECRET",
}

$twitterRestClient = Twitter::REST::Client.new(config)
$twitterStreamingClient = Twitter::Streaming::Client.new(config)

Then, change the server program to read tweets.

server.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/json'
require './config'

post '/webhook' do
  tweets = $restClient.home_timeline
  text = tweets[0].text
  return json({
      speech: "Reading the latest tweets using API." + text
  });
end

get '/' do
  return "Hello World"
end

Let's test the application.

On Dialogflow, see the right side of the page and click "See how it works in Google Assistant." to run the action Simulator. (Or, on "Actions on Google" project menu, click "Simulator")

Let's type "talk to My Twitter".

You got the latest tweet message!

Then, let's talk to Google Home.

Say "OK Google, talk to My Twitter".

Google Home read the latest tweet on Twitter!

Search tweet on Twitter

Next, let's add a feature to search a tweet from Twitter.

Let's make the application response to the message "search xxx".

Open Dialogflow( https://console.dialogflow.com/ ). On the menu, choose "Intents" and click "CREATE INTENT" button to show the page to create the Intent.

Set expected user's voice to "User says" field.

At first, type "Search foo".

f:id:paiza:20180131180338p:plain

As the part of "foo" is not fixed, set the part as a parameter. Choose the area "foo" and click it. As the list is shown, choose "@sys.any".

f:id:paiza:20180131180502p:plain

Set "keyword" to "PARAMETER NAME". Now, the part of "foo" can be anything and can be referred as "keyword" parameter of the message.

f:id:paiza:20180131180642p:plain

As the parameter is required, check "REQUIRED" checkbox. To set the message for the case user's message doesn't containers the parameter, click "Define prompts...".

f:id:paiza:20180131180759p:plain Here, we set "Set search keyword like: search whatever".

f:id:paiza:20180131180827p:plain As we use the server program on PaizaCloud, click "Fulfillment", and check "Use Fulfillment", and check "Use webhook".

f:id:paiza:20180119111642p:plain

Click "SAVE" button to save the settings.

Change the Ruby server program("server.rb") like below:

server.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/json'
require './config'

post '/webhook' do
    obj = JSON.parse(request.body.read)
    keyword = obj['result']['parameters']['keyword']
    puts "keyword=#{keyword}"
    if ! keyword
        tweets = $twitterRestClient.home_timeline
        text = tweets[0].text
        return json({
            speech: "I'm reading the latest tweet on Twitter. " + text
        });
    else
        tweets = $twitterRestClient.search(keyword).take(5)
        if tweets[0]
            text = tweets[0].text
            return json({
                speech: "I'm reading a tweet of the search result for keyword #{keyword}." + text
            });
        else
            return json({
                speech: "I cannot find any tweet for keyword #{keyword}."
            });
        end
            
    end
end

get '/' do
  return "Hello World"
end

Let's see the code. For the user's message "Search for xxx", the keyword part "xxx" is passed to the program as HTTP request body as JSON format. So, convert it to the object using JSON.parse(). As the parameters are passed as "result", "parameters" field, we get the "keyword" parameter from it.

Let's test the program.

On Dialogflow, see the right side of the page, and click "See how it works in Google Assistant." to start action Simulator(Or, on "Actions on Google" project menu, click "Simulator".)

Type "talk to My Twitter". Then input "search by ...".

We got the search result!

Next, let's talks to the Google Home.

Say "OK Google, talk to My Twitter", the say "search by ...".

Google Home says the Twitter search result! It's succeeded!

Now, we created the Google Home application to speech tweets on Twitter!

Note that on PaizaCloud free plan, the server will be suspended. To run the bot continuously, please upgrade to the BASIC plan.

Summary

We created a Google Home application on PaizaCloud using Ruby, and run it on the same environment.

We can create Google Home application without implementing speech recognition. It is fascinating that everyone can easily use the voice application. It is quite fun to create the application thinking what to response to the user's message. Now, it is the time to create your own application!

 


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud


Create and Run Slack bot with Ruby on PaizaCloud Cloud IDE

f:id:paiza:20180115170315p:plain
(Japanese article is here)

f:id:paiza:20151217152725j:plainHello I'm Tsuneo(@).

Now, Slack is one of the most major communication tools. And, by creating a Slack bot program, the bot program can communicate with people using text message.

As Slack bot program only handle text messages, it is easy to write code for the Slack bot program. And, as people can easily use the Slack bot just by sending text messages, the bot developer can easily get feedback from the user and it motivates us to improve the Slack bot. So, for the programming beginner, developing Slack bot will be the good practice.

But, creating and running the Slack bot requires installing and setting up the development environment, and a server to run the Slack bot. Those can be annoying when we just want to create a simple Slack bot program.

So, here comes PaizaCloud Cloud IDE, a browser-based online web and application development environment.

As PaizaCloud have Slack bot development environment, you can just start coding for the Slack bot program in your browser.

And, as you can develop in the cloud, you can just run the Slack bot on the same machine without setting up another server and deploying to it.

Here, we develop a Slack bot using Ruby on the PaizaCloud Cloud IDE.

Following the instruction below, you'll create and run the Slack bot just in 5 minutes.

Getting started with PaizaCloud Cloud IDE

Let's start!

Here is the website of PaizaCloud Cloud IDE.

https://paiza.cloud/

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

f:id:paiza:20171214154558p:plain

Click "new server" to open a dialog to set up the server. Just click "New Server" button in the dialog without any settings.

f:id:paiza:20171219143410p:plain

Just in 3 seconds, you'll get a browser-based online development environment for creating Slack bot using Ruby.

f:id:paiza:20180116171931p:plain

Create Slack application

We need to create a Slack application to run a Slack bot. So, let's create the Slack application.

Open the Slack application page below.

https://api.slack.com/apps

f:id:paiza:20180115170344p:plain

If you have not signed up, click a "sign in to your Slack account" link, and open "https://api.slack.com/apps", again.

f:id:paiza:20180115170402p:plain

You'll see the list of application. To create an application, click "Create New App" button.

f:id:paiza:20180115170417p:plain

You'll see a dialog box to create the Slack application. Put your application name and select your Slack workspace. Here, we set the application name "MyBot" as an example. And, click a "Create App" button to create the application.

Now, the Slack application is created, you'll see the Slack application page below.

f:id:paiza:20180115170432p:plain

Create Slack command

At first, let's create a Slack command. Slack command is a command text begin with a slash('/'). For example, if you type a Slack command "/who" in the channel, you'll see the list of users in the channel.

Here, we create a Slack command "/time" to display the date and time.

On application page, in the "Add features and functionality", click "Slash Commands".

f:id:paiza:20180115170456p:plain

Click "Create New Command" button.

f:id:paiza:20180115170919p:plain

As a command creation page is shown, put a command name "/time" to the "Command" field.

Put a URL for the server program we will create on PaizaCloud to the "Request URL" field.

On PaizaCloud, the server name is "[SERVER NAME].paiza-user.cloud". The port number of "Sinatra" application we'll create is "4567". As you can automatically use HTTPS instead of HTTP on PaizaCloud, the protocol of the URL is HTTP.

So, the URL is " https://[SERVER-NAME].paiza-user.cloud:4567/ "(Replace "[SERVER-NAME]" to your server name on PaizaCloud).

Put the description of your bot to "Short Description" field, and put your command's usage to "Usage Hint" field.

Then, click "Save" button to save the settings.

Now, you have created the Slack command. You'll see the list of commands like below.

f:id:paiza:20180115170938p:plain

Then, to use the Slack application, install the Slack application to your Slack workspace.

Select "Install App" from the menu. On the installation page, click "Install App to Workspace" button.

f:id:paiza:20180115173815p:plain

You see the authorization page. Click "Authorize" button to authorize the Slack application.

f:id:paiza:20180115173829p:plain

Now, create a Ruby program to run when the Slack command is sent.

On PaizaCloud, you can create and edit the file in the browser. On PaizaCloud, click "New File" button at the left-side of the page.

f:id:paiza:20171219143513p:plain

As a dialog box to put filename is shown, type a filename "command.rb" and click "Create" button.

f:id:paiza:20180116172115p:plain The file is created!

Let's write a simple Slack command program using Ruby and Sinatra. Write a program like below.

command.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/json'

post '/slack/command' do
    text = params['text']
    return json({
        text: "The command succeeded! The command parameter is #{text}.",
        response_type: 'in_channel',
    })
end

get '/' do
  return "Hello World"
end

f:id:paiza:20180116172209p:plain Click "Save" button to save the file.

Let's see the program. The "post '/slack/command'" block define an action for POST "/slack command" requests. You see the request parameter as "params". For the Slack command message, you can get the parameter text following the command by "params['text']".

The object returned in the block will be the response to the request. Put reply message to "text" field, and put 'in_channel' to the "response_type" field to show the message to not only you but also the members of the channel.

Here, we set the reply message to "The command succeeded! The command parameter is #{text}".("#{text}" is the command message's parameter text). Add an action to GET '/' request to check that the service is running.

Then, let's run the Slack bot program we created. To run the program, run a command "ruby ./command.rb -o 0". As Sinatra listen only on localhost and does not accept connection from out of the server by default, we add "-o 0"(or, "-o 0.0.0.0") option to listen on the global address to accept connection from the clients.

On PaizaCloud, you can use a Terminal application in the browser to run the command.

Click "Terminal" button at the left side of the PaizaCloud page.

f:id:paiza:20171214154805p:plain

The Terminal launched. Type the command "ruby ./command.rb -o 0", and type enter key.

$ ruby ./command.rb -o 0

f:id:paiza:20180115171054p:plain

The command started. The text "tcp://0:4567" means that the server running on port 4567.

Now, you see a button with a label "4567" at the left-side of the PaizaCloud page.

f:id:paiza:20180115171204p:plain

Sinatra listens on port 4567. PaizaCloud detects the port number 4567, and add the button for the port 4567 to launch browser automatically.

By clicking the button, browser(a browser on PaizaCloud) launch and you see the message from the server "Hello World".

f:id:paiza:20180115171236p:plain

Then, let's send a Slack command. Type "/time TestTest" message on the Slack.

f:id:paiza:20180116172521p:plain

You got the response for the command! Slack command works!

Next, change the program to reply the date and time like below.

command.rb:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/json'

ENV['TZ'] = 'JST-9'  # Timezone

post '/slack/command' do
    text = params['text']
    if text =~ /now/i
        now = Time.now
        responseText = "Now is #{now.hour}:#{now.min}:#{now.sec} ."
    elsif text =~ /today/i
        today = Time.now
        responseText = "Today is #{today.year}-#{today.month}-#{today.day} ."
    elsif text =~ /tomorrow/i
        tomorrow = Time.now + (60*60*24)
        responseText = "Tomorrow is #{today.year}-#{today.month}-#{today.day} ."
    else
        responseText = "Example: Now/Today/Tomorrow"
    end
    json({
        text: responseText,
        response_type: 'in_channel',
    })
end

get '/' do
  return "Hello World"
end

The code checks whether the message text contains strings(now/today/tomorrow) using regular expressions, and send reply message by returning a object with the replying text message.

Exit the command("ruby ./command.rb -o 0") by typing Ctrl-C, and re-run the command.

Let's see. Type the Slack commands like below on Slack.

/time What time is it now ?
/time What date is it today ?
/time How about tomorrow ?

You got the reply! You successfully created a Slack command to reply date and time.

f:id:paiza:20180116173615p:plain

Create Slack bot

While the program can answer for the Slack command, you need to send the specific Slack command as a message.

To make the bot program to handle other than Slack command, we can create Slack bot.

To create the Slack bot, go to Slack application page(https://api.slack.com/apps), and choose the Slack application, and choose "Basic information" from the menu.

f:id:paiza:20180115174145p:plain

Click "Add features and functionality", and choose "Bots" from the list.

f:id:paiza:20180115172052p:plain

On the Bot User creation page, click "Add Bot User" button.

f:id:paiza:20180115172103p:plain

If permission changing is requested, click "Click Here" link, and on the next page, click "Authorize" button to allow changing the permission.

f:id:paiza:20180115172119p:plain f:id:paiza:20180115172129p:plain

To create a Slack bot, we need Bot User OAuth Access Token.

On application page menu, click "Auth & Permission" on "Features", and notes the "Bot User OAuth Access Token" string begin with "xoxb-".

f:id:paiza:20180115172349p:plain

Now, let's write a Slack bot program in Ruby.

Slack bot requires WebSocket. So, we use a Ruby gem library called "faye-websocket". Run the command below to install the "faye-websocket" Ruby gem.

$ sudo gem install faye-websocket

f:id:paiza:20180115172448p:plain

Create a file "bot.rb", and write Ruby code like below. The program reply date and time, as the Slack command we just created.

Here, replace "OAUTH-TOKEN" to the "Bot User OAuth Access Token" string that begins with "xoxb-".

bot.rb:

require 'http'
require 'json'
require 'eventmachine'
require 'faye/websocket'

TOKEN='***OAUTH-TOKEN***'

ENV['TZ'] = 'JST-9' # Timezone

response = HTTP.get("https://slack.com/api/rtm.connect", params: {token: TOKEN})
resposeObj = JSON.parse(response.body)

url = resposeObj['url']

EM.run do
  puts "Connecting to #{url}..."
  ws = Faye::WebSocket::Client.new(url)

  ws.on :open do |event|
    p [:open]
  end

  ws.on :message do |event|
    msg = JSON.parse(event.data)
    p [:message, JSON.parse(event.data)]
    
    if msg["type"] != 'message'
        next
    end
    text = msg["text"]

    if text =~ /now/i
        now = Time.now
        responseText = "Now is #{now.hour}:#{now.min}:#{now.sec} ."
    elsif text =~ /today/i
        today = Time.now
        responseText = "Today is #{today.year}-#{today.month}-#{today.day} ."
    elsif text =~ /tomorrow/i
        tomorrow = Time.now + (60*60*24)
        responseText = "Tomorrow is #{tomorrow.year}-#{tomorrow.month}-#{tomorrow.day} ."
    end
    
    reply = {
        type: 'message',
        text: responseText,
        channel: msg['channel'],
    }
    puts "Replying: #{reply}"
    ws.send(reply.to_json)
  end

  ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
    EM.stop
  end

end

Let's see the code. It accesses to "https://slack.com/api/rtm.connect" with the TOKEN parameter to retrieve WebSocket URL, and assign the URL to "url" variable.

It connects to the WebSocket URL using eventmachine(EM) and faye-weboskcket(Faye::WebSocket::Client).

"ws.on :message" block handles WebSocket messages. We only handle the message with type 'message'. msg["text"] is the message text. It checks whether the message text contains strings(now/today/tomorrow) using regular expressions, and send reply message using "ws.send" method. On the "ws.send" parameter, set 'message' to the "type" field, message text to the "text" field, and the channel to response(here, the channel of the sent message) to the "channel" field.

Now, let's run the Slack bot! Run a command "ruby ./bot.rb" on the Terminal on PaizaCloud.

$ ruby ./bot.rb

As the Slack bot can only read message on the channel it joined, invite the bot user to the channel.

Now, let's send the message !

f:id:paiza:20180116174406p:plain

Yay! We got the message from the Slack bot we created!

We successfully create the Slack bot using Ruby on PaizaCloud!

Note that on PaizaCloud free plan, the server will be suspended. To run the bot continuously, please upgrade to the BASIC plan.

Summary

We created and ran a Slack bot using Ruby on PaizaCloud. It is quite simple to create and run the Slack bot. It is fun to think how the Slack bot works, and improve the bot. Now, let's create your own Slack bot on PaizaCloud!


With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser. https://paiza.cloud