LoginSignup
0
1

More than 3 years have passed since last update.

LaTeX表記の数式を画像で返送するLINE botの作成

Last updated at Posted at 2020-07-19

$ax^2+bx+c=0$のように$記号でLaTeX表記の数式を囲むと、画像が返送されます。なお、1つのメッセージにつき1つの数式を返すことができます。
スクリーンショット 2020-07-19 23.26.59.png
LaTeX表記については、http://www.latex-cmd.com をご覧ください。

友だち追加

ここから友だち追加をすることができます。

開発

以下の参考を読み、実装しました。

参考

Google Chart APIの数式は非推奨となったようなので、いつ使えなくなるかはわかりません。
CGIモジュールを使用しているのは、+などの記号をエンコードする必要があるためです。

callback.rb
class LinebotController < ApplicationController
  require 'line/bot'
  require 'cgi'

  protect_from_forgery :except => [:callback]

  def client
    @client ||= Line::Bot::Client.new { |config|
      config.channel_secret = ENV["LINE_CHANNEL_SECRET"]
      config.channel_token = ENV["LINE_CHANNEL_TOKEN"]
    }
  end

  def callback
    body = request.body.read

    signature = request.env['HTTP_X_LINE_SIGNATURE']
    unless client.validate_signature(body, signature)
      head :bad_request
    end

    events = client.parse_events_from(body)

    events.each { |event|
      case event
      when Line::Bot::Event::Message
        case event.type
        when Line::Bot::Event::MessageType::Text
          if event.message['text'].include?('$')
            formula = CGI.escape(event.message['text'].match(/(?<=\$)(.*)(?=\$)/).to_s())
            message = {
              type: "image",
              originalContentUrl: "https://chart.apis.google.com/chart?cht=tx&chl=#{formula}",
              previewImageUrl: "https://chart.apis.google.com/chart?cht=tx&chl=#{formula}"
            }
            client.reply_message(event['replyToken'], message)
          end
        end
      end
    }

    head :ok
  end
end
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1