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")

⎗
✓
1
2
3
4
5
6
    context.user_data['pincode'] = pincode
    await update.message.reply_text('Please provide the sumInsured.')
    return SUM_INSURED
except ValueError:
    await update.message.reply_text("Please enter a valid pincode")
    return 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")

⎗
✓
# Store the date of birth in the context
context.user_data['dob'] = dob
if context.user_data['planType'] == 'Floater':
    keyboard = [
        ['Self', 'Spouse'],
        ['Mother', 'Father'],
        ['Son', 'Daughter']
    ]
    await update.message.reply_text('Please provide the relationship of the insured member.',
                                    reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True))
    return RELATIONSHIP
else:
    members = context.user_data.get('members', [])
    members.append({
        'sumInsured': int(context.user_data['sum_insured']),
        'dob': context.user_data['dob'],
        'relationship': 'Self'
    })
    context.user_data['members'] = members
    await process_insurance_request(update, context)
    return ConversationHandler.END

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
}
}

⎗
✓
headers = {
    "x-api-key": "7nrFvEjIjd4aEhu2ZmF58a6pRzVxgXdZ2e0vlTtz",
    "Content-Type": "application/json",
    "Authorization": Authorization_KEY
}
payload = {
    "producerCode": "8826000979",
    "tenure": tenure,
    "ipAddress": "1.2.3.4",
    "memberDetails": members,
    "source": "TATA-AIG",
    "proposer": proposer,
    'portability': False,
    'isEmployee': False,
    'planType': planType,
    'branchLocation': 'CHENNAI'
}
print(payload)
await update.message.reply_text('Searching for you....')
response = requests.post(INSURANCE_API_KEY, headers=headers, json=payload)
response_json = response.json()
data = response_json.get('data', {})
# print(data)
if response.status_code == 200:
    if not data:
        await update.message.reply_text('No premium price found. Please try again later.')
        ConversationHandler.END
    else:
        premium_product_dict = {}
        quotes = data.get('quotes', [])
        for quote in quotes:
            productName = quote.get('productName')
            premium_price = quote.get('premium')
            premium_product_dict[premium_price] = productName
        if len(quotes) <= 1:
            stri = 'plan'
        else:
            stri = 'plans'
        await update.message.reply_text(f'Hey, We have {len(quotes)} premium {stri}.')
        sorted_premiums = sorted(premium_product_dict.keys())
        for i, premium in enumerate(sorted_premiums, start=1):
            productName = premium_product_dict[premium]
            await update.message.reply_text(f'{i}. Product Name: {productName}, Premium Price: {premium_price}.')
            return ConversationHandler.END
else:
    await update.message.reply_text('Something went wrong. Please try again later.')
    return ConversationHandler.END

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"
}

⎗
✓
1
2
3
4
5
6
7
8
response = requests.post(url, headers=headers, data=payload)
if response.status_code == 200:
    return response.json().get('access_token')
else:
    print("Failed to get authorization key:")
    print(response.status_code)
    print(response.text)
    return None

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}

⎗
✓
return {"statusCode":200}

test_event = {

"body": json.dumps({

"update_id": 123456789,

"message": {

"message_id": 123,

"from": {

"id": 1111111,

"is_bot": False,

"first_name": "Test",

"username": "test_user",

"language_code": "en"

},

"chat": {

"id": 1111111,

"first_name": "Test",

"username": "test_user",

"type": "private"

},

"date": 1609459200,

"text": "/start"

}

})

}

lambda_handler(test_event,None)

Edit

Pub: 05 Jun 2024 05:09 UTC

Views: 21