Discord.NET Bot Development (S2) · Working with APIs · Episode 7 [OUTDATED, SEE DESC]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to episode seven finally it's time and the episode is here we start by apologizing for the long long wait for this episode it has been a couple of months the last episode was released three months ago and i'm so sorry now first off in the last couple of months a lot of things still have happened on the discord server for instance we have switched to kofi from patreon and we have started our own minecraft server let's quickly take a look at our kofi page before we start with the episode there's not much new except for the extra option that's called access to minecraft with aphone i've added this option because recently i have started a new micro server which is only accessible to patrons of the channel and you can start joining us for as low as one euro per month and as soon as you become an all access patron or a vip patron you get to bring a friend now why does this cost money and that's a good question now the main reason is because of the cost of the server micro 1.17.1 is using a lot of resources computing power etc and that costs a lot of money when you want to host it on a server it has good specs so that you can have a lot of players on the server and therefore i have bought a pretty good server but of course that costs money and part of the donations that go through coffee are going to be used to afford this server other than that the kofi page also allows you to do a one-time tip by buying me a coffee which would be amazing because recently i've started to drink coffee again so feel free to take a look at this page and join our microserver or of course become a patreon to join our coding nights now with that being said it's time to start taking a look at episode seven what are we going to do today now first off there are a few small changes that we're going to make to our analyzers that we're using because some things are just a little outdated and we need to update that the second thing that we're going to look into today is apis how can we send a request properly to an api then get the json or some form of data back and then convert that into something that we can use in our code let's start with the first one we're going to make a couple of changes to our analyzers which are telling us to change certain things to be in compliance with certain conventions but some of those conventions are a little outdated and thus we're going to make a couple of changes to make this more modern the first one is to get rid of this we're going to get rid of this because the conventions revolving this have changed now you just use it like this unless you have a private property in which you first have a underscore and then the property itself so let's get rid of this keyword and then we can hover over context because of course we'll get the warning again then we press the light bulb we say suppress or configure issues and then what we can now do is say suppress sa1101 in the suppression file which will then suppress this warning now because we want to suppress this warning in the entire project we're going to go a bit to the right get rid of this last part which is saying target and scope as we want to apply this globally then we can provide a justification as for why we are doing this in my case i will just put here hey the conventions are a little outdated so i'm sticking with not using this just like that now we can go back to general and see that we no longer get this warning and when we hover over this we can actually remove this qualification in the entire project by just clicking here and then clicking apply as you can see in all of our files this has now been removed except for locations where they actually have a function like for instance here and let's take a look into that because private fields with the newer conventions start with an underscore so we'll change this all to underscores and again we'll get some warnings saying hey field underscore provider should not begin with an underscore but then we will say or configure issues press sa1309 and an in-suppression file again we get rid of the target in the scope because we want to apply this globally and then as justification we say as conventions have changed private fields do begin with an underscore now that that's done we can go back to our command handler and rename all of these fields so this dot provider becomes underscore provider this dot client becomes underscore client this not service becomes underscore service and is not configuration becomes underscore configuration now let's just go over all of these names in this file and replace them where needed the client is going to copy that here and just paste it everywhere that we have it we do the same for the provider here and here and i see that we missed the client over here we'll just rename it like this and then we go up we do the same for the service and here and for configuration we of course do the same as well let's really check if all our files are now correct and as you can see now we're more in accordance with modern guidelines now we're still using the analyzers for instance to remind us that we want to add comments and explain things to certain methods or to stay in certain conventions like putting brackets around these and not emitting them now that that's done it's time to start looking into working with apis now for today's tutorial we're going to be using the board api which is very simple it's just going to give us a nice little bit of json containing a little bit of data regarding some random activities that you can do how accessible they are how much they may cost and how we have many people you can do them etc now board api the link to that will be here and you can already see a small little example over here now when working with apis it's very important to look at the documentation you can of course just straight go to the developer and be like hey i want to do this and this but well if 100 people ask the same question at some point that developer can get a little irritated therefore they have made documentations like this one over here where they try and explain what their api does what you need to do if you need to provide something to it and what actions you can do for instance the most basic one is to get a random activity you just go to this link which is the sample query and the expected response will be something along the lines of this if we go to the discord documentation for its apis we can actually see that they have the same so if we go for instance to a channel and we say get channel they'll say okay this is the action this is the url and this is a description and then sometimes they'll include a sample response such as if we go a little down here you'll see a sample response of what you may get back these documentations are extremely valuable they'll give you vital information about what you need to send what you can expect back etc so if we'll take a look back at that board api documentation we can see that we'll have to send a request to this url and then we can expect a response looking something along the lines of this so if we copy that url open up our browser and go to it you'll see that we indeed get that response so that's all working really well but now you may be thinking like an episode or when we implement apis wouldn't this get very complex again with using some weird indexing and zeros and knowing where to go yes but there's an amazing tool that actually helps you with that and just in general it is a very good practice when you have data such as json to make a class where you can convert that json to so that instead of saying data and then square bracket zero square records one sphere goes to zero you can actually say data dot in this case for instance activity or type or participants that makes life a lot easier and there's an amazing tool to help you with that which is called quick type and that is on this website which will of course be in the link down below now if we press generate c sharp now go back to the board api's response that we have over here and copy the output like this and paste it in here you'll see that it converts the json from here to c sharp over here and then we can give this class a custom name let's give it the name activity like that now we have a class called activity with some fields like activity activity type participants price link key and accessibility now because we already have a field here called activity let's change this to a event that way we now have just a normal field called activity type participants price etc now you may be wondering what do all these fields mean and again that's why the documentation is so important because if we go back to the documentation and just skim over it see what's in there eventually we will find a table explaining each key and value to us so the activity key will give us a description of the curied activity if we look here activity actually explains okay well what is this then the accessibility being a factor describing how possible event is to do with 0 being the most accessible and if we see here accessibility 0.08 means that this activity is quite accessible now the type is the type activity and so on and so forth so this actually explains what data we will get in return and what it all means now let's put it to use we have our model here as we can call it but as you can see there's something here called a par string converter and in this class there's nothing really like a method that would allow us to convert the json to this class so to get that as well we want to go here on the right pass attributes only and change it to complete which will give us even more let's quickly go over the code that it now gives us the first is public partial class event with containing a method called from json that's very simple this will simply give us a method from json converted to a event and from an event converted to a string which is then json these will all be within one class then we have another class called converter this is a class that is made by quick type and that's all done by them we don't have to worry a lot about it it will just help us convert the json to the class and vice versa and the same goes for the par string converter in this case it is then more related to strings so converting something to string and string to something so what do we do i made a small mistake a serialized class is actually not part of the event class it will be a separate class because this will be able to contain multiple two json methods that will convert multiple jsons to their respective class so what we'll first do is we'll have one class called event which is containing all the methods and fields related to events we have a class called serialize which allows us to serialize an event or a class in this case which one of them is an event to json and then we have this class which will be helping with that and this other class which will also be helping with that so first off what we'll do is we'll copy these two classes we'll then go to visual studio and go ahead and make a new folder in which we can store these models so right click your project press add as new folder let's call this models now we right click this folder press add again press class because we're going to make a class in there in which we can store our event model then we want to replace this class with the class that we just generated we're going to add a lot of errors and warnings because we simply don't have everything in place yet so what you want to do is hover over json property press the light bulb and say using newtonsoft.json which will already resolve a lot of the errors then because here it's referring to the quick type namespace we can actually get rid of this because our namespace is watermelon.models but since we're going to place this converter class which i mentioned earlier in the same folder we don't need to have any namespaces here so we can just get rid of it now we can do is create another class over here add class and we're going to make that serialize class press add go to the browser go to quick type copy this portion of the code go back to visual studio and paste it in here again because the namespace quick type is not required as we're going to be using this within the same folder we can just get rid of it hover over json convert press the light bulb and say using newtonsoft.json now we go back to our browser and we copy this converter class go back to visual studio right click models press add class and call it converter replace the contents with the portion of the code that we just copied click the light bulb say using newtonsoft.json then hover over here press using newtonsoft.json.com and go over here and press using system.globalization now we go back to our browser and do the final part which is this internal class parse string converter copy the portion of the code go to visual studio right click models press add press class and call it parse string converter and replace the contents with the code that we just copied like that and make sure to add a final curly bracket at the end now hover over json converter press the light bulb using newtonsoft.json and then we're done now it's going to give us a lot of warnings about what to do and that we need to provide some explanation here and there or all of the things that we just pasted and it's of course normal feel free to do all of those on your own you can add comments this was also discussed in previous episodes but for now we're just going to look more into the api part as of course the analyzer is something that we discussed in episode 5. so let's go ahead and go to our event class and take a look in here now the first thing that i will do is get in compliance with our analyzer and get rid of the using statements that we simply just don't use then we'll move this using part into the namespace like we've done in the previous classes for instance if you look in general you'll see that the using statements are within the namespace and then we can go back to our event class and then what i do want to do is add descriptions to these fields now because we get this data from an api we can just simply put the description of the api as description over here so we just go here use a comment like this so that we have a summary go to our browser and go to the documentation and just copy the description that we have over here go to visual studio and paste it in now because we have a get and set over here the analyzer will ask from us to have get or sets dumping something in this summary so we'll say gets or sets the description of the query activity and then it will be happy let's repeat this for all these fields now for instance sometimes you may stumble upon fields that are simply not described like this link in that case you can just analyze the data you got yourself and consider what to do for instance if we were to refresh and see that this link field usually is just not used we can just have a generic description something along the lines of get source sets the link of the activity and of course all the other fields that do have an explanation can just be copied from the api documentation now that this is done let's go over here and give our event class a description as well and we'll do the same here and then for the from json method will give a summary and that this method allows us to convert json to the event class as a parameter we have json and then we'll set this to djsong to be converted and then returns a converted c event object now when that's done we can go to our general class and now you may actually be wondering how are we going to do this so first off of course we want to start with a nice command which we're going to call let's just call it activity then we'll bind a method to it public async task activity and open it up for curly brackets now how do we exactly make this request we could of course like episode four in season one use something like a http client or something along the lines of that but there is a small problem with http clients to put it all simple during the entire lifespan of your application you want to use just a singular http client and although you can just inject hp client in your application and then try and just use it once that may get quite difficult so instead of using a http client we're going to hear using a http client factory allowing us to create http clients or get ones whenever we need one while properly keeping them managed now how do we do this first off we'll need a special library that's going to help us with this so we'll go to tools we get package manager manage nuka packages for solution in here what we want to do is search up extensions.http and then the one that we want is microsoft.extensions.http which is made by microsoft click your project and hit install and now when that's done you can go to your program.cs because in here we want to add a dependency to our service collection let's go down here where we have add hosted server command handler and let's add http client now this method takes care of a couple of things for us allowing us to use hp client factory which we can then use to get http client and then use it to make a request to an api so let's go back to our general class and in here what we want to do is get that hp client factory let's go all the way up and first we'll start by making a new field called private read only and then i http client factory and then we want to use system.net.http and then underscore http client factory and then don't forget the underscore at the start then we want to get a constructor we can simply do this by typing in the keyword ctor and then pressing tab twice or we can just write it manually by doing public and the class that we want to have the cross sector for so general and then two parentheses and then two curly brackets now there's actually an even faster way to do this entire part let's just start over real quick and give you a quick tip get rid of this part type in ctor and press tab twice then go over here and add i http client factory http client factory like this then hover over here until you get the light bulb or get your cursor over here and then create an assign field hp client factory like this now this will not already use a underscore at the start so let's add one and then instead of saying this dot http client factory equals http client factory we'll say under squares to be client factory equals hp client factory now in here we can just inherit the constructor documentation and say d c i h v client factory to be used like this now that's done we have done the most complex part of all now we can just go down and now we can start writing the code that will actually get us the data to do this we say var http client so to get a client that we can use we do underscore http client factory dot create client it's just going to get us a beautiful hp client that we can use then we want to make the request we do this simply by saying var response so we're going to store that response into a nice variable and then we'll say await this is an async method that we want to run http client get string async so we're going to not only send a request but then also we want it as a string asynchronously and then we have the url now the url of the api if we go back to our browser go over here it's just something that we can find in the api documentation so if we go all the way up we can find it here and if we go to the main page we can find it right over here so let's check out the documentation copy this url go to visual studio and place it in here make sure to add the s after https and then we add a semicolon all the way at the end and now we want to convert this response that we have into our event class how do we do that that sounds very complex well not that hard all we do is we save marvin so this response converted to our class equals now because event is also a keyword instead what we'll do is just call it activity from the start and then say equals event and now we want to have using watermelon.models dot from json and then the response which will convert our json to a nice response now there are cases where we might get an error and in that case we want to let the user know like hey something went wrong please try again later so if the activity equals null then we'll say away reply async an error occurred please try again later like that and then we do an early return statement if that's not the case we can just give the data back to the user so we'll say away reply async and then first let's start with the description so activity and then some description and so forth let's put a semicolon here and put some nice stars over here so that that part will be pulled now because we want to use inline variables what we want to do is add a dollar sign at the start over here now how do we use our model we simply use some curly brackets so that we can use inline variables and then we'll say activity dot activity as you can see we can now just use a class and even use intellisense to autofill the properties of our model and thus our data then we can say okay well how many participants so participants then we can just simply say activity dot participants and we'll get the number and what about the type we'll just say type and then curly brackets activity dot type now you may be asking wait is it really this simple well let's give it a shot let's run the bot let's head over to discord and try and run this activity command that we just made as you can see we now have an activity go to the gym participants 1 i have to go alone and type recreational and if we run activity again ok take athena participants 1 and type relaxation now if we go back to visual studio we can even add more data we can for instance also provide it with the price factor but we can say activity price and we can say something along the lines of accessibility activity.accessibility and present all the data that we get from the api so if we run our bot again go to discord and try to run this command again you'll see that we get some even more data and that's super cool now i hope that this was useful for you all and that you're now a little bit more comfortable with using apis and their respective documentations now as we've come to the end of this episode i would like to say a huge thank you to run free steve mobs j free fembok takashi 98 alif von pelt nicholas barclay taylor strantley regis vilokas 26 gameplay zero nine cody stuma zillion kyog and andy young for supporting our patreon and kofi page you guys are absolutely awesome thank you all for supporting the channel and i hope to see you all in the next episode now if you have any questions need some additional support feel more than free to join our discord server which you can find in the description down below i hope you have an amazing day and i hope to see in the next one bye [Music] [Music] you
Info
Channel: Coding with Efehan
Views: 889
Rating: undefined out of 5
Keywords: discord, discord.net, discord bot, c#, classes, API, models
Id: AVM67MQFcUI
Channel Id: undefined
Length: 30min 0sec (1800 seconds)
Published: Tue Sep 28 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.