DEV Community

Ambareesha AV
Ambareesha AV

Posted on

Send a msg to Discord channel through webhook in Elixir

Webhooks

Webhooks are a form of HTTP-based callbacks that are triggered by specific events on a Web Platform. A callback refers to a small code snippet related to a Web Application. Whenever any triggering event occurs on the originating Web Platform, the Webhooks identifies it, collects the data, and sends it to the URL you specified as an HTTP request.

A Webhook acts as a reverse API and is used for calling another application to receive data. You can connect a Webhooks with another application to send data directly to your system as soon as there is a change in it. This makes the process very convenient and efficient for providers and users.

Using Webhooks allows Web Applications to automate their communication. Unlike traditional systems that involved one system polling other systems for some data, Webhooks enables you to automatically push data into the other system whenever some event occurs. This eliminates the need for constant monitoring by the subject.

The following features have made Webhooks popular in the market:

  • Automation: Webhooks enable many types of automation powered by other services and also allow you to manually send clear messages. These features provide various use cases like posting updates, logging, posting custom messages for aesthetic purposes, etc.
  • Customization: You can associate a unique name and image with each of your Webhooks. Moreover, each message sent by these Webhooks can also be unique. You can have several different Webhooks on different channels and use them according to your need.
  • Low Cost: All you need to work with Webhooks is its URL and a Website to which the Webhooks will be connected. Moreover, unlike a regular bot, Webhooks are hosted on Discord. This often saves you the hassle of making a financial investment to use them.

Discord's Webhooks

Discord's built in Webhooks function as an easy way to get automated messages and data updates sent to a text channel in your server.

Think of them as one of those fancy pneumatic tube things you used to love sending money into at a bank and watch disappear, but instead of never seeing your money again, you're actually sending messages into Discord from another platform.

By creating a webhook endpoint in your server, you'll generate a Webhook URL that you can drop into a number of different other services to link the two.

While everyone absolutely loves pneumatic tubes (100% true), it's important to note that webhooks require another website to use (though programming-inclined users can make their own tube schoomper themselves).

MAKING A WEBHOOK
  1. Open your Server Settings and head into the Integrations tab:
  2. Click the "Create Webhook" button to create a new webhook!

Settings

You'll have a few options here. You can:

  • Edit the avatar: By clicking the avatar next to the Name in the top left
  • Choose what channel the Webhook posts to: By selecting the desired text channel in the dropdown menu.
  • Name your Webhook: Good for distinguishing multiple webhooks for multiple different services.

You now have your own handy URL / pneumatic tube schoomp-er that you can link to more websites to receive messages from.

webhook editing screen

Now copy the URL

Elixir Part

Now think where you wanted to trigger event notification,
To simplify I send a notification message whenever someone visits my web page

Implement The Code

We will create a new Phoenix project called "webhook" we'll use mix commands to generate boiler plate project
run this command in your terminal mix phx.new webhook --install
open your generated project in IDE,
we need HTTP Client to send a message to Discord, so I'm using HTTPoison add {:httpoison, "~> 1.8"} in mix.exs then run mix deps.get

open page_controller.ex add this snippet

def send_webhook(user, msg) do
    case System.get_env("DISCORD_CHANNEL") do
      nil ->
        IO.puts("DISCORD_CHANNEL webhook is not loaded from .env")
        nil

      url ->
        headers = [{"Content-type", "application/json"}]
        body = Jason.encode!(%{content: "this user: #{user} has visited your page: \n#{msg}"})
        HTTPoison.post(url, body, headers) # actual magic happens on this line of code
    end
  end
Enter fullscreen mode Exit fullscreen mode

for security reasons I stored above copied Discord webhook(url) in .env file, open or create .env file in your project root folder add export DISCORD_CHANNEL=URL then run source .env command in your terminal
The above function will send a message to given URL in .env
place this function send_webhook(user, msg) somewhere in index/2 block now run mix phx.server and visit localhost:4000 it will send message to your Discord channel
you can use this function wherever you wanted to trigger a event notification and modify body variable according your requirements, body accepts only JSON format, read more on Discord

this is how we build software in Functionary labs

Top comments (0)