Good morning chatgtp, I want my current program to achieve the following: 1) The…
- User
Good morning chatgtp, I want my current program to achieve the following: 1) The telegram bot should have a prompt back to ask the user for the a specific telegram number to set the Bot to perform checks on . Hence the line asyncio.run(search_and_display("ITE000ETQ23000193")) , the "ITE000ETQ23000193" is the tender number that needs to be changed by the telegram bot prompt of the user. 2) I am thinking of having error handling on the telegram bot as well to detect tender numbers that the user give that may be invalid as well like after not identifying the or achieveing the results, the message on telegram tells the user it is not avaliable or something like that. 3) I want the telegram bot to have welcome screen guiding the user to 2 options - 1st option Change Tender Number to check 2nd option Check tender number. The 2nd option is set activate everyday @ 9am so we would still need it notify without the welcome screen. There's where I have no idea how to deal with that. The problem is this: I want to display status @ 9am still and the user can have the option to change or view now as well (2options) also instead of 9am. Any ideas how to? My code now: import os from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time from telegram import Bot from telegram.ext import Updater, CommandHandler, CallbackContext import asyncio from datetime import datetime
ANSI escape codes for text colors
COLOR_RED = '\033[91m' COLOR_GREEN = '\033[92m' COLOR_YELLOW = '\033[93m' COLOR_BLUE = '\033[94m' COLOR_RESET = '\033[0m'
Specify the path to your OneDrive folder
ONE_DRIVE_FOLDER = r'C:\Users\chinsoont.BECKHOFF\OneDrive - Singapore Polytechnic'
Telegram bot token
TELEGRAM_BOT_TOKEN = '6540947414:AAGVoA9X-vw-Uq1b1YqLvTH8YkQX1UlfNkU' DEFAULT_CHAT_ID = '1471225821' # Replace with your default chat ID OTHER_CHAT_ID = '1471225821' # Replace with another chat ID
async def notify_on_telegram(search_term, status_text, awarded_to, award_value, award_date, recipient_chat_id=None): bot = Bot(token=TELEGRAM_BOT_TOKEN)
# If recipient_chat_id is None, use the default chat ID chat_id = recipient_chat_id if recipient_chat_id else DEFAULT_CHAT_ID # Message formatting for better clarity (e.g., bolding the status_text) message = f"Status update for tender {search_term}:\n\n<b>{status_text}</b>\n\nAwarded to: {awarded_to}\nAward Value: {award_value}\nAward Date: {award_date}\n\nLast Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" # Use parse_mode='HTML' to enable text formatting (e.g., bold) await bot.send_message(chat_id=chat_id, text=message, parse_mode='HTML')async def search_and_display(search_term):
# Set the path to your webdriver (replace with the actual path to your chromedriver.exe) webdriver_path = r'C:\Users\chinsoont.BECKHOFF\Downloads' # Set the webdriver path using the executable_path argument chrome_options = webdriver.ChromeOptions() chrome_options.add_argument(f'--webdriver={webdriver_path}') # Add the following line to run Chrome in headless mode #chrome_options.add_argument('--headless') driver = webdriver.Chrome(options=chrome_options) url = 'https://www.gebiz.gov.sg/' # Open the website in the browser driver.get(url) # Wait for a few seconds to let the page load (you might need to adjust the wait time) time.sleep(0.2) checkbox_title = driver.find_element(By.ID, 'contentForm:j_id55_0') checkbox_title.click() # Find the search input field and submit a query search_input = driver.find_element(By.CSS_SELECTOR, 'input[name="contentForm:searchBar_searchBar_INPUT-SEARCH"]') search_input.send_keys(search_term) search_input.send_keys(Keys.RETURN) # Wait for a few seconds to let the search results load (you might need to adjust the wait time) time.sleep(0.5) wait = WebDriverWait(driver, 10) try: # Using XPath to locate the status element based on its class status_element = wait.until(EC.presence_of_element_located(( By.XPATH, '//div[@class="label_MAIN label_WHITE-ON-GRAY" or ' '(@class="label_MAIN label_WHITE-ON-GREEN" and text()="AWARDED") or ' '(@class="label_MAIN label_WHITE-ON-GRAY" and text()="OPEN") or ' '(@class="label_MAIN label_WHITE-ON-LIGHT-GRAY" and (text()="CLOSED" or ' 'text()="CANCELLED" or text()="NO AWARD"))]' ))) # Check if all elements are found status_text = status_element.text.strip() # Replace "\n" with a space in the output status_text = status_text.replace("\n", " ") # Using XPath to locate the additional elements for Awarded To, Award Value, and Award Date subtitle_elements = wait.until(EC.presence_of_all_elements_located(( By.XPATH, "//div[@class='formOutputText_HIDDEN-LABEL outputText_SUBTITLE-BLACK' and @style='text-align: left;']" ))) # Initialize variables for Awarded To, Award Value, and Award Date awarded_to = None award_value = None award_date = None # Loop through subtitle elements to dynamically assign values to columns for index, subtitle_element in enumerate(subtitle_elements): text = subtitle_element.text.strip() if index == 0: awarded_to = text elif index == 1: award_value = text elif index == 2: award_date = text # Notify on Telegram to the default chat ID await notify_on_telegram(search_term, status_text, awarded_to, award_value, award_date) # Notify on Telegram to another chat ID await notify_on_telegram(search_term, status_text, awarded_to, award_value, award_date, OTHER_CHAT_ID) except Exception as e: print(f"{COLOR_RED}An error occurred: {e}{COLOR_RESET}") # Close the browser driver.quit()def start_telegram_bot(): updater = Updater(TELEGRAM_BOT_TOKEN)
# Get the dispatcher to register handlers dp = updater.dispatcher # Start the Bot updater.start_polling() # Run the bot until you send a signal to stop (Ctrl+C) updater.idle()def start_menu(): asyncio.run(search_and_display("ITE000ETQ23000193"))
if name == "main": start_menu()
- Assistant
Your current use case involves quite a few different aspects, so let's walk through each of them and see how we might modify your existing code to meet your requirements.
-
Prompting the user for a tender number: You will need to use Telegram's
ConversationHandlerto create an interactive dialogue with the user. The user will be prompted to enter a tender number, which you will then pass to thesearch_and_displayfunction. -
Error handling for invalid tender numbers: You will need to determine what counts as an invalid tender number and catch exceptions or perform checks in your
search_and_displayfunction to inform the user accordingly. -
A welcome message with options and automated checking: You'll want a way to send a welcome message that presents users with options. The automated check at 9 am can be achieved by using Python's
scheduleorAPSchedulerlibraries.
The following code will serve as a rough outline, and you will have to fill in specific actions and details:
from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackContext import schedule import time CHOOSING, TENDER_NUMBER = range(2) def start(update: Update, context: CallbackContext) -> int: reply_keyboard = [['Change Tender Number', 'Check Tender Number']] update.message.reply_text( 'Welcome! Choose an option:', reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True), ) return CHOOSING def change_tender_number(update: Update, context: CallbackContext) -> int: update.message.reply_text( 'Please send me the tender number you would like to check.', reply_markup=ReplyKeyboardRemove(), ) return TENDER_NUMBER def check_tender_number(update: Update, context: CallbackContext) -> int: # Perform the check here or pass to separate function # ... return ConversationHandler.END def received_tender_number(update: Update, context: CallbackContext) -> int: user_text = update.message.text # Run search_and_display with provided tender number, handle exceptions here # ... return ConversationHandler.END def scheduled_check(): # Function to perform the scheduled check, no prompting # You could schedule this function like: schedule.every().day.at("09:00").do(lambda: asyncio.run(search_and_display("DefaultTenderNumber"))) # You would need to run a loop to keep checking for scheduled tasks: # while True: # schedule.run_pending() # time.sleep(1) def main(): updater = Updater(TELEGRAM_BOT_TOKEN) dp = updater.dispatcher conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ CHOOSING: [ MessageHandler(Filters.regex('^Change Tender Number$'), change_tender_number), MessageHandler(Filters.regex('^Check Tender Number$'), check_tender_number) ], TENDER_NUMBER: [MessageHandler(Filters.text & ~Filters.command, received_tender_number)] }, fallbacks=[CommandHandler('start', start)] ) dp.add_handler(conv_handler) updater.start_polling() # Start the schedule loop threading.Thread(target=scheduled_check).start() updater.idle() if __name__ == '__main__': main()You will need to adjust the
search_and_displayfunction to return error messages or the result string to be used in the message after you have determined how to identify invalid tender numbers. Additional error handling might be needed based on the potential exceptions raised by your code.Moreover, to run scheduled jobs, you'll need to start a separate thread that checks for and runs scheduled events, since
schedule.run_pending()needs to be called in a loop for the checks to be performed at the scheduled time. Alternatively, you could use theAPSchedulerlibrary, which handles threading internally.Please replace
THREADING_MODULEwith the appropriate threading library import, and ensure you handle it correctly within the context of an async application.Note: Asynchronous programming patterns like those used with
asynciomight require you to adjust some parts to work without issues, particularly regarding the thread that runs alongside the async event loop. Please make sure to appropriately adapt the provided pseudo-code to fit into your program's async structure. -