import telebot import requests from bs4 import BeautifulSoup import time import json #…
- User
import telebot import requests from bs4 import BeautifulSoup import time import json # For persistent storage
Replace with your bot token
BOT_TOKEN = "7653489072:AAHb1LLCqlr92ZmmnkCDbbUkqrbgwjbyctk" bot = telebot.TeleBot(BOT_TOKEN)
Avito search URL (replace with your query)
AVITO_SEARCH_URL = "https://www.avito.ru/sankt-peterburg/telefony/mobilnye_telefony/apple/iphone_15_pro_max-ASgBAgICA0SywA3Woe0RtMANzqs5sMENiPw3?cd=1"
File to store processed ads
PROCESSED_ADS_FILE = "processed_ads.json"
def load_processed_ads(): """Loads processed ads from a JSON file.""" try: with open(PROCESSED_ADS_FILE, "r") as f: return set(json.load(f)) except (FileNotFoundError, json.JSONDecodeError): return set()
def save_processed_ads(ads): """Saves processed ads to a JSON file.""" with open(PROCESSED_ADS_FILE, "w") as f: json.dump(list(ads), f)
processed_ads = load_processed_ads()
def get_avito_ads(url): """Gets a list of ads from Avito.""" try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.content, "html.parser") ads = soup.find_all("div", class_="iva-item-content-rejJg") # Class might change!
ad_list = [] for ad in ads: title_element = ad.find("a", class_="iva-item-title-link") if title_element: #Check if element exists to avoid AttributeError title = title_element.text.strip() price_element = ad.find("meta", {"itemprop": "price"}) price = price_element.get("content") if price_element else "N/A" #Handle missing price link = title_element.get("href") ad_list.append({"title": title, "price": price, "link": link}) return ad_list except requests.exceptions.RequestException as e: print(f"Error requesting Avito: {e}") return [] except Exception as e: print(f"Error parsing Avito: {e}") return []def send_new_ads(chat_id): """Sends new ads to Telegram.""" ads = get_avito_ads(AVITO_SEARCH_URL) new_ads = [] for ad in ads: ad_id = ad['link'] if ad_id not in processed_ads: new_ads.append(ad) processed_ads.add(ad_id)
if new_ads: for ad in new_ads: message = f"<b>{ad['title']}</b>\nЦена: {ad['price']}\nСсылка: {ad['link']}" bot.send_message(chat_id, message, parse_mode="HTML") save_processed_ads(processed_ads) #Save after sending@bot.message_handler(commands=['start']) def start(message): chat_id = message.chat.id bot.send_message(chat_id, "Бот запущен. Буду следить за новыми объявлениями на Avito.") # Add the chat ID to a list of users to monitor. Could use a database for better scalability. # For simplicity we'll just store in memory here. In reality, you'd use a database.
- Assistant
- User
Error requesting Avito: 403 Client Error: Forbidden for url: https://www.avito.ru/sankt-peterburg/telefony/mobilnye_telefony/apple/iphone_15_pro_max-ASgBAgICA0SywA3Woe0RtMANzqs5sMENiPw3?cd=1
- Assistant