Creating a Telegram Bot with Python
Creating a Telegram Bot with Python
Hello friends, in this post I will explain how you can create a bot for telegram using Python. In this article, I will first explain how to create a bot using botfather and then how to receive simple commands and respond to them.
What is Bot Father?
No matter which language you use, if you want to create a bot with Python, especially if you want to do it legally instead of illegally, the first step you need to take is to message botfather on Telegram and create your bot.
To send a message to Bot Father, use the link below and start a chat with @botfather.
When you first message Bot Father, it will show you all the commands you can use.
BotFather Commands
If we need to review these commands, let me explain right away.
/newbot - Allows you to create a new bot.
/mybots - Shows your existing bots and lets you edit them.
Edit Bot
/setname - Allows you to change the name of your existing bot.
/setdescription - Allows you to change the description of your existing bot.
/setuserpic - Allows you to change the profile picture of your existing bot.
/setcommands - Allows you to add and edit a command menu to your existing bot.
/deletebot - Allows you to delete your existing bot.
Bot Settings
/token - Generates a new token for your bot.
/revoke - Revokes access to an existing token for your bot.
/setinline - Enables/disables inline mode./setinlinegeo - Enables/disables location requests.
/setinlinefeedback - Sets feedback.
/setjoingroups - Sets whether the bot can be added to groups.
/setprivacy - Allows you to set privacy settings.
/mygames - Allows you to edit your games.
/newgame - Allows you to create a game.
/listgames - Lists your games.
/editgame - Allows you to edit a game.
/deletegame - Allows you to delete an existing game.
Creating a New Bot Using Bot Father
- First, enter the "/newbot" command in Bot Father to create a bot.
- After the command, we determine and enter our bot's name.
- I entered the name "deneme" in the image above.
- We enter a username for our bot.
- The username is the name that will be called like "@deneme".
- The username must end with "bot" or "Bot".
- The username must not be taken by someone else.
- Above, I tried to get the name "deneme_bot" but since it was taken by someone else, it gave a warning and I took the username "deneme_urhoba_bot".
- After these steps are completed, you will receive a message starting with "Done!" and which will include the "API Key".
- Keep this API Key.
- We will use the API Key to allow our code to communicate with our bot.
Creating a Telegram Bot with Python (Simple)
First, we need to install the telegram bot library written for python. You can use pip to install the telegram bot.
pip install python_telegram_bot # Pythonpip3 install python_telegram_bot # Python 3
We download the telegram library using any of the commands above.
Once the installation is complete, we can now move on to our project codes.
# This project created by urhoba
# www.urhoba.net
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update, ParseMode # We add our telegram library, Update and ParseMode functions allow us to send more detailed messages.
from telegram.ext import * # Library we use to receive, send messages and perform other operations.
def StartCommand(update, context): # Our first command function
# We write our message.
text = f'''
Hello, <b>{update.message.from_user.first_name}</b>
'''
context.bot.send_message(chat_id=update.message.chat_id, text=text, parse_mode=ParseMode.HTML) # We send a message to the user using the bot.
def ErrorExcept(update, context):
# We print the error message to the screen.
print(f"Telegram bot error : Update {update} caused error {context.error}")
def main():
updater = Updater("Bot API", use_context=True) # We create our telegram bot.
dp = updater.dispatcher # We create a dispatcher to catch commands.
dp.add_handler(CommandHandler("start", StartCommand)) # Here we create our first command, the function that will run when "/start" is given.
dp.add_error_handler(ErrorExcept) # Our error catching command, this function is called when an error occurs in the bot.
updater.start_polling(1) # Determines how many seconds the bot should respond and starts the bot.
updater.idle() # We tell the bot to wait to read commands even if no message is sent.
main()
Yes friends, we can create our telegram bot at a very basic level like this. Now, let's see how we can develop a more advanced bot.
Commands/Features We Can Use to Develop the Bot
InlineKeyboardButton
With this feature, you can add buttons to your bot and allow users to interact using these buttons.
# Our command showing the buttons
def ButtonCommand(update, context):
words = ("button1", "button2")
buttons = []
for word in words:
buttons.append([InlineKeyboardButton(word, callback_data=word)]) # InlineKeyboardButton("Text on the button", callback_data="Value returned by the button")
reply_markup = InlineKeyboardMarkup(buttons)
context.bot.send_message(chat_id=update.message.chat_id, text=f"Buttons\n{update.message.text}",
parse_mode=ParseMode.HTML, reply_markup=reply_markup)
# Command to capture the value returned by the button
def ButtonCallBack(update:Update, context):
query = update.callback_query # We get the value returned by the button
query.answer() # We process the value returned by the button
query.message.reply_text(text=query.data, parse_mode=ParseMode.HTML) # We send the value returned by the button as a message
With these functions, we can create and capture the values returned by the buttons. Don't forget to add the command to catch the value returned by the button inside main!
dp.add_handler(CallbackQueryHandler(ButtonCallBack)) # Command to catch command from button
So, all our code should look like this.
# This project created by urhoba
# www.urhoba.net
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update, ParseMode, replymarkup
from telegram.ext import *
from LogManager import LogManager
from Settings import TelegramSettings
def StartCommand(update, context):
text = f'''
Hello, {update.message.from_user.first_name}
'''
context.bot.send_message(chat_id=update.message.chat_id, text=text, parse_mode=ParseMode.HTML)
def ButtonCommand(update, context):
words = ("button1", "button2")
buttons = []
for word in words:
buttons.append([InlineKeyboardButton(word, callback_data=word)]) # InlineKeyboardButton("Text on the button", callback_data="Value returned by the button")
reply_markup = InlineKeyboardMarkup(buttons)
context.bot.send_message(chat_id=update.message.chat_id, text=f"Buttons\n{update.message.text}",
parse_mode=ParseMode.HTML, reply_markup=reply_markup)
def ButtonCallBack(update:Update, context):
query = update.callback_query # We get the value returned by the button
query.answer() # We process the value returned by the button
query.message.reply_text(text=query.data, parse_mode=ParseMode.HTML) # We send the value returned by the button as a message
def ErrorExcept(update, context):
logManager = LogManager("TelegramLog")
logManager.AddLog(f"Telegram bot error : Update {update} caused error {context.error}")
def main():
updater = Updater(TelegramSettings.telegramAPI, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", StartCommand))
dp.add_handler(CommandHandler("button", ButtonCommand)) # Command showing the buttons
dp.add_handler(CallbackQueryHandler(ButtonCallBack)) # Command to catch command from button
dp.add_error_handler(ErrorExcept)
updater.start_polling(1)
updater.idle()
main()
Sending Audio
To make your bot send audio, you can use the command below.
context.bot.send_audio(chat_id=update.message.chat_id, audio=open('seskonumu.mp4', 'rb')) #
Sending Video
If you want your bot to send a video, you can use the command below.
context.bot.send_video(chat_id=update.message.chat_id, video=open('video location.mp4', 'rb'), supports_streaming=True) # here we use the send_video command.
send_video(chat_id.message.chat_id, video=open('video location', 'rb), supports_streaming=True) Once you enter the video location, your bot will send the video.
Yes friends, explaining all the features related to the telegram bot would be very long and also quite complicated for you, but this much should be enough for you.
If it is not enough for you, you can check out this documentation or you can ask me below in the comments.
Sending Echo Message
Update: Friends, I forgot to show echoing, so let me show you this as well.
We create a function for echo and send the incoming message back with this.
def EchoCommand(update, context): context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text, parse_mode=ParseMode.HTML)
The command we need to call inside main to listen for incoming messages continuously for the function above is:
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, EchoCommand))
Now, when the user sends a message, the sent message will be sent back to them.

Yorum Gönder