removed chat id env variable

pull/231/head
Yariv Menachem 2025-01-01 17:46:39 +02:00
parent 4fb2b2dbb7
commit f83e875171
9 changed files with 31 additions and 25 deletions

View File

@ -63,7 +63,6 @@ JobPost
```env ```env
TELEGRAM_BOT_TOKEN=your_telegram_bot_token TELEGRAM_BOT_TOKEN=your_telegram_bot_token
MONGO_URI=your_mongodb_connection_string MONGO_URI=your_mongodb_connection_string
TELEGRAM_CHAT_ID=your_telegram_chat_id
``` ```
4. **Run the bot**: 4. **Run the bot**:

View File

@ -23,7 +23,6 @@ class JobRepository:
self.logger = create_logger("JobRepository") self.logger = create_logger("JobRepository")
mongo_client = MongoDB() mongo_client = MongoDB()
self.collection = mongo_client.db["jobs"] self.collection = mongo_client.db["jobs"]
self.logger.info("Succeed connect to MongoDB")
return cls._instance return cls._instance
def find_by_id(self, job_id: str) -> Optional[JobPost]: def find_by_id(self, job_id: str) -> Optional[JobPost]:

View File

@ -29,4 +29,5 @@ class MongoDB:
"MONGO_DB_NAME environment variable is not set") "MONGO_DB_NAME environment variable is not set")
self.db = client[database_name] self.db = client[database_name]
logger.info("Succeed connect to MongoDB")
return cls._instance return cls._instance

View File

@ -1,4 +1,5 @@
import os import os
from typing import Union
from dotenv import load_dotenv from dotenv import load_dotenv
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup
@ -20,7 +21,6 @@ class TelegramBot:
def __init__(self): def __init__(self):
self._api_token = os.getenv("TELEGRAM_API_TOKEN") self._api_token = os.getenv("TELEGRAM_API_TOKEN")
self.chatId = os.getenv("TELEGRAM_CHAT_ID")
self.bot = Bot(token=self._api_token) self.bot = Bot(token=self._api_token)
def get_reply_markup(self): def get_reply_markup(self):
@ -35,7 +35,7 @@ class TelegramBot:
return InlineKeyboardMarkup(keyboard) return InlineKeyboardMarkup(keyboard)
async def send_job(self, job: JobPost): async def send_job(self, chat_id: Union[int, str], job: JobPost):
""" """
Send JobPost details to Telegram chat. Send JobPost details to Telegram chat.
""" """
@ -47,18 +47,19 @@ class TelegramBot:
reply_markup = self.get_reply_markup() reply_markup = self.get_reply_markup()
try: try:
await self.bot.sendMessage(chat_id=self.chatId, text=message, reply_markup=reply_markup) await self.bot.sendMessage(chat_id=chat_id, text=message, reply_markup=reply_markup)
logger.info(f"Sent job to Telegram: {job.id}") logger.info(f"Sent job to Telegram: {job.id}")
except Exception as e: except Exception as e:
logger.error(f"Failed to send job to Telegram: {job.id}") logger.error(f"Failed to send job to Telegram: {job.id}")
logger.error(f"Error: {e}") logger.error(f"Error: {e}")
async def send_text(self, message: str, reply_markup: InlineKeyboardMarkup = None): async def send_text(self, chat_id: Union[int, str], message: str, reply_markup: InlineKeyboardMarkup = None):
""" """
Send Text han Message to Telegram chat. Send Text han Message to Telegram chat.
""" """
try: try:
await self.bot.sendMessage(chat_id=self.chatId, text=message, reply_markup=reply_markup)
await self.bot.sendMessage(chat_id=chat_id, text=message, reply_markup=reply_markup)
logger.info("Sent text message to Telegram") logger.info("Sent text message to Telegram")
except Exception as e: except Exception as e:
logger.error("Failed to send text message to Telegram") logger.error("Failed to send text message to Telegram")
@ -77,12 +78,12 @@ class TelegramBot:
logger.error("Failed to send test message to Telegram") logger.error("Failed to send test message to Telegram")
logger.error(f"Error: {e}") logger.error(f"Error: {e}")
async def set_message_reaction(self, message_id: int, emoji_reaction: ReactionEmoji): async def set_message_reaction(self, chat_id: Union[int, str], message_id: int, emoji_reaction: ReactionEmoji):
""" """
Send Test Message to Telegram chat. Send Test Message to Telegram chat.
""" """
try: try:
await self.bot.set_message_reaction(chat_id=self.chatId, message_id=message_id, await self.bot.set_message_reaction(chat_id=chat_id, message_id=message_id,
reaction=emoji_reaction) reaction=emoji_reaction)
logger.info(f"Reaction set to message: {message_id}") logger.info(f"Reaction set to message: {message_id}")
except Exception as e: except Exception as e:

View File

@ -51,7 +51,8 @@ class ButtonCallBackContext:
elif self._data: elif self._data:
job = self._job_repository.find_by_id(self._data) job = self._job_repository.find_by_id(self._data)
if job: if job:
self._strategy = JobTitleStrategy(job) chat_id = self._message.chat.id
self._strategy = JobTitleStrategy(chat_id,job)
else: else:
self._logger.error("Invalid enum value") self._logger.error("Invalid enum value")
return return

