Create a Discord Anti Spam Bot Using C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello youtube this is mo from tutorials.eu and welcome to a new shop tutorial so i was going through our discord earlier 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 that auto deletes spam messages so i decided to make a tutorial on it we will be building a discord bot that will be able to detect when someone sends a link then it will extract the link send it to a security service that will check whether the link is safe or not and if so delete the message containing the link we will be using discord.net which is a c2r wrapper for discord api we have lots to do so let's get started so i'll be creating a new console application project and i'm gonna call it discord anti-spam bot and i'm going to target.net 5 and the first thing i'm going to do is install the nougat package for discord.net from the browse tab search for discord and it should be the first one on top select your project and click install accept both messages and now discord.net is installed all right cool so before we start with coding we need to create a discord bot account so go to discord slash developer slash applications and create a new application i'm just gonna name it untie bambot click on create go to the bot tab and click on add a bot now since both cannot accept invite links we must invite them through the oauth2 flow i'm going to select the scope of this application as a bot and then for the bot permissions i'm going to make it an admin then copy the link open it in your browser then select the server you want to add this bot to i already created a server called spam free server which i'm going to use to test this bot click continue and then authorize as an admin once you see this message then it's all set now if you look at discord you can see my spam free server and you can see the bot that we created as a member of course it's offline it will be online once we run our c application all right now back to our console application first i need to import a few libraries the first one is discord and discord.websocket then i need to create a discord socket client that will connect to discord so private static discord socket client and i'm gonna call it client now since i'll be running a lot of async tasks so i need to mark the main method as an async method and of course it need to return a task and for that i need to import the system dot threading the task namespace so before i initialize my client object i need to create a configuration object and set a number for the message cache size so that our bot would be able to read messages of this code so first i'm going to create a config object discord socket config and i'm gonna set the message cache size to something like 200 which should be enough then i'm going to use this config object to initialize my client object and i'm going to pass it the config we just created now to keep track of our bot actions we need we need a method to log our data luckily our discord socket client already contains an event called log which we can subscribe to so i'm going to create my own log method and i'll let visual studio generate that for me so as you can see our log method follows the same signature of our log event which returns a task and takes a log message as an argument so instead of throwing an exception directly i'm going to cw the log message we got and i'm gonna convert it to a string which will contain the message and the timestamp of the log message and then at the end i'm gonna return task dot completed task to indicate that this task is now finished so now i need to log in using my socket client and i'm going to use login async and it takes an enum for the token type which is of type bot and i need to pass my token as a string over here and this token we can get from the discord developer portal if we go to bot we can see that we can copy the token from here now be careful whoever have this token will be able to do actions on behalf of your bot so you have to keep this one very safe and never share it with anybody so to keep our code clean i'm gonna add a new static class and i'm gonna call it env short for environment variables and i'm gonna make it public static and for starters it's gonna have a public static string which will be my discord bot token now of course i'm not gonna reveal my token but you need to add your own token here so now back to our login async method i'm gonna pass it static string that i just created in my environment variables class and now we are ready to start our bot so i'm gonna call start async from our client object now the thing is i don't want this bonus application to close once it's done so after we start our bot will close automatically since i don't have a pose over here so i'm going to delay the whole main task by calling task to delay and if i pass it -1 it means it will be delayed indefinitely which will result in my bot running until i close it now let's test it out you can see that our bot is now connecting and now it's ready and these all the log messages we are getting from our log event over here now if we check our discord we will see that our bot is now online all right so so far we created a config object then we pass it to our client which is of type discord socket client then we subscribe to the log event and then we start our bot now we need to find a way to get notified whenever a message is sent in our discord server so for that i'll need to subscribe to a different event called message received which will be called whenever a message is basically received by our bot i'm gonna call my method message received as well and i'll let visuals to generate that for me as well for now whenever i receive a message i'm just gonna print its content into the console after that i'm just going to return task dot completed all right let's give it a try now my bot is connected and if i go to discord and i send any message we can see that now our messages are being logged into our console now let's modify our bot to make it reply to us so whenever we receive a message we just want to write something back so using our socket message over here this object contains a channel object which is the source or the channel that the message was received from and to any channel i can also send a message and my message will be something like what you want bro and since this is an async method i'm gonna have to await this task now i can actually get rid of this line since now i am already awaiting a task over here so let's run it and once it's connected i'm gonna go to discord again let me put that over here so you can see it i'm gonna type hey again and now we can see that our bot is actually spamming the chat and there is a reason for that because this event will get called whenever a message is received regardless of who sent this message so once our bot actually replies to our message that will also trigger another message received event to prevent this we need to check the sender or the author of this message that we have over here so if the message that we received if it's author id equals to our client current user.id we simply want to return now don't judge me this is the only scenario where i don't put brackets for an if statement is when i'm simply just returning or exiting a method so this way whenever a message is received we're gonna check the id of the author if this message is sent by the bot we're gonna return otherwise i'm gonna print this message over here so let's give it another try now if i say hey again the bot will only respond once and of course everything is now being logged into our console as well of course we can play with it a bit so let's say if the content of our message was ping i'm going to send pong and return so again let's give it a try so now if i say hey nothing will happen but if i say pink the bot will reply with punk now don't use this as a way to program your bot commands if you want to have some sort of commands in your bot since the scored api contains a very cool command service so use that instead all right so now that our bot can actually receive messages through the message received event we can now have a deeper look at the messages that we are actually receiving right because at the end of the day our task is to take these messages and then look if they contain any link basically or any url and then check if this link is actually spam or not and in that case we'll have to delete that message so our next task is to actually find a way to extract the links from any paragraph and for that we are going to use regular expressions or rejects so first i'm going to create a regex object i'm going to call it my regex and it will be a new regex and of course i need to add the regular expression namespace which exists in system.txt dot regular expressions now we need to pass a few things to our rejects constructor the first thing is our pattern which is going to present any link pattern basically so i found this trigger expression on stack overflow which i'm going to use and it's pretty simple it will basically look for a link between any set of words that's why we have the slash b so it will look for any string that starts with https and the s here is optional that's why we have the question mark followed by a column double slash or double forward slash or wwe dot followed by any number of non-white space characters that's why we have the sphere and plus indicates that it's one or more non-white space characters of course this part of the bot can't be improved which i'll leave it to you because i've seen some links that starts with something other than http or https or www next i'm gonna pass my redex settings let's say so the first projects option is going to be compiled so that our objects will be actually part of our assembly which will increase the speed of our application because keep in mind that we will be doing a lot of stuff within one message received event and there could be like tens per second if we have a very active discord server and then i'm going to add another rejects option to ignore the case which means it doesn't matter if our link contains either capital or smart characters now we could use rejects.match like so and then of course we can give it the pattern directly and the our input message but this will but this will give us a boolean that says okay this message contains our pattern but that's not what we want to do we actually want to store our strings or our links in an array or a list so that we can pass them to servers that will check if they are malicious or not so enough for each loop i will go through each match in my in my regex object so i'm gonna use the matches and here we can see that match will return one map but matches will return a match collection since a message could actually contain more than one link so we want our bot to be smart and i'll pass it the content of the message that we actually receive so just to avoid a typecast i'm gonna change that to a match and for now i just want to let the bot send the link back to the chat so await args dot channel dot send message async and i'm gonna pass it the match dot value and let me just add a string over here that says link found all right let's try it out let's wait for our bot to connect and once it's ready let's go back to discord and let's say hey of course nothing will happen now let's say a www.google.com and the bot will reply with link found followed by the link i missed an e but it doesn't really matter of course a spam message could be of the following form something like get free discord nitro at http s and let's say this code because usually they mispronounce it because they can't have the same domain name dot net slash three nitro and let's say get it now now if we send this message we will only get our link because of the regular expression that we used all right so now that our link extraction is working perfectly all is left is to send it to the service i told you about to check whether the link is malicious or not quick pause in this video you'll learn something about c sharp and if you want to learn everything there is to know that you need for the fundamentals and to become a real c sharp developer then definitely check out my c c-sharp master class in which you're going to learn all of the things you need to know about c-sharp so you're going to learn how to do the basics how to use object-oriented programming how to use wpf in order to create your own user interfaces how to use databases how to use link how to create your own games using unity and a lot more so if you want to become a real c sharp developer definitely check out the link in the description below so to find out whether a link is malicious or not i'm going to use this service called ip quality and they basically have an api where you send it a link and it will give you a score for it and a bunch of other information like the category of the website it's ip is it spam does it contain malicious files or xe files etc of course you could use any other service that you like for example google safe browsing but for the sake of this tutorial this service is quite good enough so first you need to register or log in if you already have an account i'm going to log into mine once you are logged in it will redirect you to the dashboard and they offer a bunch of other services as well like an email verification api a device fingerprint tracking service phone number validation api to check whether a number is actually real or is it a google number and this is the service that i'm more interested in which is called malicious url scanner api so if you go to the documentation we can see that this api provide a phishing detection malicious scanning park domain detection filter email spamming domains abusive domains etc and here we can see an example on how to use this api in php of course we're going to do the same but in c-sharp so when we call this api we'll need to give it a key and a url for example google.com and we'll need to pass it a strictness value or a strictness variable and this determines how strict should the scoring of this url be so if you want maximum security you should put here says between 0 and 2 so you should pass it to if you want your bot to be very strict when it comes to evaluating a url and down here you can see an example of a successful response in json so here we have a variable that says is it unsafe which is a boolean and safe is false it means the the link is safe and it will give you a bunch of other information as we said the domain the ip address the server the page size and then other values for other scores is it a parking url is it a spamming url is it does it contain malware is the phishing url etc for example if you want your bot to also block any adult content as well so that's also an option so maybe the link is not malicious it's a plus 18 website so maybe you want to have a kids friendly discord server so you could use this service to actually prevent anybody from sending these kinds of websites the only information that we are interested in is this one which determines whether the link is safe or not but we will be getting all these data so that in case you want to actually extend on the spot yourself it will be easier for you so here you can see an example on how to call this api so this part is actually let me zoom in a bit so this part is the actual api url and here we chose that we want to use json instead of xml for example as for our response and then forward slash url followed by our key which we can get from the dashboard so this is going to be our key and then followed by our website now since we are actually passing a url as a variable as an embedded variable in a url we need to replace the column with percentage 3a and the slash with percentage to f and that's why you have two of them because we have column forward flash forward slash so this this is a thing that we'll have to pay attention to when we are programming this part of course this url is going to be the url that we extracted from our discord message or on our message received event and the rest is going to be the same of course this part is going to be different for you and you you can find it over here once you log in this will be your own key this is my key for example so i'm going to copy this part over here to use it later in our code so first to make a post request we need an http client so i'm going to define a new http client object and i'm going to call it http client and it will be new http client and for that i need to add the http client that exists in the system.net.http namespace and http.https so after that i need to prepare the list of variables that i need to pass along the post request that we've seen in the documentation like the strictness level for example so this list of data is going to be in the form of a dictionary so i'm just going to define a new dictionaries and i'm gonna call it post request values or variables and it's gonna be a new dictionary of type string string for the key and value and of course i need to also add the collection generic namespace and the first key value pair is going to be the strictness for the speed if you read the documentation it also requires you to add how fast you want your evaluation to be i'm going to select it as fast and this is a boolean so it's going to be true and then a semicolon at the end so as i said i'll be passing these values using my http client when i'm making a post request to the ipscore api and of course we can't just pass it like that so i need to bake it into a url content using a class called form url encoded content and i'm gonna pass it my post request values so now i have my content ready the last thing that i have to prepare is the link or the url that i'll be sending and of course the url is inside of my match object over here so i'm going to prepare my url and send it inside of the for each loop so i'm going to define a new string and i'm going to call it url and it will be my match dot value now the thing is that as we discussed i need to replace any colon or forward slash with percentage 3a and percentage 2f so i'm going to replace that over here and first i'm going to do that for the column and i will replace it with percentage 3a now the replacement will return a new string that contains the string with the replaced value so i will also replace that as well to do the replacement for the forward slash so i want to replace any forward slash with percentage to f so here we are taking from our match object that we got from our content so the match is actually our extracted link or extracted values so i'm taking this value and i'm replacing every column with this value and then i'm taking the result string and i'm also replacing in that every forward slash with percentage to f as well and finally i'm storing it inside our url string and this url string will be the url that i'll be passing to the api over here all right so next step is to actually make the post request so i'm going to define a new http response message object and i'm gonna call it response and it's going to be the response that i will get from my post request so i will use my http post async and since it's an async method i'll need to avoid that and then i'm gonna give it the url that i copied earlier of course minus the link that we want to evaluate because that's gonna be changing so and then i'm gonna concatenate this string with my url string that i have evaluated over here and finally i'm gonna pass it my content which is the dictionary that we prepared earlier [Music] next i need to actually read the string or data that i got in my response so i'm going to define a new string and i'm going to call it response string and i'll use a method called read as string async from my spawns dot content and let me fix the spelling over here to response and it's a good practice to always test every bit of code that you add so for now i'm just gonna write my response string into the console just to see if it's working so now let's give it a try i'm going to run my bot and then once it's connected i'm going back to discord and i'll send this message back again and here we can see the response that i'm getting from the api it says the message was successful and then the unsafe value or unsafe boolean it says false which means this link is safe well since it's actually something that i made up actually it's not a real spam link but anyway so the next step would be to actually extract this unsafe value from our response string and then make a simple if statement if the unsafe is true then i will have to just delete the message so next i need to parse this response string into now if you look at our dependencies over here if we look at the packages discord.net and then discord.net rest we can see that we have a version of newtonsoft json already included in this discord.net package so we didn't have to actually install the newtonsoft json nougat package again a quick way to actually generate a chr class out of this json response is to use a tool that i'm going to show you in a bit so let me actually run the bot again and once it's connected i'll send the message again and here i'm just going to copy my response and i'm going to search for a tool called json to c-sharp here it is and i'm going to just paste my response over here and that's going to convert my json response into c-sharp classes basically that i can use directly so i'm gonna copy these classes over here let me stop the application and i'm gonna put them at the bottom of my main file of course it's always better to put them in their separate files for the sake of simplicity i'm just gonna put them over here the main name of my type is gonna be root and it's going to contain another class called domain age which also contains a bunch of other data related to the timestamp as we said i'm only concerned with this value over here which is called unsafe as you can see there is something new here this starts with an app and the reason why we need an ad over here is because the word and safe itself is a key word in c sharp so when you are dealing with unsafe code or unmanaged code you will see this keyword a lot and in case we want to use a reserved keyword as a variable name we have to add the at over here so that we can tell the compiler actually that we are defining a variable called and safe and we are not using the unsafe keyword itself similarly you can actually define a variable called string like so all right so next i'm going to use newton's soft adjacent to actually deserialize my response into a c-sharp object and the name of my class was root so and i'm gonna use it as it is of course you can change its name and i'm gonna call it parsed response and it's gonna be this realized object from the json convert class dot deserialize object and of course i need to add the newtonsoft json namespace once that is here i'm gonna use the deserialize object and i want to use the root as my type and string is going to be the response string once that is done after that i'll have a c-sharp object that represent my response basically so next i'll need to check if my parsed response dot unsafe is true so if it's not safe basically in that case i want to do two things first i want to send a message back to the chat that says this message is spam so args which is my socket message over here that we've been using the channel dot send message async and i'll say something like spam found and after that i'll call another async method that will actually delete the message and it's called delete async and we will be doing this for every link that we actually find so that if somebody sends a big paragraph with a bunch of links and one of the links is actually malicious so i'm going to delete the message and just reply with spam found probably it's a good idea to also add the author id so that i'm actually replying to to the guy who sent the spam message so i'm also going to add here the author id and i'm going to say something like bad boy and since i'm actually looking at multiple links possibly within a one message so uh it also makes sense to actually break out of the loop once i've deleted the message because every message contains three links the first or the second one is malicious once i found that i just send spam found then i read the message and there is no need to actually go through the rest of the links right so i'm after that i'm going to break and here is also a point or a place where you could actually improve the bot so maybe unsafe is not good enough or not good enough indicators so you could actually say um also if it's if it's suspicious so if it's suspicious or if the the score of the website itself the risk score is maybe less than 50 for example then maybe all of these criteria could your way to actually filter spam messages so i actually went the extra mile and i found you a link that is actually uh a bit dodgy so don't try to open this link on your own it's just for the purpose of testing so i'm gonna send it to the chat but let me first run my application again i'm gonna send that link over here and then the bot will reply with spam found along with my id followed by bad boy so to actually make it look more elegant let me actually change the author id to the username the username of whoever sent the message so we can actually shame them because you know it's not very nice to send such links right all right so now again spam found and it says mo basm bad boy so that's actually it for this tutorial i'll put a link in the description for this code on github feel free to modify it and use it as you wish as we said there is a lot of improvements that could be done to this spot maybe you could use a better exception handling because i'm not handling that very well over here you could improve the rejects over here maybe you want to use a different api for example a different service maybe you want to use more criteria um probably you want to also ban the user if you want so let's say if someone is continuously spamming maybe you can like add a database to your own bot and then if somebody sends like three or more links at the same time that are malicious then you could actually ban this user so it's all up to you basically alright so i hope that you enjoyed this video and you've learned something new if you did please leave a like subscribe and do the bell thing and let me know if you have ideas for tutorials that you want me to make in the future i would really love to hear from you other than that i'll see you in the next one
Info
Channel: tutorialsEU
Views: 1,464
Rating: undefined out of 5
Keywords: Tutorials, Tutorial, Programming, Course, Learn, Step by step, guide, development, programmer, video course, video tutorial, learn how to, how to, antispam discord bot, discord bot spammer, better anti spam bot, discord spammer, anti spam bot discord dashboard, auto spam bot, discord spam bot for pokecord, anti spam discord, anti spam, anti spam bot tutorial, anti spam api, anti spam algorithm, discord mods, discord bot c#, discord bot tutorial
Id: W1dYRP1eL1o
Channel Id: undefined
Length: 34min 37sec (2077 seconds)
Published: Thu Sep 16 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.