Create a Discord bot in C# and .NET - Part 3
This is part 3 in the series of articles about creating a Discord bot in C# and .NET. In part 1 of the series, we completed our project setup in Visual Studio and created all the necessary information in the Discord developer portal. In part 2, we created a bot using the Discord.NET library and added some basic functionality.
🧑🏻💻 Source code: https://github.com/adamstirtan/DiscordBotTutorial
🧠 Part 1: https://blog.adamstirtan.net/2023/10/create-discord-bot-in-c-and-net-part-1.html
🧠 Part 2: https://blog.adamstirtan.net/2023/10/create-discord-bot-in-c-and-net-part-2.html
Implementing Logging using the ILogger interface
As we build out new features debugging will become more involving. By implementing logging we'll be able to print to the terminal when something happens and we'll have a much better idea of what the is doing.
Add NuGet package Microsoft.Extensions.Logging.Console
dotnet add package Microsoft.Extensions.Logging.Console
Update the ServiceCollection in Program.cs
Any class that wants to log information will use dependency injection to resolve an instance of ILogger for itself. For example, the Bot class will have an instance variable of type ILogger<Bot> which is received in its constructor. Update the ServiceCollection we created in part 2 as follows:
In this code, we've added lines 2-6 which registers our logger and sets console logging as the only provider.
Finally, remove the Console.WriteLine calls we've made. Let's move the logging into the Bot class instead using the ILogger interface.
Changes to Bot.cs
Adding logging to the bot requires minimal changes. We'll create an ILogger<Bot> instance variable and handle it in the constructor. Next, when the bot starts, stops and receives a message we'll log these events to the console. Here's what the changed class should look like:
With logging implemented this way, you should now have a very intuitive way to debug your own commands. If console logging isn't sufficient, you can use many other logging providers. Some that might be useful to your bot are:
Implementing UrbanDictionary API command
Let's add something fun to our bot. This new command will allow a user to type !ud <phrase> and we'll look for that phrase on the UrbanDictionary.com API using HttpClient. The definition will be written back to the channel.
Kind of a burn, right? |
This trigger is the first one with some complexity to it. In it, making an HTTP GET request to UrbanDictionary.com, converting the result to JSON and then parsing out the phrase's definition. With this pattern, you can make calls to just about any RESTful API to make more commands for your server.
Try it out yourself
Start up your bot and once its in your server use the !ud command to search the UrbanDictionary API for something hilarious.
Don't forget the source code is available here if you get stuck: https://github.com/adamstirtan/DiscordBotTutorial/tree/master/Part%203/DiscordBot
Comments
Post a Comment