Skip to content

Commit 33fd9af

Browse files
committed
v0.1.16.6 - removed plugin handlers, greeting only in new chats, side
1 parent 28aefdb commit 33fd9af

File tree

11 files changed

+89
-23
lines changed

11 files changed

+89
-23
lines changed

FunPayAPI/account.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,8 @@ def get_subcategory_public_lots(self, subcategory_type: enums.SubCategoryTypes,
304304
description = description.text if description else None
305305
server = offer.find("div", class_="tc-server")
306306
server = server.text if server else None
307+
side = offer.find("div", class_="tc-side")
308+
side = side.text if side else None
307309
tc_price = offer.find("div", {"class": "tc-price"})
308310
if subcategory_type is types.SubCategoryTypes.COMMON:
309311
price = float(tc_price["data-s"])
@@ -344,7 +346,8 @@ def get_subcategory_public_lots(self, subcategory_type: enums.SubCategoryTypes,
344346
if i in attributes:
345347
del attributes[i]
346348

347-
lot_obj = types.LotShortcut(offer_id, server, description, amount, price, currency, subcategory_obj, seller,
349+
lot_obj = types.LotShortcut(offer_id, server, side, description, amount, price, currency, subcategory_obj,
350+
seller,
348351
auto, promo, attributes, str(offer))
349352
result.append(lot_obj)
350353
return result
@@ -387,6 +390,8 @@ def get_my_subcategory_lots(self, subcategory_id: int,
387390
description = description.text if description else None
388391
server = offer.find("div", class_="tc-server")
389392
server = server.text if server else None
393+
side = offer.find("div", class_="tc-side")
394+
side = side.text if side else None
390395
tc_price = offer.find("div", class_="tc-price")
391396
price = float(tc_price["data-s"])
392397
if currency is None:
@@ -398,7 +403,7 @@ def get_my_subcategory_lots(self, subcategory_id: int,
398403
amount = tc_amount.text.replace(" ", "") if tc_amount else None
399404
amount = int(amount) if amount and amount.isdigit() else None
400405
active = "warning" not in offer.get("class", [])
401-
lot_obj = types.MyLotShortcut(offer_id, server, description, amount, price, currency, subcategory_obj,
406+
lot_obj = types.MyLotShortcut(offer_id, server, side, description, amount, price, currency, subcategory_obj,
402407
auto, active, str(offer))
403408
result.append(lot_obj)
404409
return result
@@ -1113,6 +1118,8 @@ def get_user(self, user_id: int, locale: Literal["ru", "en", "uk"] | None = None
11131118
description = description.text if description else None
11141119
server = j.find("div", class_="tc-server")
11151120
server = server.text if server else None
1121+
side = j.find("div", class_="tc-side")
1122+
side = side.text if side else None
11161123
auto = j.find("i", class_="auto-dlv-icon") is not None
11171124
tc_price = j.find("div", {"class": "tc-price"})
11181125
tc_amount = j.find("div", class_="tc-amount")
@@ -1126,7 +1133,8 @@ def get_user(self, user_id: int, locale: Literal["ru", "en", "uk"] | None = None
11261133
currency = parse_currency(tc_price.find("span", class_="unit").text)
11271134
if self.currency != currency:
11281135
self.currency = currency
1129-
lot_obj = types.LotShortcut(offer_id, server, description, amount, price, currency, subcategory_obj,
1136+
lot_obj = types.LotShortcut(offer_id, server, side, description, amount, price, currency,
1137+
subcategory_obj,
11301138
None, auto,
11311139
None, None, str(j))
11321140
user_obj.add_lot(lot_obj)

FunPayAPI/types.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -953,6 +953,9 @@ class LotShortcut:
953953
:param server: название сервера (если указан в лоте).
954954
:type server: :obj:`str` or :obj:`None`
955955
956+
:param side: название стороны (если указана в лоте).
957+
:type side: :obj:`str` or :obj:`None`
958+
956959
:param description: краткое описание (название) лота.
957960
:type description: :obj:`str` or :obj:`None`
958961
@@ -969,7 +972,7 @@ class LotShortcut:
969972
:type html: :obj:`str`
970973
"""
971974

972-
def __init__(self, id_: int | str, server: str | None,
975+
def __init__(self, id_: int | str, server: str | None, side: str | None,
973976
description: str | None, amount: int | None, price: float, currency: Currency,
974977
subcategory: SubCategory | None,
975978
seller: SellerShortcut | None, auto: bool, promo: bool | None, attributes: dict[str, int | str] | None,
@@ -980,6 +983,8 @@ def __init__(self, id_: int | str, server: str | None,
980983
"""ID лота."""
981984
self.server: str | None = server
982985
"""Название сервера (если указан)."""
986+
self.side: str | None = side
987+
"""Сторона (если указана)."""
983988
self.description: str | None = description
984989
"""Краткое описание (название) лота."""
985990
self.title: str | None = description
@@ -1017,6 +1022,9 @@ class MyLotShortcut:
10171022
:param server: название сервера (если указан в лоте).
10181023
:type server: :obj:`str` or :obj:`None`
10191024
1025+
:param side: название стороны (если указана в лоте).
1026+
:type side: :obj:`str` or :obj:`None`
1027+
10201028
:param description: краткое описание (название) лота.
10211029
:type description: :obj:`str` or :obj:`None`
10221030
@@ -1033,7 +1041,7 @@ class MyLotShortcut:
10331041
:type html: :obj:`str`
10341042
"""
10351043

1036-
def __init__(self, id_: int | str, server: str | None,
1044+
def __init__(self, id_: int | str, server: str | None, side: str | None,
10371045
description: str | None, amount: int | None, price: float, currency: Currency,
10381046
subcategory: SubCategory | None, auto: bool, active: bool,
10391047
html: str):
@@ -1043,6 +1051,8 @@ def __init__(self, id_: int | str, server: str | None,
10431051
"""ID лота."""
10441052
self.server: str | None = server
10451053
"""Название сервера (если указан)."""
1054+
self.side: str | None = side
1055+
"""Сторона (если указана)."""
10461056
self.description: str | None = description
10471057
"""Краткое описание (название) лота."""
10481058
self.title: str | None = description

FunPayAPI/updater/runner.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,6 @@ def __init__(self, account: Account, disable_message_requests: bool = False,
8686
"""Экземпляр аккаунта, к которому привязан Runner."""
8787
self.account.runner = self
8888

89-
self.__msg_time_re = re.compile(r"\d{2}:\d{2}")
90-
9189
def get_updates(self) -> dict:
9290
"""
9391
Запрашивает список событий FunPay.

Utils/config_loader.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ def load_main_config(config_path: str):
108108

109109
"Greetings": {
110110
"ignoreSystemMessages": ["0", "1"],
111+
"onlyNewChats": ["0", "1"],
111112
"sendGreetings": ["0", "1"],
112113
"greetingsText": "any",
113114
"greetingsCooldown": "any"
@@ -220,6 +221,11 @@ def load_main_config(config_path: str):
220221
config.set(section_name, param_name, "🐦")
221222
with open("configs/_main.cfg", "w", encoding="utf-8") as f:
222223
config.write(f)
224+
elif section_name == "Greetings" and param_name == "onlyNewChats" and param_name not in config[
225+
section_name]:
226+
config.set("Greetings", "onlyNewChats", "0")
227+
with open("configs/_main.cfg", "w", encoding="utf-8") as f:
228+
config.write(f)
223229

224230
# END OF UPDATE
225231

cardinal.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,14 @@ def __init__(self, main_config: ConfigParser,
146146
self.profile_last_tag: str | None = None
147147
# Тег последнего event'а, после которого обновлялось состояние лотов.
148148
self.last_state_change_tag: str | None = None
149+
# Тег последнего event'а, перед которым пороговое значение для определения новых чатов.
150+
self.last_greeting_chat_id_threshold_change_tag: str | None = None
151+
self.greeting_threshold_chat_ids = set() # ID чатов для последующего обновления self.greeting_chat_id_threshold
149152
self.blacklist = cardinal_tools.load_blacklist() # ЧС.
150153
self.old_users = cardinal_tools.load_old_users(
151154
float(self.MAIN_CFG["Greetings"]["greetingsCooldown"])) # Уже написавшие пользователи.
155+
self.greeting_chat_id_threshold = max(self.old_users.keys(), default=0)
156+
# пороговое значение для определения новых чатов (для приветствия)
152157

153158
# Хэндлеры
154159
self.pre_init_handlers = []
@@ -853,7 +858,8 @@ def run_handlers(self, handlers_list: list[Callable], args) -> None:
853858
"""
854859
for func in handlers_list:
855860
try:
856-
if getattr(func, "plugin_uuid") is None or self.plugins[getattr(func, "plugin_uuid")].enabled:
861+
plugin_uuid = getattr(func, "plugin_uuid")
862+
if plugin_uuid is None or (plugin_uuid in self.plugins and self.plugins[plugin_uuid].enabled):
857863
func(*args)
858864
except Exception as ex:
859865
text = _("crd_handler_err")

first_setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050

5151
"Greetings": {
5252
"ignoreSystemMessages": "0",
53+
"onlyNewChats": "0",
5354
"sendGreetings": "0",
5455
"greetingsText": "Привет, $chat_name!",
5556
"greetingsCooldown": "2"

handlers.py

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ def save_init_chats_handler(c: Cardinal, e: InitialChatEvent):
6868
cardinal_tools.cache_old_users(c.old_users)
6969

7070

71+
def update_threshold_on_initial_chat(c: Cardinal, e: InitialChatEvent):
72+
"""
73+
Обновляет пороговое значение для определения новых чатов.
74+
"""
75+
if e.chat.id > c.greeting_chat_id_threshold:
76+
c.greeting_chat_id_threshold = e.chat.id
77+
78+
7179
# NEW MESSAGE / LAST CHAT MESSAGE CHANGED
7280
def old_log_msg_handler(c: Cardinal, e: LastChatMessageChangedEvent):
7381
"""
@@ -106,6 +114,25 @@ def log_msg_handler(c: Cardinal, e: NewMessageEvent):
106114
MSG_LOG_LAST_STACK_ID = e.stack.id()
107115

108116

117+
def update_threshold_on_last_message_change(c: Cardinal, e: LastChatMessageChangedEvent | NewMessageEvent):
118+
"""
119+
Обновляет пороговое значение для определения новых чатов.
120+
"""
121+
# Должно выполняться после greetings_handler для корректной обработки
122+
# c.greeting_threshold_chat_ids (чтобы не спамило приветствиями)
123+
if not c.old_mode_enabled:
124+
if isinstance(e, LastChatMessageChangedEvent):
125+
return
126+
chat_id = e.message.chat_id
127+
else:
128+
chat_id = e.chat.id
129+
if e.runner_tag != c.last_greeting_chat_id_threshold_change_tag:
130+
c.greeting_chat_id_threshold = max([c.greeting_chat_id_threshold, *c.greeting_threshold_chat_ids])
131+
c.greeting_threshold_chat_ids = set()
132+
c.last_greeting_chat_id_threshold_change_tag = e.runner_tag
133+
c.greeting_threshold_chat_ids.add(chat_id)
134+
135+
109136
def greetings_handler(c: Cardinal, e: NewMessageEvent | LastChatMessageChangedEvent):
110137
"""
111138
Отправляет приветственное сообщение.
@@ -120,8 +147,10 @@ def greetings_handler(c: Cardinal, e: NewMessageEvent | LastChatMessageChangedEv
120147
else:
121148
obj = e.chat
122149
chat_id, chat_name, mtype, its_me, badge = obj.id, obj.name, obj.last_message_type, not obj.unread, None
123-
if any([time.time() - c.old_users.get(chat_id, 0) < float(
124-
c.MAIN_CFG["Greetings"]["greetingsCooldown"]) * 24 * 60 * 60,
150+
if any([c.MAIN_CFG["Greetings"].getboolean("onlyNewChats") and
151+
(chat_id <= c.greeting_chat_id_threshold or chat_id in c.greeting_threshold_chat_ids),
152+
time.time() - c.old_users.get(chat_id, 0) < float(
153+
c.MAIN_CFG["Greetings"]["greetingsCooldown"]) * 24 * 60 * 60,
125154
its_me, mtype in (MessageTypes.DEAR_VENDORS, MessageTypes.ORDER_CONFIRMED_BY_ADMIN), badge is not None,
126155
(mtype is not MessageTypes.NON_SYSTEM and c.MAIN_CFG["Greetings"].getboolean("ignoreSystemMessages"))]):
127156
return
@@ -135,15 +164,19 @@ def add_old_user_handler(c: Cardinal, e: NewMessageEvent | LastChatMessageChange
135164
"""
136165
Добавляет пользователя в список написавших.
137166
"""
167+
if not c.MAIN_CFG["Greetings"].getboolean("sendGreetings") or c.MAIN_CFG["Greetings"].getboolean("onlyNewChats"):
168+
return
169+
138170
if not c.old_mode_enabled:
139171
if isinstance(e, LastChatMessageChangedEvent):
140172
return
141173
chat_id, mtype = e.message.chat_id, e.message.type
142174
else:
143175
chat_id, mtype = e.chat.id, e.chat.last_message_type
144176

145-
if not c.MAIN_CFG["Greetings"].getboolean("sendGreetings") or mtype == MessageTypes.DEAR_VENDORS:
177+
if mtype == MessageTypes.DEAR_VENDORS:
146178
return
179+
147180
c.old_users[chat_id] = int(time.time())
148181
cardinal_tools.cache_old_users(c.old_users)
149182

@@ -506,13 +539,9 @@ def setup_event_attributes_handler(c: Cardinal, e: NewOrderEvent, *args):
506539
lot_description = e.order.description
507540
# пробуем найти лот, чтобы не выдавать по строке, которую вписал покупатель при оформлении заказа
508541
for lot in sorted(list(c.profile.get_sorted_lots(2).get(e.order.subcategory, {}).values()),
509-
key=lambda l: len(f"{l.server}, {l.description}"), reverse=True):
510-
if lot.server and lot.description:
511-
temp_desc = f"{lot.server}, {lot.description}"
512-
elif lot.server:
513-
temp_desc = lot.server
514-
else:
515-
temp_desc = lot.description
542+
key=lambda l: len(f"{l.server}, {l.side}, {l.description}"), reverse=True):
543+
544+
temp_desc = ", ".join([i for i in [lot.server, lot.side, lot.description] if i])
516545

517546
if temp_desc in e.order.description:
518547
lot_description = temp_desc
@@ -820,10 +849,11 @@ def send_bot_started_notification_handler(c: Cardinal, *args):
820849
continue
821850

822851

823-
BIND_TO_INIT_MESSAGE = [save_init_chats_handler]
852+
BIND_TO_INIT_MESSAGE = [save_init_chats_handler, update_threshold_on_initial_chat]
824853

825854
BIND_TO_LAST_CHAT_MESSAGE_CHANGED = [old_log_msg_handler,
826855
greetings_handler,
856+
update_threshold_on_last_message_change,
827857
add_old_user_handler,
828858
send_response_handler,
829859
process_review_handler,
@@ -833,6 +863,7 @@ def send_bot_started_notification_handler(c: Cardinal, *args):
833863

834864
BIND_TO_NEW_MESSAGE = [log_msg_handler,
835865
greetings_handler,
866+
update_threshold_on_last_message_change,
836867
add_old_user_handler,
837868
send_response_handler,
838869
process_review_handler,

locales/en.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@
114114
# Greeting settings
115115
gr_greetings = "{} Greet users"
116116
gr_ignore_sys_msgs = "{} Ignore system messages"
117+
gr_only_new_chats = "{} Only in new chats"
117118
gr_edit_message = "✏️ Change the text of the welcome message"
118119
gr_edit_cooldown = "⏱️ Cooldown: {} days"
119120

locales/ru.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@
114114
# Настройки приветствия
115115
gr_greetings = "{} Приветствовать пользователей"
116116
gr_ignore_sys_msgs = "{} Игнорировать системные сообщения"
117+
gr_only_new_chats = "{} Только в новых диалогах"
117118
gr_edit_message = "✏️ Изменить текст приветственного сообщения"
118119
gr_edit_cooldown = "⏱️ Кулдаун: {} дн."
119120

main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
......................','.",`............ ..................
5757
............................................................"""
5858

59-
VERSION = "0.1.16.5"
59+
VERSION = "0.1.16.6"
6060

6161
Utils.cardinal_tools.set_console_title(f"FunPay Cardinal v{VERSION}")
6262

0 commit comments

Comments
 (0)