import os import requests from bs4 import BeautifulSoup from telegram import Bot # Function to load environment variables from .env file def load_env(): with open('.env', 'r') as file: for line in file: if line.strip() and not line.startswith('#'): key, value = line.strip().split('=', 1) os.environ[key] = value # Function to retrieve webpage contents and count occurrences of the keyword def count_keyword_occurrences(url, keyword): try: # Retrieve webpage contents response = requests.get(url) response.raise_for_status() # Raise an HTTPError for bad responses html_content = response.text # Count occurrences of the keyword in the HTML content occurrences = html_content.lower().count(keyword.lower()) return occurrences except Exception as e: print(f"An error occurred: {e}") return 0 # Function to send a Telegram message async def send_telegram_message(api_token, chat_id, message): try: bot = Bot(token=api_token) response = await bot.send_message(chat_id=chat_id, text=message) print(f"Telegram message sent successfully. Message ID: {response.message_id}") except Exception as e: print(f"An error occurred while sending Telegram message: {e}") if __name__ == "__main__": # Load environment variables from .env file load_env() # Retrieve variables from environment variables url_to_check = os.getenv("URL_TO_CHECK") telegram_api_token = os.getenv("TELEGRAM_API_TOKEN") telegram_chat_id = os.getenv("TELEGRAM_CHAT_ID") search_keyword = os.getenv("SEARCH_KEYWORD") # Count occurrences of the keyword on the webpage keyword_occurrences = count_keyword_occurrences(url_to_check, search_keyword) # Define the message based on the occurrences if keyword_occurrences > 0: message = f"The word '{search_keyword}' was found {keyword_occurrences} times on {url_to_check}. Sending Telegram message." # Send the message to Telegram import asyncio asyncio.run(send_telegram_message(telegram_api_token, telegram_chat_id, message)) else: print(f"The word '{search_keyword}' was found {keyword_occurrences} times on {url_to_check}. Not sending Telegram message.")