Create a Telegram Bot using Python
In this article, we will learn to create a simple telegram bot using python. First of all, we will create the API token for our telegram bot.
Connect with FatherBot
We can do this by opening the BotFather bot on telegram. Yes, we will be using a bot created by Telegram to start creating our own Bot. For this, you must have telegram installed on your machine. If you have it already installed, click on this link to start with. This will open a new Telegram Bot chat and clicking on ‘start’ will give you the following screen.
Create a new bot using the Father Bot.
Now send /newbot message to the Fatherbot and choose your bot’s name and user name and you will get your API and copy it.
Code your first Telegram Bot in Python
Now, we will quickly jump to the coding part of this tutorial. It is convenient to use a virtual environment (Blogpost/Video) for your project and we would be using python-decouple to save our token key securely instead of hard coding it in the code itself.
Once, you have created a desired folder and activated the virtual environment, you can install the requisite modules using the following command
pip install pyTelegramBotAPI python-decouple
Once, this is done, create a new .env file in the same folder, open it in your favorite editor and add your api-key in it:-
Now, create a new python file and start coding
import telebot from decouple import config #getting the key from .env file API_KEY = config('API') #creating the bot bot = telebot.TeleBot(API_KEY) #passing the 'hello' command to the bot @bot.message_handler(commands=['hello']) #getting the bot to output "Hello!" def hello(message): bot.send_message(message.chat.id, "Hello! I am a bot created by SaralGyaan") #looking out for messages bot.polling()
The code above is self explanatory, now run the python file to start the bot and then open telegram on your phone or device and search for your bot with name or id which you created. For me, it is saralgyaan-bot or saralgyaan_bot. Send ‘/hello’ to your bot to get the reply