Sunday, July 30, 2017

Writing a Discord Bot For Literally Anything

I love Discord. It is not only great for gaming chat, but it's awesome for chat in general, supporting arbitrary numbers of people, channels, and voice channels. It's really remarkable how much Discord can do. Discord, being the awesome application it is, exposes an API for you to develop bots with. These bots can do literally anything a regular user can, so we can make some great things with it. So, why don't we make all the things with it? Let's make a modular bot that has hot swappable components and can span multiple hosts monitoring multiple things. Sounds hard right? It's probably not, but as I'm writing this I haven't touched any code whatsoever.

So the first thing we'll need to write is our actual bot. This will be the thing connected to our server. We're going to give the bits and pieces the opportunity to connect via a websocket connection. They'll announce which piece they are and, if you've already okayed it, they'll be allowed to send and receive messages and do things. Exciting right? So let's get to it!

I went ahead and just copied the example code on the frontpage of https://discord.js.org to get it to start working. I then created the application in the Discord Application Page, calculated its permissions with this tool and authorized it with the generated link. After that, my bot showed up and the ping/pong functionality worked perfectly!

Now let's work on some architecture stuff. We'll need to include Socket.io and NeDB. The former is to communicate with the modules I'll call "transponders" from here on out, and the latter is to store the names of transponders we will accept. This will all be controlled via the Discord app itself.

So, to start, I'll create the websocket protocol we'll be using. It consists of four custom events: declare (sent from a transponder to say what it is), not_allowed (sent from the bot to say it wasn't allowed), ready (sent from the bot to say it was allowed), and message (sent in either direction to relay commands and responses).

The bot itself only has three commands:

  • allow <name> - allows a transponder by the name given to connect and exchange messages
  • remove <name> - disallows a transponder
  • assign <name> - any message the named transponder sends will be added to the channel that this command is run on.
I've also written a sample transponder that just replies "lemons are good" any time you send it something. Check it out, the code should be simple enough to understand. Here's the GitHub repo.

Also, on a meta note, I'll be getting back to some more of the hardware related stuff next month or so when I move back to where all of that stuff is. I had to put all of my projects on hold over the summer but now that I'm going back to school, I should be able to resume them. So either August or September, I'll be making some more hardware stuff, so look for that.

No comments:

Post a Comment