Skip to content

Instantly share code, notes, and snippets.

@mattantonelli
Created December 16, 2020 18:33
Show Gist options
  • Save mattantonelli/d9c311abbf2400387480488e3853dd1f to your computer and use it in GitHub Desktop.
Save mattantonelli/d9c311abbf2400387480488e3853dd1f to your computer and use it in GitHub Desktop.
Discord interactions webhook implementation for Ruby on Rails

app/controllers/discord_controller.rb

class DiscordController < ApplicationController
  skip_before_action :verify_authenticity_token

  def interactions
    # Request signature verification
    begin
      verify_request!
    rescue Ed25519::VerifyError
      return head :unauthorized
    end

    body = JSON.parse(request.body.read)

    if body['type'] == 1
      # Respond to Discord PING request
      render json: { type: 1 }
    else
      # Respond to /commands
      response = { type: 4, data: { content: 'This is a response' } }
      render json: response
    end
  end

  private
  def verify_request!
    signature = request.headers['X-Signature-Ed25519']
    timestamp = request.headers['X-Signature-Timestamp']
    verify_key.verify([signature].pack('H*'), "#{timestamp}#{request.raw_post}")
  end

  def verify_key
    Ed25519::VerifyKey.new([MY_PUBLIC_KEY].pack('H*')).freeze
  end
end

config/routes.rb

post 'discord/interactions'

Gemfile

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