Update Chat.ubereats

This commit is contained in:
AlberLC
2023-03-08 02:14:47 +01:00
parent 61daaa387a
commit 34320079eb
3 changed files with 28 additions and 34 deletions

View File

@@ -76,7 +76,7 @@ class FlanaBot(Connect4Bot, PenaltyBot, PollBot, ScraperBot, UberEatsBot, Weathe
async def _get_message( async def _get_message(
self, self,
event: multibot_constants.MESSAGE_EVENT, event: multibot_constants.MESSAGE_EVENT,
pull_overwrite_fields: Iterable[str] = ('_id', 'config', 'ubereats_seconds') pull_overwrite_fields: Iterable[str] = ('_id', 'config', 'ubereats')
) -> Message: ) -> Message:
return await super()._get_message(event, pull_overwrite_fields) return await super()._get_message(event, pull_overwrite_fields)
@@ -146,7 +146,7 @@ class FlanaBot(Connect4Bot, PenaltyBot, PollBot, ScraperBot, UberEatsBot, Weathe
if k not in config_names: if k not in config_names:
continue continue
if k == 'ubereats': if k == 'ubereats':
k = f"ubereats (cada {flanautils.TimeUnits(seconds=message.chat.ubereats_seconds).to_words()})" k = f"ubereats (cada {flanautils.TimeUnits(seconds=message.chat.ubereats['seconds']).to_words()})"
buttons_texts.append((f"{'' if v else ''} {k}", v)) buttons_texts.append((f"{'' if v else ''} {k}", v))
await self.send('<b>Estos son los ajustes del chat:</b>\n\n', flanautils.chunks(buttons_texts, 3), message, buttons_key=ButtonsGroup.CONFIG) await self.send('<b>Estos son los ajustes del chat:</b>\n\n', flanautils.chunks(buttons_texts, 3), message, buttons_key=ButtonsGroup.CONFIG)
@@ -165,7 +165,7 @@ class FlanaBot(Connect4Bot, PenaltyBot, PollBot, ScraperBot, UberEatsBot, Weathe
await self.start_ubereats(message.chat) await self.start_ubereats(message.chat)
else: else:
await self.stop_ubereats(message.chat) await self.stop_ubereats(message.chat)
button_text = f"ubereats (cada {flanautils.TimeUnits(seconds=message.chat.ubereats_seconds).to_words()})" button_text = f"ubereats (cada {flanautils.TimeUnits(seconds=message.chat.ubereats['seconds']).to_words()})"
else: else:
button_text = config_name button_text = config_name
message.buttons_info.pressed_button.text = f"{'' if message.chat.config[config_name] else ''} {button_text}" message.buttons_info.pressed_button.text = f"{'' if message.chat.config[config_name] else ''} {button_text}"
@@ -269,15 +269,15 @@ class FlanaBot(Connect4Bot, PenaltyBot, PollBot, ScraperBot, UberEatsBot, Weathe
await flanautils.do_every(multibot_constants.CHECK_OLD_DATABASE_MESSAGES_EVERY_SECONDS, self.check_old_database_actions) await flanautils.do_every(multibot_constants.CHECK_OLD_DATABASE_MESSAGES_EVERY_SECONDS, self.check_old_database_actions)
for chat in Chat.find({ for chat in Chat.find({
'platform': self.platform.value, 'platform': self.platform.value,
"config.ubereats": {"$exists": True, "$eq": True}, 'config.ubereats': {"$exists": True, "$eq": True},
"ubereats_cookies": {"$exists": True, "$ne": []} 'ubereats.cookies': {"$exists": True, "$ne": []}
}): }):
chat = await self.get_chat(chat.id) chat = await self.get_chat(chat.id)
chat.pull_from_database(overwrite_fields=('_id', 'config', 'ubereats_cookies', 'ubereats_seconds')) chat.pull_from_database(overwrite_fields=('_id', 'config', 'ubereats'))
if ( if (
chat.ubereats_next_execution chat.ubereats['next_execution']
and and
(delta_time := chat.ubereats_next_execution - datetime.datetime.now(datetime.timezone.utc)) > datetime.timedelta() (delta_time := chat.ubereats['next_execution'] - datetime.datetime.now(datetime.timezone.utc)) > datetime.timedelta()
): ):
await flanautils.do_later(delta_time, self.start_ubereats, chat) await flanautils.do_later(delta_time, self.start_ubereats, chat)
else: else:

View File

@@ -52,8 +52,7 @@ class UberEatsBot(MultiBot, ABC):
self.task_contexts[chat.id]['playwright'] = await playwright.async_api.async_playwright().start() self.task_contexts[chat.id]['playwright'] = await playwright.async_api.async_playwright().start()
chat.pull_from_database(overwrite_fields=('ubereats_cookies',)) for i, cookies in enumerate(chat.ubereats['cookies']):
for i, cookies in enumerate(chat.ubereats_cookies):
for _ in range(3): for _ in range(3):
try: try:
self.task_contexts[chat.id]['browser'] = await self.task_contexts[chat.id]['playwright'].chromium.launch() self.task_contexts[chat.id]['browser'] = await self.task_contexts[chat.id]['playwright'].chromium.launch()
@@ -90,7 +89,7 @@ class UberEatsBot(MultiBot, ABC):
code = pyperclip.paste() code = pyperclip.paste()
codes.append(code) codes.append(code)
chat.ubereats_cookies[i] = await context.cookies('https://www.myunidays.com') chat.ubereats['cookies'][i] = await context.cookies('https://www.myunidays.com')
except playwright.async_api.Error: except playwright.async_api.Error:
pass pass
@@ -103,8 +102,6 @@ class UberEatsBot(MultiBot, ABC):
if playwright_ := self.task_contexts[chat.id]['playwright']: if playwright_ := self.task_contexts[chat.id]['playwright']:
await playwright_.stop() await playwright_.stop()
chat.save()
return codes return codes
# ---------------------------------------------- # # ---------------------------------------------- #
@@ -112,7 +109,7 @@ class UberEatsBot(MultiBot, ABC):
# ---------------------------------------------- # # ---------------------------------------------- #
@group(False) @group(False)
async def _on_ubereats(self, message: Message): async def _on_ubereats(self, message: Message):
if not message.chat.ubereats_cookies: if not message.chat.ubereats['cookies']:
return return
time = flanautils.text_to_time(message.text) time = flanautils.text_to_time(message.text)
@@ -127,7 +124,7 @@ class UberEatsBot(MultiBot, ABC):
return return
seconds = int(time.total_seconds()) seconds = int(time.total_seconds())
message.chat.ubereats_seconds = seconds message.chat.ubereats['seconds'] = seconds
message.save() message.save()
period = flanautils.TimeUnits(seconds=seconds) period = flanautils.TimeUnits(seconds=seconds)
await self.send(f'A partir de ahora te enviaré un código de UberEats cada <b>{period.to_words()}</b>.', message) await self.send(f'A partir de ahora te enviaré un código de UberEats cada <b>{period.to_words()}</b>.', message)
@@ -137,28 +134,30 @@ class UberEatsBot(MultiBot, ABC):
# -------------------- PUBLIC METHODS -------------------- # # -------------------- PUBLIC METHODS -------------------- #
# -------------------------------------------------------- # # -------------------------------------------------------- #
async def send_ubereats_code(self, chat: Chat, update_next_execution=True): async def send_ubereats_code(self, chat: Chat, update_next_execution=True):
chat.pull_from_database(overwrite_fields=('ubereats',))
new_codes = [] new_codes = []
for code in await self._scrape_codes(chat): for code in await self._scrape_codes(chat):
new_codes.append(code) new_codes.append(code)
if code in chat.ubereats_last_codes: if code in chat.ubereats['last_codes']:
warning_text = '<i>Código ya enviado anteriormente:</i>' warning_text = '<i>Código ya enviado anteriormente:</i>'
else: else:
warning_text = '' warning_text = ''
await self.send(f'{warning_text} <code>{code}</code>', chat, silent=True) await self.send(f'{warning_text} <code>{code}</code>', chat, silent=True)
chat.ubereats['last_codes'] = new_codes
chat.ubereats_last_codes = new_codes
if update_next_execution: if update_next_execution:
chat.ubereats_next_execution = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=chat.ubereats_seconds) chat.ubereats['next_execution'] = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=chat.ubereats['seconds'])
chat.save() chat.save()
async def start_ubereats(self, chat: Chat, send_code_now=True): async def start_ubereats(self, chat: Chat, send_code_now=True):
await self._cancel_scraping_task(chat) await self._cancel_scraping_task(chat)
chat.config['ubereats'] = True chat.config['ubereats'] = True
chat.save(pull_overwrite_fields=('ubereats_cookies',)) chat.save(pull_overwrite_fields=('ubereats',))
self.task_contexts[chat.id]['task'] = await flanautils.do_every(chat.ubereats_seconds, self.send_ubereats_code, chat, do_first_now=send_code_now) self.task_contexts[chat.id]['task'] = await flanautils.do_every(chat.ubereats['seconds'], self.send_ubereats_code, chat, do_first_now=send_code_now)
async def stop_ubereats(self, chat: Chat): async def stop_ubereats(self, chat: Chat):
await self._cancel_scraping_task(chat) await self._cancel_scraping_task(chat)
chat.config['ubereats'] = False chat.config['ubereats'] = False
chat.save(pull_overwrite_fields=('ubereats_cookies',)) chat.save(pull_overwrite_fields=('ubereats',))

View File

@@ -1,6 +1,5 @@
__all__ = ['Chat'] __all__ = ['Chat']
import datetime
from dataclasses import dataclass, field from dataclasses import dataclass, field
from multibot import Chat as MultiBotChat from multibot import Chat as MultiBotChat
@@ -8,7 +7,7 @@ from multibot import Chat as MultiBotChat
@dataclass(eq=False) @dataclass(eq=False)
class Chat(MultiBotChat): class Chat(MultiBotChat):
DEFAULT_CONFIG = { config: dict = field(default_factory=lambda: {
'auto_insult': True, 'auto_insult': True,
'auto_scraping': True, 'auto_scraping': True,
'auto_weather_chart': False, 'auto_weather_chart': False,
@@ -16,14 +15,10 @@ class Chat(MultiBotChat):
'punish': False, 'punish': False,
'scraping_delete_original': True, 'scraping_delete_original': True,
'ubereats': False 'ubereats': False
} })
ubereats: dict = field(default_factory=lambda: {
config: dict = field(default_factory=dict) 'cookies': [],
ubereats_cookies: list[list[dict]] = field(default_factory=list) 'last_codes': [],
ubereats_last_codes: list[str] = field(default_factory=list) 'seconds': 86700,
ubereats_seconds: int = 86700 'next_execution': None
ubereats_next_execution: datetime.datetime = None })
def __post_init__(self):
super().__post_init__()
self.config = self.DEFAULT_CONFIG | self.config