How To Create A Telegram Bot With Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
before we get into the video let me just quickly explain how this video came about so recently i started working at a startup called replied and through them i was introduced to jacob from clarity quarters and he proposed that he makes a tutorial video uh right here on cs dojo and when i ask my twitter followers if it's something they want to see they basically said yes and that's why i decided to post it right here so let's just get started one thing that i find very useful about python scripts is having some type of a script that can send you an alert or you can ping for information back now i've done this in videos with an sms alert and different things like that but it either costs something or there's workarounds that are kind of country based that doesn't work for all the viewers so what we're going to do today is set up a telegram bot that does something similar in just a couple lines of python so if you don't have a telegram account you want to go ahead and sign up for one and you'll come to a kind of starting screen like this it's free so go ahead and grab it now we need to get an api key to work with telegram so we're going to search for bot father bob father is telegram's official bot for handing out api keys so even though we're going to create our own custom bot we're going to get an api key from bot father you can see it'll show up here go ahead and click on that says some things that this bot can do we're going to go ahead and hit start and you can see here the different things that that we can ask for here and there is a i think it's new bot we'll just try it so you're going to do slash new bot and then it says what do you want to call it so you can pick whatever name you want this doesn't have to be unique so ours is going to be tutorialbot now this next one does have to be unique so it's going to say if the bot already exists and it has to end with bot so we can do our something like clarity tutorial underscore bot i gotta remember it because we gotta find it later so you can see that that worked it was unique if it wasn't unique it's gonna say that that bottle already exists try and create another one and you can just pick a different bot name here so you can see now we have this http api access token now you're going to have to get your own so don't copy mine here and we are going to use that so you're going to go ahead and select that entire line here all the way over and then we can go ahead and minimize this now for our program here we're gonna do it i'm gonna do it in repli for a couple of reasons one you can duplicate my code fully and run it in the exact same environment that i did you can also run this locally or however you want replit offers some paid packages to run the spot 24 7 and different things like that there's also some workarounds to run it 24 7 for free so that's that's the route we're gonna go here so you can set this up locally and follow the exact same steps i'm just gonna do it in replied there'll be a link in the description if you want to copy my code so we're gonna go ahead and do create a new repli it's in python obviously we're going to do telegram bot and then we can go ahead and add in we're going to add in one package that's going to help us work with that api so what we're going to do here is we're going to find our package so i clicked on this button there's a couple here options here for different apis that you can use the one i chose to use that worked really nicely with replit or whatever environment you're going to work with is pi telegram bot api and you can see it's in version 3.77 so in the future if this doesn't quite work you want to make sure you get the same version as me kind of hug that version but also make sure when you're searching for this package that you're not getting one of these others that aren't the right thing we're talking about this is like 0.0.4 so make sure you have the right bot now if you're in a different environment if you're in just your traditional local environment you can just do your pip install like you normally would so i'm going to go ahead and hit that plus button and it's going to install my package for me and we can go ahead and go back in our main project now if you're working with a free version of replit all these are going to be public the code that you're writing so you don't want to put your api key directly in the program itself so what we're going to do is we're going to add another file up here and we're going to call this dot e n v now what that's going to do it's going to give us a private place to store that api key that isn't shared so i'm going to say api underscore key i'm going to do all capitals just because it's a constant and then i'm going to paste in that api key and then i can save this now to get that api key into our program we can actually import os and then we can set our api key equal to os dot get env env and then just the key name so remember we called it api underscore key cool now we have our api key in our program as well we're also going to import telebot here perfect that's it so now we can go ahead and set up the basics of our bot i'm going to send you i'm going to set the most simplistic bot you can and a couple different things so i'm going to use yahoo stocks to kind of pull in data just to showcase something you can use this for whatever data you're trying to pull in so i'm going to show you how to send a message to the bot and it sends something back to you sends information back to you so how the bots work and we're going to start with just a reply so we're going to send it something it's going to reply the same thing back to us so we're going to do at bot dot message underscore handler so this is the kind of setup that handles the different commands that come into the bot we're going to look out for a command and the command that i want to look out for is greet so when we send a command of greet we want the bot to do something back and then you define your function of what you want to do right underneath that you can call this function whatever you want i'm going to mimic that from above and just call it greet i'm going to pass in our message so this is when it has a message that has a command of greet which i'll show you in a minute it's going to run this function and it's going to pass in the message as well now we can just do bot.reply to we're going to reply to that message with hey how's it going so this is going to be our basic setup for the first couple lines of our bot here and also we don't want to forget to create our bot as well so we're going to say bot equals telebot dot telebot watch your capitalization here and then we're going to pass in our api key now we got to set this bot to keep looking out for messages as well so we're going to say bot.polling so this is going to keep checking for messages you could look up in the documentation i'm not sure how often it checks it seems pretty instant so i'm sure it's every couple seconds or whatever but that's fine for us so now that we have everything here we can go ahead and run this script you can see it doesn't do anything right because it's just it's just pulling for information but we haven't sent anything to our bot yet so the one thing that we need to do is start a conversation with our bot so ours was clarity tutorial underscore bot so what i'm going to do is i'm going to search for that and you're you're going to search for whatever you named yours and you can see that here's our bot we're gonna click on that we're gonna start a conversation now commands start with the slash symbol so you remember in our program now we don't have to do them all as commands but we set up the first kind of test as a slash greet so we're going to try that so we're going to go slash greet and of course coding is really fun so your commands really matter here this is commands with an s we'll change that let's stop this we'll restart our bot and pretend i didn't send like eight messages trying to figure that out and you can see that if we use the correct capitalization we get the response that we are looking for here you can see it says hey how's it going which is what we typed as our response so we have a working bot set up here and this is how you're going to use commands to kind of get text into your bot itself now you probably noticed that it used a reply line so it copied my message from above into the actual message it sent that's because we use the reply to one that you'll see that's very common is also to we'll copy this let's call this hello we'll say hello here if you say hello we'll call this function hello and instead of reply to let's do send message so what we can do is do send underscore message instead now this you it has to know what chat it's in so we need the chat id now luckily we can get that off the message itself so we can do message.chat.id now if we stop this and run it now we should have a command that we can run with hello no capitals here you can see now it doesn't have the re it's not replying to a certain message it's just prompting to actually send that message cool so let's do something kind of useful now uh i wanted to use a library that i don't have to set up an api key or anything like that just for ease of use so if you want to ping for different information follow along exactly with me here see how i do it from yahoo and then branch out and do whatever you want and make sure to share it so we can all see how you did it that sort of thing so i'm going to grab the yahoo api here so i'm going to pull in yahoo finance and then i'm going to walk you through a function that i created to grab the wall street bet stock so if you've been following reddit and all the craziness with gamestop and different stocks like that i want to create a function that whenever i ping it it sends me the last three days worth of stock prices for their favorite stocks like amc gamestop and nokia so here's the function that i use to create this and we'll take a look at it here so what i did was i added another command function so we're going to have to use the slash and wsb i'm going to show you how you can do something without a command next but we're going to do one more command here so this is slash wsb standing for wall street bets and what it does it runs this get stock function we're going to pull in a response that's just where i saved all my data back when i get responses and then you can choose whatever stocks you want to put in here i put the three wall street bet stocks that i see that are most popular with them then for each stock i'm pulling in data off of yahoo so this is where i call the yahoo finance api so i'm saying download the ticker and the ticker that i'm choosing is one of these three it's rotating through those each time it's getting a period of two days and it's giving you the one day price so that's the data i'm getting back that data is a pandas data frame that you can kind of check out and look at but essentially it's just going to have this data in it i'll show you a pop-up here to kind of show you what the data frame looks like we're going to reset that index so what that does instead of the date being the index it's going to reset the index to be 0 on the side and then we can pull the date out of that information so then my response is going to be the stock this is an f string so we're putting in the stock name and then we're going to append that to our stock data frame and then for each row so for each row of information for that stock we're gonna pull out the close price and round it to two decimal points and we're gonna format the date in month slash day so that's what we're doing on this line and then we're gonna add that to our response append the stock price then just print out a blank line after each stock so now after we have all of our stocks information i do something a little special here i'm adding in some spacing just to make it look right on the output on telegram itself it gets all kind of jumbled up so what i'm doing here is i'm adding the column headers and i'm making sure that each of them have 10 spaces so they're kind of lined up and then i'm doing another 10 spaces for the next column another 10 spaces for the next column so we got the stock name the first date and then the most recent date and then i'm just simply sending that in a message in a response so that's it that's how we created that function now we can go ahead and stop this if we run it again then let's open up our emulator here and we'll do slash wsb oops we in we installed some other library so we gotta wait until it actually starts running here i got a little impatient drink some coffee it's not t i'm not scent decks then you'll see that it still did run our function after we finally got the data it's printing out to console i just had that for some debugging and things like that but if you open up our tutorial bot you can see that when we send it slash wsb it sends us back a response with the data we requested so you can see here these are like the column headers it has stock oh 331 and 0401 which is the last two days the u.s market was open and then the stock prices for those stocks the formatting is a little weird because telegram's a little uh finicky about how things are structured so you can play with that a little bit and make it better i'm going to show you one more and that is how to not use a command so we don't want to use slash anymore say say you want to do something custom like you want to say some type of code so you want to say like stop a price space and then a stock name or something and then you want to get data back so here's the setup we're going to use for this next part it's a little different so we're going to use message handler again but we're going to use the function keyword and then we're going to create a custom function now that custom function when it returns true then whatever's inside of here where i said pass that will run so your function is going to either return true or false based on the message and then if it's true it'll run whatever you want to create it might be a little confusing but we'll go ahead and walk through it here my function so this is to return true or false so this is to decide if this send price actually runs or not so our function that we want to control that is called stock request so what i wanted a stock request to look like i'll pull one up on the screen is to have price space and then a stock name so what we do here is we test to see if it's possible that this is a stock request so what i do right away is i do request i take the message and the text from the message and i split it and when you split with the default parameters it splits it based on spaces so what it's going to do here is it's going to split it up into as many spaces as it has so if i say price space gme space hello world it doesn't matter the it's gonna break it into those first two chunks so what i'm saying is the length of those chunks i have to have at least two right because if i have price space and then the stock name that's going to be two so i'm going to make sure it's at least of length 2. at least has one space in it then i'm going to take the request that first space i'm going to lower case it so in case you do price with a capital p it'll still work and i'm going to say if it's not in price so if it's not at least of a link 2 or if the first word isn't price we're going to return false because we don't want to run it anything else is going to return true so if it does have price as the first word and it does have at least two items in the message itself then we're going to run send price so now we can fill out this function below here i'll copy pasta a little more and then walk you through it so remember we're doing something here that could cause an error if we weren't validating before this is only going to run if we have a zero index which is price and a one index of something so i can go ahead and safely try to grab out the one index because i know this wouldn't run if we didn't have a one index because we tested for up here so my request is going to be the one index i know the price is at the zero index now what's at the one index we don't know we hope it's a stock ticker so if it isn't a stock ticker yahoo is just going to return no data and we can send that back that we didn't recognize the stock symbol or whatever so what we're going to do here you can see instead of putting in a ticker i use whatever the user sent in request and i'm going to get one minute data chunks and i'm going to get five minutes worth of that data so essentially we're going to get the last one minute stock price of whatever ticker they want to put in so this could be useful like during the actual trading day stuff like that so here's my check when i get that data back i'm making sure the size is greater than zero if the size is less than zero we're just going to send back that we didn't get any data if the size is greater than zero then we know we got some stock information back and we're going to go ahead and format that i'm going to do something very similar to what i did before so i won't break it down too much but i'm essentially making a format a date this time i do it a little differently because it's minute data instead of daily data so i'm going to pass back a month a day the 12 hour time frame and the minutes and then am or pm i'm going to set the index blah blah and then eventually i'll send the message so let's go ahead and try this out so we can stop here we can run it again now remember we picked the format we could pick this to be whatever we want so we are going to start this command with price do space and then whatever we want to uh whatever we want to look up so let's try a new one let's get a popular one so we'll go price tesla and you can see now we get a now you could have a nice title here or something that would have looked nice here now that i'm not i'm looking at so we know we're looking at tesla here but you can see we got the last five minutes worth of data now the market's closed so we saw the actual last five minutes of the day uh if it was a live market you would see the last five minutes now but we got those prices here so let's try another one we'll say price some garbage and you can see that we got no data back because it wasn't a real stock symbol let's try one more so we're going to say price gme and then this is my favorite stock so what's gonna happen here is it's gonna break up this and it's gonna still pass our validation right the first index well nope now it will the first index is price and then the second is going to be a stock ticker and it's going to ignore everything else in the statement so it is still going to give us back the data i hope and you can see that we did get our data back now if you like this video if you want us to do a couple more things with telegram we got a few more ideas here let us know in the comments what you want to see and we'll put it in the next video the one thing that you want to note here is if you're on a free account of replit this is going to fall asleep after a certain period of time if you're on a paid version of the account you can get a trial that you can go down to always on and turn this on and that will leave your bot running 24 7. now there are some workarounds for this as well that i will show in the next telegram video along with anything else you would like me to show in the comments below give this a shot let me know what you think and until next time keep coding
Info
Channel: CS Dojo
Views: 194,118
Rating: 4.9280238 out of 5
Keywords:
Id: NwBWW8cNCP4
Channel Id: undefined
Length: 20min 23sec (1223 seconds)
Published: Tue May 04 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.