import telegram

from telegram.ext import Updater, MessageHandler, Filters, ConversationHandler
from urllib.parse import urlparse, parse_qs, urlencode, quote
import urllib.parse
import re
from bs4 import BeautifulSoup
import requests
from requests.exceptions import HTTPError
import time
import csv

TOKEN = '5942635780:AAGAqf-_Y-uC2EMnigv6wDwZpH0eJczdQAE'
bot = telegram.Bot(token=TOKEN)
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher

# Define the states for the conversation
ENTER_PRICE = range(1)

def handle_url(update, context):
url = update.message.text
print("Submit By User", url)

context.bot.send_message(chat_id=update.message.chat_id, text="Working on URL")

myheaders = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}

page = requests.get(url, headers=myheaders)
print(page.status_code)
soup = BeautifulSoup(page.content, "html.parser")

maindiv = soup.find('div', id="apex_desktop")
pricediv1 = maindiv.find('div', id="corePriceDisplay_desktop_feature_div")
price1 = pricediv1.find('span', {'class': 'a-price-whole'}).text.replace("₹","")

print("Price 1:", price1)

# Store the url and price1 in user_data
context.user_data['url'] = url
context.user_data['price1'] = price1

# Prompt user to enter another price
context.bot.send_message(chat_id=update.message.chat_id, text="Enter another price:")
return ENTER_PRICE

def handle_price(update, context):
# Retrieve the second price
price2 = update.message.text
print("Price 2:", price2)

# Append the link and prices to a list
data = [(context.user_data['url'], context.user_data['price1'], price2)]

# Write the list to a CSV file
with open('/Users/jitendersingh/Documents/prices.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)

context.bot.send_message(chat_id=update.message.chat_id, text="The prices have been saved to the CSV file.")
return ConversationHandler.END

def cancel(update, context):
context.bot.send_message(chat_id=update.message.chat_id, text="The conversation has been cancelled.")
return ConversationHandler.END

# Define the conversation handler
conv_handler = ConversationHandler(
entry_points=[MessageHandler(Filters.text & (~Filters.command), handle_url)],
states={
ENTER_PRICE: [MessageHandler(Filters.text & (~Filters.command), handle_price)],
},
fallbacks=[],
)
dispatcher.add_handler(conv_handler)

updater.start_polling()

0 comments:

Post a Comment

 
Top