View File

@ -27,4 +27,5 @@ class FireStrategy(ButtonStrategy):
return return
job.applied = True job.applied = True
self._job_repository.update(job) self._job_repository.update(job)
await self._telegram_bot.set_message_reaction(self._message.message_id, self._emoji) chat_id = self._message.chat.id
await self._telegram_bot.set_message_reaction(chat_id, self._message.message_id, self._emoji)

View File

@ -1,16 +1,19 @@
from typing import Union
from jobspy import JobPost from jobspy import JobPost
from telegram_bot import TelegramBot from telegram_bot import TelegramBot
from telegram_handler.button_callback.button_strategy import ButtonStrategy from telegram_handler.button_callback.button_strategy import ButtonStrategy
class JobTitleStrategy(ButtonStrategy): class JobTitleStrategy(ButtonStrategy):
def __init__(self, job: JobPost) -> None: def __init__(self, chat_id: Union[int, str], job: JobPost) -> None:
""" """
Usually, the Context accepts a strategy through the constructor, but Usually, the Context accepts a strategy through the constructor, but
also provides a setter to change it at runtime. also provides a setter to change it at runtime.
""" """
self._job = job self._job = job
self._chat_id = chat_id
self.telegram_bot = TelegramBot() self.telegram_bot = TelegramBot()
async def execute(self): async def execute(self):
await self.telegram_bot.send_job(self._job) await self.telegram_bot.send_job(self._chat_id, self._job)

View File

@ -11,10 +11,10 @@ class PooStrategy(ButtonStrategy):
Usually, the Context accepts a strategy through the constructor, but Usually, the Context accepts a strategy through the constructor, but
also provides a setter to change it at runtime. also provides a setter to change it at runtime.
""" """
self.message = message self._message = message
self._emoji = ReactionEmoji.PILE_OF_POO self._emoji = ReactionEmoji.PILE_OF_POO
self.telegram_bot = TelegramBot() self.telegram_bot = TelegramBot()
async def execute(self): async def execute(self):
await self.telegram_bot.set_message_reaction(self.message.message_id, self._emoji) chat_id = self._message.chat.id
await self.telegram_bot.set_message_reaction(chat_id, self._message.message_id, self._emoji)

View File

@ -48,11 +48,12 @@ class TelegramDefaultHandler(TelegramHandler):
async def handle(self, update: Update, context: ContextTypes.DEFAULT_TYPE): async def handle(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
self.logger.info("start handling") self.logger.info("start handling")
await self.telegram_bot.set_message_reaction( chat_id = update.message.chat.id
await self.telegram_bot.set_message_reaction(chat_id,
update.message.message_id, ReactionEmoji.FIRE) update.message.message_id, ReactionEmoji.FIRE)
site_names = [site.name for site in self.sites_to_scrap] site_names = [site.name for site in self.sites_to_scrap]
site_names_print = ", ".join(site_names) site_names_print = ", ".join(site_names)
await self.telegram_bot.send_text( await self.telegram_bot.send_text(chat_id,
f"Start scarping: {site_names_print}") f"Start scarping: {site_names_print}")
filtered_out_jobs, jobs = scrape_jobs( filtered_out_jobs, jobs = scrape_jobs(
site_name=self.sites_to_scrap, site_name=self.sites_to_scrap,
@ -61,17 +62,17 @@ class TelegramDefaultHandler(TelegramHandler):
results_wanted=200, results_wanted=200,
hours_old=48, hours_old=48,
filter_by_title=self.title_filters, filter_by_title=self.title_filters,
country_indeed = 'israel' country_indeed='israel'
) )
self.logger.info(f"Found {len(jobs)} jobs") self.logger.info(f"Found {len(jobs)} jobs")
self.jobRepository.insert_many_if_not_found(filtered_out_jobs) self.jobRepository.insert_many_if_not_found(filtered_out_jobs)
old_jobs, new_jobs = self.jobRepository.insert_many_if_not_found(jobs) old_jobs, new_jobs = self.jobRepository.insert_many_if_not_found(jobs)
for newJob in new_jobs: for newJob in new_jobs:
await self.telegram_bot.send_job(newJob) await self.telegram_bot.send_job(chat_id, newJob)
if filtered_out_jobs: if filtered_out_jobs:
await self.telegram_bot.send_text("filtered by title: ", await self.telegram_bot.send_text(chat_id, "filtered by title: ",
reply_markup=map_jobs_to_keyboard(filtered_out_jobs)) reply_markup=map_jobs_to_keyboard(filtered_out_jobs))
self.logger.info(f"Found {len(old_jobs)} old jobs") self.logger.info(f"Found {len(old_jobs)} old jobs")
await self.telegram_bot.send_text( await self.telegram_bot.send_text(chat_id,
f"Finished scarping: {site_names_print}") f"Finished scarping: {site_names_print}")
self.logger.info("finished handling") self.logger.info("finished handling")