forked from ehcaning/divar-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
174 lines (142 loc) · 4.86 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import datetime
import json
import os
import time
import requests
import telegram
from pydantic import BaseModel
import asyncio
URL = "https://api.divar.ir/v8/web-search/{SEARCH_CONDITIONS}".format(**os.environ)
BOT_TOKEN = "{BOT_TOKEN}".format(**os.environ)
BOT_CHATID = "{BOT_CHATID}".format(**os.environ)
SLEEP_SEC = "{SLEEP_SEC}".format(**os.environ)
proxy_url = None
if os.environ.get("PROXY_URL", ""):
proxy_url = os.environ.get("PROXY_URL")
TOKENS = list()
# setup telegram bot client
req_proxy = telegram.request.HTTPXRequest(proxy_url=proxy_url)
bot = telegram.Bot(token=BOT_TOKEN, request=req_proxy)
# AD class model
class AD(BaseModel):
title: str
price: int
description: str = ""
district: str
images: list[str] = []
token: str
def get_data(page=None):
api_url = URL
if page:
api_url += f"&page={page}"
response = requests.get(api_url)
print("{} - Got response: {}".format(datetime.datetime.now(), response.status_code))
return response.json()
def get_ads_list(data):
return data["web_widgets"]["post_list"]
def fetch_ad_data(token: str) -> AD:
# send request
data = requests.get(f"https://api.divar.ir/v8/posts-v2/web/{token}").json()
images = []
# check post exists
if not "sections" in data:
return None
# get data
for section in data["sections"]:
# find title section
if section["section_name"] == "TITLE":
title = section["widgets"][0]["data"]["title"]
# find images section
if section["section_name"] == "IMAGE":
images = section["widgets"][0]["data"]["items"]
images = [img["image"]["url"] for img in images]
# find description section
if section["section_name"] == "DESCRIPTION":
description = section["widgets"][1]["data"]["text"]
# get district
district = data["seo"]["web_info"]["district_persian"]
price = data["webengage"]["price"]
# create ad object
ad = AD(
token=token,
title=title,
district=district,
description=description,
images=images,
price=price,
)
return ad
async def send_telegram_message(ad: AD):
text = f"🗄 <b>{ad.title}</b>" + "\n"
text += f"📌 محل آگهی : <i>{ad.district}</i>" + "\n"
_price = f"{ad.price:,} تومان" if ad.price else "توافقی"
text += f"💰 قیمت : {_price}" + "\n\n"
text += f"📄 توضیحات :\n{ad.description}" + "\n"
text += f"https://divar.ir/v/a/{ad.token}"
# send single photo
if len(ad.images) == 1:
await bot.send_photo(
caption=text, photo=ad.images[0], chat_id=BOT_CHATID, parse_mode="HTML"
)
# send album
elif len(ad.images) > 1:
_media_list = [telegram.InputMediaPhoto(img) for img in ad.images[:10]]
try:
await bot.send_media_group(
caption=text, media=_media_list, chat_id=BOT_CHATID, parse_mode="HTML"
)
except telegram.error.BadRequest as e:
print("Error sending photos :", e)
return
else:
# send just text
await bot.send_message(text=text, chat_id=BOT_CHATID, parse_mode="HTML")
def load_tokens():
token_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "tokens.json"
)
with open(token_path, "r") as content:
if content == "":
return []
return json.load(content)
def save_tokns(tokens):
token_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "tokens.json"
)
with open(token_path, "w") as outfile:
json.dump(tokens, outfile)
def get_tokens_page(page=None):
data = get_data(page)
data = get_ads_list(data)
data = data[::-1]
# get tokens
data = filter(lambda x: x["widget_type"] == "POST_ROW", data)
tokens = list(map(lambda x: x["data"]["token"], data))
return tokens
async def process_data(tokens):
for token in tokens:
# get the ad data
ad = fetch_ad_data(token)
if not ad:
continue
print("AD - {} - {}".format(token, vars(ad)))
# send message to telegram
print("sending to telegram token: {}".format(ad.token))
await send_telegram_message(ad)
time.sleep(1)
if __name__ == "__main__":
print("Started at {}.".format(datetime.datetime.now()))
tokens = load_tokens()
print("Tokens length: {}".format(len(tokens)))
pages = [""]
while True:
for page in pages:
# get new tokens list
tokens_list = get_tokens_page(page)
# remove repeated tokens
tokens_list = list(filter(lambda t: not t in tokens, tokens_list))
tokens = list(set(tokens_list + tokens))
asyncio.run(process_data(tokens_list))
# save new tokens
save_tokns(tokens)
time.sleep(int(SLEEP_SEC))