This report outlines the steps involved in creating a conversational AI Telegram bot using Python.
1. Creating a Telegram Bot:
- Visit the BotFather account on Telegram ([link to BotFather ON Telegram t.me]).
- Use the
/newbotcommand to create a new bot. Follow the prompts to set a name and username. - BotFather will provide a unique token, which is essential for authentication.
2. Setting Up the Python Environment:
- Install the
python-telegram-botlibrary usingpip install python-telegram-bot --upgrade.
3. Writing the Python Code:
- Import necessary libraries like
logging,Update, andCommandHandlerfrom thetelegramandtelegram.extmodules. - Configure logging for informative messages.
- Define an asynchronous function
startthat sends a greeting message when the user types/start. - Within the
__main__block: - Create an application instance using
ApplicationBuilderand provide your bot's token. - Define a command handler for
/startusingCommandHandlerand link it to thestartfunction. - Add the handler to the application.
- Start the bot using
application.run_polling().
4. Integrating the AI Model (placeholder):
- Define an asynchronous function
ai_modelto handle user input and interact with an AI model (placeholder function in the provided code). - This function sends a waiting message and retrieves the user’s message.
- The placeholder
ai_curlfunction (not shown) would typically send a POST request to an AI service with the user's message and receive its response. - The bot then sends the AI’s response back to the user.
Make bot account with https://t.me/BotFather
text
/newbotPython telegram
Install
bash
pip install python-telegram-bot --upgradeSo, let’s get started!. Paste the following into your file:
python
import logging
from telegram
import Update
from telegram.ext
import ApplicationBuilder, ContextTypes, CommandHandlerlogging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)async
def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id,
text="I'm a bot, please talk to me!")if __name__ == '__main__':
application = ApplicationBuilder().token('TOKEN').build() start_handler =
CommandHandler('start', start)
application.add_handler(start_handler) application.run_polling()Replace ‘Token’ with the token you get on the telegram bot.
Add AI part for ask AI model
python
async def ai_model(update: Update, context: ContextTypes.DEFAULT_TYPE): print("please wait") await
context.bot.send_message(chat_id=update.effective_chat.id, text="⚠️ please wait ⚠️") message =
update.message.text ai_response, similar_answer = ai_curl(message) await
context.bot.send_message(chat_id=update.effective_chat.id, text=ai_response)send a Post request to get a response from AI
python
def ai_curl(message : str ) :
my_obj = {'text': message}
x = requests.post(os.environ.get("AI_URL"), json = my_obj)
if x.status_code != 200: print("Error: ", x.status_code) return "Error: " +
str(x.status_code)
json_message = json.loads(x.text)
return json_message['message']Stackademic 🎓
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us X | LinkedIn | YouTube | Discord
- Visit our other platforms: In Plain English | CoFeed | Differ
- More content at Stackademic.com
