DEV Community

John Costanzo
John Costanzo

Posted on

Building Serverless Function for Slack Slash Command

At work some of the side conversations we have is about watching Anime. We talk about what we are watching at the current time and sometimes people bring up an anime that you have never heard of. So typically I or a co-worker would send a slack message with a link to see some information about what the anime is about.

So I wanted to get into learning about serverless functions and I am the type of person that needs a goal to help keep me motivated to learn. So I decided to build something that I could setup in slack to allow someone to type something like, /anime One Piece and when I would hit enter we would get something like the following as a result:

Slack
A sample of what the output will look like in slack

Markdown
A sample of what the output will look like in markdown

Looking at the markdown version really makes me excited for the day that Slack opens their eyes and support full markdown. If you are interested in looking at the full code for this, here is the Github link to it. Next I want to break down the how I built some of this. The code is by no means fully ready as there are improvements I want to make, but I wanted to write this now before getting into make more changes.

Main Dependencies

Netlify Functions

This library made it real easy to get started with setting up the netlify function. The library gives you the handlers you need for when the function is called. In the past when I wrote an app like this, I set up an express server to build the route. Using this library I was able to create a ts file and just put the following to get started

import { Handler, HandlerEvent } from '@netlify/functions';

const handler: Handler = async (event: HandlerEvent) => {
   ...

   return {
     statusCode: 200,
     body: JSON.stringify({message: 'Hello'});
   }
});
Enter fullscreen mode Exit fullscreen mode

With the help of Netlify CLI I took this code and I ran netlify dev and I was able to go into Postman and call this API.

Node Fetch

So since this is not running in a browser, we do not have access to use window fetch. So node fetch will give us a way to use fetch to get the data we need for the response.

Getting Data

So before I got too far, I needed to find a way to lookup the anime data that a person would be searching for. So the 2 I found that had API access, was Anilist and Anime News Network. Anilist API uses graphql and Anime News Network which uses rest with xml response.

I did not want to deal with xml so I went with graphql as that was going to be way more flexible and easy for me.

Finish Up

I would be interesting to know if people would find something like this useful or not. Take a look at the code and let me know what you think. You can view the code at:

GitHub logo jrock2004 / anime-slackbot

This is a slack bot that will go out and get you information on your favorite anime

Top comments (0)