Skip to content

Instantly share code, notes, and snippets.

@dammer
Last active February 18, 2021 20:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dammer/fa0e0aa388bc75962ea6f59a2dc75959 to your computer and use it in GitHub Desktop.
Save dammer/fa0e0aa388bc75962ea6f59a2dc75959 to your computer and use it in GitHub Desktop.
Using Tourmaline in Lucky
# Somewhere in src/handlers ...
require "tourmaline"
module Tourmaline
# Sample bot
class EchoBot < Tourmaline::Client
@[Command("echo")]
def echo_command(ctx)
ctx.message.reply(ctx.text)
end
end
# Tourmaline Handler
class TMBotHandler
include HTTP::Handler
property bot : Tourmaline::Client
property path : String
# Handle requests with given path
def initialize(path = nil)
@bot = EchoBot.new(bot_token: ENV["BOT_TOKEN"])
@path = path || "/webhook/#{bot.bot.username}"
# See original Kemal handler for details
# check_config if Lucky::Env.production?
end
# Just match path and method
def only_match?(context)
context.request.path == @path && context.request.method == "POST"
end
def call(context)
return call_next(context) unless only_match?(context)
if body = context.request.body
# Extract data from Tgm
update = Tourmaline::Update.from_json(body)
# Send update to your bot
@bot.handle_update(update)
end
end
end
end
@dammer
Copy link
Author

dammer commented Feb 18, 2021

See details in https://luckyframework.org/guides/http-and-routing/http-handlers

src/app_server.cr

class App < Lucky::BaseAppServer
  def middleware
    [
      Lucky::HttpMethodOverrideHandler.new,
      Lucky::LogHandler.new,
      Tourmaline::TMBotHandler,  # Add this line
      Lucky::ErrorHandler.new(action: Errors::Show),
      Lucky::RouteHandler.new,
      Lucky::StaticFileHandler.new("./public", false),
      Lucky::RouteNotFoundHandler.new,
    ]
  end
end

Thats all.

@watzon
Copy link

watzon commented Feb 18, 2021

This is pretty awesome. I like that you managed to integrate Tourmaline with Lucky. I'll definitely be hanging on to this and adding it to the documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment