![]() |
VOOZH | about |
In this article, we are going to see how to create a telegram bot using Python.
In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filter the spam messages sent by users.
We can install this module via pip and conda with the below command.
# installing via pip pip install python-telegram-bot # installing via conda conda install -c conda-forge python-telegram-bot
Step 1: After opening an account on Telegram, in the search bar at the top search for "BotFather"
👁 ImageStep 2: Click on the 'BotFather' (first result) and type /newbot
👁 ImageStep 3: Give a unique name to your bot. After naming it, Botfather will ask for its username. Then also give a unique name BUT remember the username of your bot must end with the bot, like my_bot, hellobot etc.
👁 ImageStep 4: After giving a unique name and if it gets accepted you will get a message something like this -
👁 ImageHere the token value will be different for you, we will use this token in our python code to make changes in our bot and make it just like we want, and add some commands in it.
Brief usage of the functions we are importing:
Start function: It will display the first conversation, you may name it something else but the message inside it will be sent to the user whenever they press 'start' at the very beginning.
Basically, in the start message, you should add something like "Hello Welcome to the Bot" etc.
Help function: It is basically in this function you should add any kind of help the user might need, i.e. All the commands your bot understands, The information related to the bot, etc)
Adding some more functionalities to the Bot.
Here we have added 4 functions one to open Gmail, one for youtube, one for LinkedIn, and the last one for GeeksforGeeks. These are not MANDATORY functions, you can add any kind of functions and their reply_text as you want, these are just for demonstration. Here the unknown_text function will send the message written inside it whenever it gets some unknown messages and the unknown function will Filter out all the unknown commands sent by the user and reply to the message written inside it.
Here each line suggests that whenever a user writes a command i.e. the first parameter of the CommandHandler in reply the user gets the message written inside the function mentioned in the next parameter.
Here whenever we start polling the bot will be active and it will look for any new message sent by any of the users and if it matches the command specified there it will reply accordingly.
Below is the full implementation:
Output: