Skip to content

Anti Spam Discord Bot in C# using Discord.Net and IPQualityScore

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

Hello, welcome to a new C# tutorial!.

So I was going through our discord earlier (which you should join if you haven’t, here is the link),

when I came across a spam message!.

So after deleting the spam a guy on our discord said, I wish discord had an AI feature to auto-delete spam messages.

So I decided to make a tutorial for it.

We will be building a discoed bot that will be able to detect when someone sends a link, send it to a security service that will check whether if the link is safe or not, and if so delete the message containing the link.

We will be using discord .net which is a C# warapper for discord API, we have lots to do so let’s get started.

 

Setting Up The Project

 

  1. First, create a new C# Console App.
  2. in the Solution Explorer, find the “Dependencies” element under your bot’s project
  3. Right-click on “Dependencies”, and select “Manage NuGet packages”
  4. In the “Browse” tab, search for Discord.Net
  5. Install the Discord.Net package

 

Follow the steps in the Discord.Net documentation to create a new bot app and acquire a token.

https://docs.stillu.cc/guides/getting_started/first-bot.html

Go to IPQualityScore Create an account and acquire your private key.

 

Adding a Config File for our Keys

 

Create a new C# class and add your keys to it like so:

 public static class EnvVariables
    {
        public static string discordBotToekn = "YOUR_DISCORD_TOKEN";
        public static string ipScoreKey = "YOUR_IP_SCORE_KEY";

    }

 

Creating JSON Response Classes

 

We need a couple of C# classes to hold the JSON response from IPQualityScore

 

    public class DomainAge
    {
        public string human { get; set; }
        public int timestamp { get; set; }
        public DateTime iso { get; set; }
    }
 public class Root
    {
        public string message { get; set; }
        public bool success { get; set; }
        public bool @unsafe { get; set; }
        public string domain { get; set; }
        public string server { get; set; }
        public string content_type { get; set; }
        public int status_code { get; set; }
        public int page_size { get; set; }
        public int domain_rank { get; set; }
        public bool dns_valid { get; set; }
        public bool parking { get; set; }
        public bool spamming { get; set; }
        public bool malware { get; set; }
        public bool phishing { get; set; }
        public bool suspicious { get; set; }
        public bool adult { get; set; }
        public int risk_score { get; set; }
        public string category { get; set; }
        public DomainAge domain_age { get; set; }
        public string request_id { get; set; }
    }

 

Programming our Bot

First, we need to create a config object for our discord socket client, and set the message cache size to 200, so that our bot can cache discord messages.

Then we will log in and start our bot. Also, subscribe to the MessageRecieved event.

First, we need to prepare our URL and our post request values, after that make the post request and parse the JSON response and check the URL score, if the URL is not safe then we will delete the message.

using System;
using Discord;
using Discord.WebSocket;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Net.Http;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace DicordAntiSpamBot
{
    class Program
    {
        private static DiscordSocketClient client;
        static async Task Main(string[] args)
        {
            //crete a new config object and set the message cache size to 200
            var config = new DiscordSocketConfig { MessageCacheSize = 200 };
            //init our discord client with our config obj
            client = new DiscordSocketClient(config);
            //subscribe to the log event
            client.Log += Log;
            //login using our token
            await client.LoginAsync(TokenType.Bot, EnvVariables.discordBotToekn);
            //start the bot
            await client.StartAsync();
            //subscribe to the MessageReceived event
            client.MessageReceived += MessageReceived;

            //keep the app running
            await Task.Delay(-1);
        }

        private static async Task MessageReceived(SocketMessage arg)
        {
            //log our message into the console
            Console.WriteLine($"{arg.Content}");
            //if the message received was sent by the bot then ignore it
            if (arg.Author.Id == client.CurrentUser.Id)
                return;

            //just a test ping command
            if (arg.Content == "Ping")
            {
                await arg.Channel.SendMessageAsync("Pong");
                return;
            }

            //create a new regex that will search for a URL pattern in our messages
            var myRegex = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            //create a new http client to make a post request
            HttpClient httpClient = new HttpClient();
            //prepare the post request values
            var postReqvalues = new Dictionary<string, string> {
                {"stricktness","0" },
                {"fast","true" }
            };
            // create a URL encoded content from our values
            var content = new FormUrlEncodedContent(postReqvalues);


            //for each URL we found in our message 
            foreach (Match match in myRegex.Matches(arg.Content))
            {
                //fix the string format, since we are sending it as an embeded variable in our URL
                string url = match.Value.Replace(":","%3A").Replace("/","%2F");
                //make a post request to IPQualityScore
                HttpResponseMessage response = await httpClient.PostAsync("https://ipqualityscore.com/api/json/url/"+EnvVariables.ipScoreKey+"/" + url, content);
                //read the response as a string
                string responseString = await response.Content.ReadAsStringAsync();
                //parse the response into a C# object
                Root parsedResponse = JsonConvert.DeserializeObject<Root>(responseString);
                //check if the link is safe
                if (parsedResponse.@unsafe == true||parsedResponse.suspicious||parsedResponse.risk_score<50)
                {
                    //if it's not then :
                    //shame the sender
                    await arg.Channel.SendMessageAsync($"Spam Found !{arg.Author.Username} bad boi!");
                    //delete the message
                    await arg.DeleteAsync();
                    //no need to go through the rest of the urls if one of them is unsafe
                    break;
                }
                //log the response
                Console.WriteLine(responseString);
            }

        }

        private static Task Log(LogMessage arg)
        {

            Console.WriteLine(arg.ToString());
            return Task.CompletedTask;
        }
    }

}

 

 

 

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide