About a month ago, I started a new project which really piqued my interest. It is rare for me to find a passion project where I don’t want to do anything but work on it. But this one in particular really had me going and for 3 weeks, I worked on a project that my friend had originally created. This project was called StyroBotPy. StyroBotPy was created by a friend of mine in C# to be a Discord bot. This bot had various functionality such as being able to talk to cleverbot in Discord chat, playing music in the voice channels, getting quotes from a text channel and more. Unfortunately for him, something in the C# API for Discord broke the night before his project was due and he re-wrote it in Python. This was all before Discord even had an official API (which it does now).
This project interested me because it was a neat idea; and since I use Discord, I thought it could be cool to mess around with this on my own. So with his permission, I became a contributor on his project and came up with a grand plan for changing it. Now, the original project was nicely structured and setup to be fairly modular, but when it was hastily re-written in python, it was messy and basically a god class. It was quite the mess and the interwovenness of the code plus the implicit nature of python made it somewhat difficult to decipher at first. But this only made it more fun to work on. And so I set off on my journey to refactor and update his Discord bot.
For about a week, I was playing around with an idea of turning the entire thing to a Plugin based architecture. This meant making it extremely modular and super easy to extend in the future. Add on top of this some of python’s quirks and you’ve got a pretty great system. The only problem was that the project in its current form wouldn’t work well with this. It was mostly because the repo and the code wasn’t really setup for multiple files. If you’ve ever done python development with more than 1 file, you will understand how it can be a problem when your project isn’t properly setup. I was also working in linux and he created the python in windows. Add on top of this the fact that there was no automation like make/batch. It was a nightmare. So I ended up spending a few days restructuring the repo and creating some automation that would allow me to have a decent workflow. I tried my best to make sure it still ran on windows, but I honestly still have no idea if those batch scripts work. I kind of abandoned the windows specific stuff to focus my efforts on the python itself.
Once everything was setup, I began experimenting with the Plugin architecture and after a bit of researching, I found a solution that I liked a lot. I am using a python module called yapsy which is short for Yet Another Plugin SYstem. It allows me to very easily create plugins and load them dynamically at runtime with almost no effort at all. And on top of this, it is built on Python’s standard library meaning it has no dependencies of its own, making it light weight and simple. Once I had found this, I had what I wanted working in minutes. Then over the course of roughly 2 weeks, I slowly tweaked my abstract Plugin class to hold the functionality I needed for the system. The result can be seen below.
__metaclass__ = abc.ABCMeta
# Initializes the plugin
# @param bot A reference to the bot's instance
async def initialize(self, bot): pass
# Gets the list of commands and their descriptions that this plugin can do
# Format: !<commandname> <parameters> - <description>
# example: !savefile <url> <name> - Saves the file at <url> to a local file named <name>
# @return An array of strings formatted like the example above
def getCommands(self): pass
# Checks if this plugin handles the command provided by the user
# @return True if you can handle this command, False otherwise
def checkForCommand(self, command): pass
# Executes the chat command
# @param server The discord server this command was executed in
# @param channel The discord channel this command was executed in
# @param author The user which executed this command
# @param command The command to execute
# @param parameters Any extra parameters that followed the command
async def executeCommand(self, server, channel, author, command, parameters): pass
# Whether or not this plugin wants to read messages completely
# Override this if you want your plugin to read messages completely for something
# @return False if you don't want to read messages, True otherwise
# Allows the plugin to read the full message and do whatever they want with it
# It is not recommend to handle commands in this function.
# @param message The message as given by discord. See discord documentation on the message class
async def readMessage(self, message): pass
# Shutdowns the plugin
async def shutdown(self): pass
The comments explain everything fairly clearly, but the basic idea is that a Plugin has all the functions it needs to do things based off of input from Discord. With this simple but effective Plugin system created, I began refactoring the codebase into plugins.
It took a little bit of time, but I eventually implemented 5 different plugins. They each show off different things you can do with the system, but they also have useful functions from the perspective of a bot. I will talk about each one individually so that I can talk about some of the interesting things about them and any challenges I faced.
To start off, I will begin with the Cleverbot plugin. This was one of my favorite parts about the bot before I started working on it and I knew that implementing it was a top priority. Luckily for me, there was a python module for cleverbot and it was something that took less than 5 minutes to implement. The idea for this plugin is that with a specific command, you could talk with cleverbot and the bot would post the response to the channel you sent the command in. The result was spectacular and you can see an example conversation below.
The next plugin I would like to show is the Quotes plugin. This plugin was designed based off some functionality the original C# bot had which would let you say messages from a specific text channel. The intent is that you create a channel for memorable quotes and then at any time you can have the bot read a random quote from this channel. When converting the bot to python, this feature got lost and I wanted to make sure it lived on. But making sure it lived on wasn’t enough, I also wanted it to be more flexible. The previous implementation had hard-coded channels and that made it so only 1 channel could be used for quotes and you couldn’t change it without modifying the python script. I wanted to make this more modular with a server side solution so that even if the bot was run on a different machine or by a different person in the same server, it would have the same settings. I eventually came up with the idea of storing this information in a text channel. This solved the problem, but it isn’t perfect. I will talk more about its shortcomings later in this post. The result of all of this was that the plugin was able to give you quotes from a channel (you could change which at any time) and it would remember this information across sessions and computers for that server. You can also see it in action below!
The next plugin I want to talk about was also a feature of the original bot. This is the music plugin. This plugin allows the user to download and play music playlists in the voice channels in Discord. You just simply tell the bot to enter a specific voice channel, queue up the songs and play. These songs are local to the machine the bot is running on, but you can always download songs through one of the commands. This would download the youtube video you specified and save it as a mp3 which would then be used for playback later. This was originally used to create playlists in the voice channel so that you could listen to Mom’s Spaghetti and other great songs while talking with friends or playing games with them. Below you can see the bot in the voice channel General playing the song Starfall which I downloaded and queued to play.
The second to last plugin I want to talk about is a new feature to the bot and was created to help show how the bot is capable of doing just about anything, such as dice rolls. This plugin lets you do typical things like roll a dice of any size or flip a coin. The result is obviously said in the chat and this could be used for things like your weekly D&D with friends or perhaps even to settle disputes such as who is the best high/low roller. Another small feature is the ability to call a coin flip before it happens. If two users do this, the coin is then flipped and it will tell you who won/lost. It is possible for everyone to win or lose depending on what the two of you called before (you don’t have to call different things).
The final plugin I created is also a new feature to the bot. This plugin handles chat moderation based off criteria defined by the server admins, specifically based off of banned words. The bot stores this information in a text channel, just like with the Quotes plugin so that it persists between sessions and machines. It also supports other settings such as how many warnings a user gets and whether to kick or ban them if they have too many infractions. The plugin is also fairly good at scrubbing through text to find words that users try to hide. It is capable of stripping out all the markdown that Discord supports, as well as other common things such as hyphens to better determine when a banned word is used. It is by no means perfect, but this plugin tries to show how one might create a plugin which doesn’t run off of commands but parses messages directly to do an action, such as moderating chat. As you can see in the images below, I have a message with a bunch of markdown which still finds the banned word (in this case, “poop”) and warns me. The plugin is also nice enough to tell you when you’ve reached your last warning before it takes action.
The Server Side Problem
Earlier I mentioned that my current server side solution has problems and isn’t very good. What I mean by this is that for starters there is no established way of doing what I want so its kind of “hacked” together. It is also not supported as a feature in the bot itself, but is instead done by the plugin itself which has drawbacks. Not to mention that in its current form, the bot doesn’t handle multiple servers very well at all.
While there may only be 5 plugins currently implemented, I know I have a few more ideas that given the time I would love to add. Things such as an improved High Roller plugin which allows for a loot system similar to World of Warcraft’s Need/Greed system and making the roll use dice notation so you can specify 2d6 or something like that to roll multiple dice like you would need in a lot of roleplaying board games. I also have other ideas such as improving the help command and adding a system to help disambiguate between commands with the same name. I would also like to create a better, more in-depth server side solution for storing settings that plugins can easily use through the bot instead of having to “hack” it. I could go on and on, but I think I made my point.
Every time I think about this project, I get excited about the potential features and all of the cool things I could do to improve the system. During the 3-4 weeks I was developing this constantly, I learned a lot more about python, but more importantly I had fun. I had the opportunity to explore something I’ve never done before and looking back, I never expected to like it so much. My hopes are definitely to continue working on this to see where I can take it and perhaps it will even become an interesting portfolio piece down the road. I also think that there is a lot of room for improvement. While building this bot, I experimented with a lot of structural things and the further I progressed, the less I implemented due to time constraints. My hopes are to return to this project in the near future to continue developing it on the side.
Check this project out on Github!