How To Create A Telegram Bot In Python For Beginners (2023 Tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
how's it going guys in today's video we're going to be looking at how we can create a telegram bot in Python and this is going to be compatible with groups as well as with private chat and I actually have to update this because my 2022 version is not working anymore so that's what led me to create this 2023 version because there are some minor changes in the API that we have to apply for it to still work but I'm going to be showing you how to do this from scratch in pycharm using Python 3.11 and to get started you need to open telegram either on your mobile phone or on your computer and you need to search for bot fodder so tap on bot further and click on start and this is where we need to set up the bot the initial face of the bot needs to be set up over here so when you start a butt folder you're going to get a lot of commands that you can use and the first one you want to use is the new bot command and it's going to say all right and you bot how are we going to call it how we can call this banana bot then we need to choose a username and that username must contain bot so we're going to type in banana underscore banana underscore bots so banana banana bot and we will tap on enter once again okay some fool out there took my username so I'm going to type in BBB banana Bots and that worked and as soon as you find a username that has not been grabbed by some other fool it's going to give you this access token that you need to remember so copy that and for now you can just paste it in your python script so here we can type in token and that's going to equal this token now I'm also going to import from typing final keyword just to give these constants a type so token of type final is going to equal this token and we should also get the bot username out of the way so we can type in both username of type final is going to equal and you need to insert your username that you've created for your Bot but it's going to start with an ad so now I have BBB banana bot and that's going to be my bot's username but let's go back to the API or to this text over here and continue customizing the bot because that's the interesting part and it's quite self-explanatory as you can see it gives us a lot of good descriptions with the commands that it has so you can easily do this by yourself but we're going to just go through a few of them such as set description and here we just need to First select which bot we want to change the description for so Banana bot and we need to give it a description of what it can do we can say I can respond as a banana exclamation mark and tap on enter and the description has been updated next we're going to set the about text so slash set about text for banana bot and we can say something about the banana I am a banana but I like bananas and we'll tap on enter after that we're going to set the user pick so slash set user pick for the banana bot and here you need to provide a profile pic for the bot so I'm going to drag in this banana picture and it's going to give us the success message if it accepts it and finally the last thing we need to do is set the commands but we will be coming back to that later because we do not have the commands in our script just yet so there's no point in setting them if we don't know which commands we're going to provide but for now we have most of the Bots set up and if we actually search for this bot so we say banana bot it's going to appear in the search so now we actually have our bot appearing with the profile pic and if we tap on it it will say what can this bot do and it says I can respond as a banana if you tap on the bot and look at the description it will say I am a banana bot I like bananas so all the information we filled out is that all we have to do to use it now is tap on start but I'm not going to do that just yet because we do want to provide a command for the user that's using this bot to see what happens when we tap on start because you can customize what happens when the user Taps on start and if we do it now nothing's going to happen because we did not program any of that but now that we've created everything that we had to with bot folder we can go to our script and finally get started with the coding or that's not entirely true because we still need to install a package and here we're going to type in PIP install python Telegram but in the terminal and tap on enter and as soon as that's done we can just close the console and we can import the elements that we need from that package so first of all I'm going to import from telegram the updates then we need to import from telegram dots extensions the application the command Handler the message Handler filters and context types and with all of these we can actually get started with creating our telegram bot the first thing I want to take care of are the commands so first we want to create a start command and with the new API we need to use async in front of our functions to make them asynchronous so here we'll type in async Dev start command and we need to provide the updates of type updates and the context of type context types dot default type then we're going to await update Dot message dot reply text if I can find that reply text and you need to pass in here the text that you want the bot to say as soon as the user Taps on start or does slash start so here we can say hello thanks for chatting with me I am a banana so this will be the first message the user gets when they start the bot and that's all it takes to create a command just make sure that you put all the logic of the code that you want inside here and that you return it as a reply text but we're going to copy that and create two more so now we have a start command and I also want to create a help command so help and the help command will just tell the user how the bot works or it will give some useful information about the bot so I am a banana please type something so I can respond and that's all we need for the help command and right below we can type in let's say custom command so if you have something else you want to create just give it a nice name that you can remember and we will update this one accordingly as well this is a custom command and that's the text that will be sent to the user when they use the slash custom command and I'm just going to place a comment up here that says commands so we can remember that these are commands right below that we want to create a way to handle the responses because right now you can write to the bot but the bot will not respond to us so we need to add some logic and I'm just going to type in handle responses or let's actually change this to responses because the next function we're going to create is called handle responses or handle response which will take some text of type string and it's going to return to us a string so inside here you want to put your logic you want to put your AI you want to put whatever code you have to process the text that the person is going to send to us and you want to return it as a string so in this example we're going to create the most simple chatbot there is and that is an if elsebot so if hello is in the message so in text we're going to return hey there if how are you is in the text I am good if I love python is in the text we will return remember to subscribe if none of these trigger we're just going to return I do not understand what you wrote and to make this more reliable we will add something called process text so we'll say processed type string is going to equal text Dot lower since python is a case sensitive language which means if the user types in hello with an uppercase this will not be recognized because we are looking for a lowercase hello so with processed we can just change all of this to processed processed and processed so we won't have that issue in case the user types in something with uppercase letters or lowercase letters it's all going to be lowercased at the end to simplify this if else check now that we have a function that handles the response we need to create a function that's going to handle the message for us so it will send it back to the user whether they are in a group or whether they are in a private chat so let's create that right below and here we need to create async def handle message and inside that we're going to insert the update of type update and we need to pass in the context of type contextypes dot default type and the very first thing we want to do in here is create a message type of type string and that's going to be the update Dot message dot chat DOT type and this will inform us whether it is a group chat or a private chat after that we can type in text of type string and say that that will be equal to update Dot message dot text so that is the message that is incoming the one that we can actually process next let's create a useful print statement that is good for debugging so here we'll type in print F and we need to insert the user in some parentheses and this user is going to be the update Dot message dot chat dot ID so we're going to get the user ID who's sending the message and we're going to say that that will be inside the message type so we'll find out whether it's in private chat or in the group and we want to also send what kind of text they are sending so here we'll just add the text and that will just log in lifetime the messages that are incoming to the bot now the reason we want to know whether it's in a group or in a private chat is because we want the bot to act accordingly which means in the group we don't want the bot to respond unless it's being tagged or unless we are directly talking to it so we want to differentiate talking to it in a group from talking to it in private and the way we're going to do this is check whether the message type is equal to group and if it is we're going to create another check so he'll type in if but username is in the text so if we're actually trying to talk to the bot in the group chat we're going to do the following we're going to first start with creating a new text of type string which is going to equal text Dot replace and we want to replace the bot username because we don't want that to be processed as part of the message we just want to process the text so we're going to replace the bot username with an empty string and to make sure there's no leading white spaces or ending white spaces we're going to call Dot strip then with this new text we can create a response and the response is going to be of type string and equal to handle response which is just going to take that new text inside else if we're not trying to contact the Bots we're just going to return out of this function because the bot should not respond unless we're explicitly calling its username and on the outer if block we're going to type in else once again and say that the response of type string is going to equal handle response of type text so this will work for all the private chats outside of the if else block we need to print that the bot gave the following response and again this will be for debugging then we can type in a weight dot update message dot reply text and we will pass in the response so this logic will take care of responding to whatever user tried to contact our bot and finally we should go down one more level and create one more function and this will be used for logging errors so async Dev error and we need to pass in the updates and the context type so we're just going to copy that from above and paste it inside there and all we're going to do is print that the update and this has to be a formatted string so that the updates update caused the following error and he will pass in the context dot error so now we wrote all of the major logic let's just glue this all together by creating a if name is equal to Main Check and inside here we want to actually put this all together so to begin that process we'll type in app is equal to application dot Builder and it's going to take a token which is our token and we need to call Dot build then I'm going to make some space and right after the app we need to type in app dot add Handler and we need to add a command Handler and the command Handler is going to take care of the commands so if we say we have a start command we need to specify that here as a string and call it start followed by the command that we want to insert and we're going to duplicate that two more times for help and custom so custom and help and remember to change these as well so help and Custom and that has to be called without the parentheses and to simplify this if you are creating a project I would recommend adding a comment here that says commands so that you can keep track of where your commands are and where the messages are going to be for example right below that we need to create some messages so messages and it's going to be a different Handler so app ad Handler and it's going to be a message Handler which is going to be used with filters dot text and we need to pass in handle message so that will take care of the messages then below we have the error Handler so we'll type in errors and we'll say app dot add error Handler and we will just pass inside the error and the final thing we have to do here is check constantly for updates on whether there's a new user message or something we have to respond to and we're going to do this through polling so app dot run polling and here we can choose to specify a poll interval which essentially just tells the program how often do you want to check for new updates so you can say every five seconds you can say every one second I'm going to keep that at five seconds or actually I'll leave it at three seconds here so it checks every three seconds for new messages and something nice you can do as well is print that the program is starting so you can type in starting but and right above polling you can print polling so you'll get some feedback in the console when you run this bot so it doesn't just look blank when you start it because you never know what's happening whether the bot is running or not if you don't have these kind of print statements having a print statement such as starting bot ensures us that the program is actually running and then having a message such as polling ensures that all of this actually ran and we're not waiting on something for no reason but next we still have to add the commands to the telegram bot via the telegram app and then after that we can finally run this bot so let's go back to bot fodder and inside here we want to type in slash help so that we can get all the commands back and the next one we want to use is the slash set commands and you don't have to tap on these you can literally just do slash set commands if you want I just find it easier to navigate inside here so I'm going to tap on slash said commands and maybe remove this text and right now it's not letting me pick there we go so we need to pick banana Bots once again and we need to provide some commands and at the moment we have three commands so if we slide back to our script you'll see that we have a start command a help command and a custom command and these are the triggers for the command so what we need to do is write these commands down and provide the description for each command for example we can say start and you here we would write something such as starts the bot then you want to create a new line and put in the next command so here we can type in help provides help for banana but and finally we have the custom command and the dash should come after so custom this is a custom command and that's going to provide the command context for the bot you don't need to write these but they're just a lot more convenient because just like with bot folder when you do slash you're going to get these help messages popping up that will make it much easier to interact with your Bot but now that we have that done we can go back to our script and we can run it so we're going to tap on the Green Arrow and if everything's working nicely it's going to say starting bot and it's going to say polling so so far so good the bot is polling which means it's waiting for someone to write something to it so that it can respond so going back to part fodder or not really bought further but telegram it's finally time we look for banana Bots one more time and that we finally started so if we tap on start it's going to say hello thanks for chatting with me I'm a banana so the first message was triggered now we finally can start chatting with banana bot and here we can say hello and banana bot will be able to respond so how are you and banana butt will say I'm good but if we write anything that doesn't make sense to Banana bot banana bot will just give us the default message back and I will tell them that I love python and banana bot will tell us to remember to subscribe now because we defined some commands we're going to get these commands appearing as soon as we use slash so slash help is going to give us the help message I'm a banana please type something so I can respond or the custom message this is a custom command so you can use commands with the spot if you want and there's even the menu that brings that up so that's pretty cool but how do we use this in a group so what we want to do next is create a group and here I'll just tap on new group and we're going to call this Banana Group and click on next and the only member I'm going to add in here is banana bot so I'm going to create this group now it says I created the group and if we want to start talking to Banana bot you'll notice that if we type in at Banana bot and we say hello nothing's going to happen and that's because we need to give banana bot administrator rights so we're going to go to view group info we're going to right click on banana bot and we're going to promote banana bot to an admin and you can pick the permissions you need to and click on Save then if we close this banana bot will now have the correct privileges to respond so we can say at Banana bot hello and banana bot will be able to respond but if you say hey it's not going to respond because we did not mention add banana bot so this is a nice feature in case you want users only to contact banana but with a direct mention and if you want banana Bots to respond to all the messages you just need to go to handle message remove this entire section with the group and you need to make sure that you're only getting this response back so now it's not going to care whether you mention the bot directly or not it's going to just run as is so now if we did that we can say hey and banana bot will respond to everything hello and you'll see banana bot will respond regardless but I think it's much better with the mention because I mean it makes more sense in a group you don't want banana bot responding to everyone all the time so if you just add that and actually we need to rerun this script to make it work now Banana bot will only respond if we use this hello hey lots of other texts it will only respond to the mention and as you can see in the console we're getting a lot of logs about which user said what whether it's in a group and actually let me demonstrate in private if we say Hey or hello you'll see that it will say in private and then the bot will be able to respond but with that being said we've finally finished our telegram bot there's a lot you can add to it this is just a starting point for you and I made sure to update it for 2023 so the next time I'm going to make a video is probably in 2024 because it seems like every year they introduce something new to this API which means I need to constantly update it but I hope you enjoyed this video do leave a like or consider subscribing if you enjoy python videos in general but with all that being said as always thanks for watching and I'll see you in the next video
Info
Channel: Indently
Views: 254,504
Rating: undefined out of 5
Keywords: pyton, pyhton, pythn
Id: vZtm1wuA2yc
Channel Id: undefined
Length: 22min 30sec (1350 seconds)
Published: Mon Mar 27 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.