import asyncio
from typing import Final
from telegram import Update, ReplyKeyboardRemove, ReplyKeyboardMarkup
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ConversationHandler, filters, ContextTypes
import requests
import threading
import json
import traceback
from datetime import datetime, timedelta
https://api.telegram.org/bot7310735693:AAHoOSQyTjNEk2Q_ctp498kY-LZnuu_x0c8/setWebhook
TOKEN: Final = '7310735693:AAHoOSQyTjNEk2Q_ctp498kY-LZnuu_x0c8'
BOT_USERNAME: Final = 'Medical_insurance_help_bot'
INSURANCE_API_KEY: Final = 'https://uatapigw.tataaig.com/bolt/quotation/create'
States for the conversation
PLAN_TYPE, TENURE, MEMBER_DETAILS, MEMBER_ADDITIONAL, PINCODE, DOB,RELATIONSHIP, SUM_INSURED = range(8)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
context.user_data.clear()
await update.message.reply_text(f'Hi {update.effective_user.first_name}! I am your bot. Please enter correct details!')
await update.message.reply_text(
'Select the plan type you want:',
reply_markup=ReplyKeyboardMarkup([['Individual', 'Floater']], one_time_keyboard=True,resize_keyboard=True)
)
return PLAN_TYPE
async def ask_planType(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
plan_type = update.message.text
context.user_data['planType'] = plan_type
await update.message.reply_text('Great! What is the tenure of the insurance (in years)?',
reply_markup=ReplyKeyboardMarkup([['1', '2', '3']], one_time_keyboard=True,resize_keyboard=True))
return TENURE
async def ask_tenure(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
tenure = update.message.text
context.user_data['tenure'] = tenure
await update.message.reply_text('Please provide the pincode of the location where the insurance is being held.')
return PINCODE
async def ask_pincode(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
pincode = update.message.text
try:
if not (pincode.isdigit() and len(pincode) == 6):
raise ValueError("Invalid PinCode")
async def ask_sum_insured(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
sum_insured = update.message.text
context.user_data['sum_insured'] = sum_insured
await update.message.reply_text('Please provide the age of the insured member.')
return DOB
async def ask_dob(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
age = int(update.message.text)
today = datetime.today()
dob = (today - timedelta(days=age*365)).strftime("%d/%m/%Y")
async def ask_relationship(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
relationship = update.message.text
members = context.user_data.get('members', [])
members.append({
'sumInsured': int(context.user_data['sum_insured']),
'dob': context.user_data['dob'],
'relationship': relationship
})
context.user_data['members'] = members
if context.user_data['planType'] == 'Floater':
await update.message.reply_text('Add another member?',reply_markup=ReplyKeyboardMarkup([['yes', 'no']], one_time_keyboard=True,resize_keyboard=True))
return MEMBER_ADDITIONAL
else:
await process_insurance_request(update, context)
return ConversationHandler.END
async def ask_member_details(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
member_details = update.message.text.split(',')
members = context.user_data.get('members', [])
members.append({
'sumInsured': int(member_details[0].strip()) if member_details[0].strip().isdigit() else member_details[0].strip(),
'dob': member_details[1].strip(),
'relationship': member_details[2].strip()
})
context.user_data['members'] = members
await update.message.reply_text('Do you want to add another member? (yes/no)')
return MEMBER_ADDITIONAL
async def ask_member_additional(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
if context.user_data['planType'] == 'Floater' and update.message.text.lower() == 'yes':
await update.message.reply_text('Please provide the age of the insured member.')
return DOB
else:
await process_insurance_request(update, context)
return ConversationHandler.END
async def process_insurance_request(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
Authorization_KEY = get_authorization_key()
planType = context.user_data['planType']
tenure = int(context.user_data['tenure'])
members = context.user_data['members']
pincode = context.user_data['pincode']
proposer = {
"address": {
"pincode": pincode
}
}
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text('Operation cancelled.', reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
print(f'Update {update} caused error {context.error}')
await update.message.reply_text('Some error Occured,Please try again later.', reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
def get_authorization_key():
url = "https://uatapigw-tataaig.auth.ap-south-1.amazoncognito.com/oauth2/token"
headers = {
"x-api-key": "7nrFvEjIjd4aEhu2ZmF58a6pRzVxgXdZ2e0vlTtz",
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": "XSRF-TOKEN=a766ca90-8e03-4348-a34d-146fddf3847b"
}
payload = {
"grant_type": "client_credentials",
"client_id": "5kbhlcpqk9f3kdrse0f1f0qneq",
"client_secret": "alokjlvkata1nrdsek4b69et5vief4jjk3jk8miuitsshgdrqf5",
"scope": "https://uatapigw.tataaig.com/write"
}
print('Starting bot...')
thread = threading.Thread(target=get_authorization_key)
thread.start()
application = ApplicationBuilder().token(TOKEN).build()
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
PLAN_TYPE: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_planType)],
TENURE: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_tenure)],
PINCODE: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_pincode)],
SUM_INSURED: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_sum_insured)],
DOB: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_dob)],
RELATIONSHIP: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_relationship)],
MEMBER_DETAILS: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_member_details)],
MEMBER_ADDITIONAL: [MessageHandler(filters.TEXT & ~filters.COMMAND, ask_member_additional)]
},
fallbacks=[CommandHandler('cancel', cancel),CommandHandler('start', start)]
)
application.add_handler(conv_handler)
application.add_error_handler(error)
application.run_polling()
async def bot_main(application,event):
async with application:
await application.process_update(
Update.de_json(json.loads(event['body']), application.bot)
)
def lambda_handler(event, context):
try:
application.setWebhook('https://api.telegram.org/bot7310735693:AAHoOSQyTjNEk2Q_ctp498kY-LZnuu_x0c8/setWebhook?url=https://8azdnictdb.execute-api.ap-south-1.amazonaws.com/default/telegram-webhook-test')
asyncio.run(bot_main(application,event))
except Exception as e:
traceback.print_exc()
print(e)
return{"statusCode":500}