senderbot/modules/telegram.py

125 lines
6.7 KiB
Python
Raw Normal View History

2024-06-09 15:42:54 +03:00
"""Bot for mailing."""
2024-06-08 17:56:40 +03:00
# -*- coding: utf-8 -*-
from pathlib import Path
import telebot
2024-06-09 15:42:54 +03:00
from telebot.types import BotCommand
2024-06-08 17:56:40 +03:00
from modules.configuration import Configuration
2024-06-09 15:35:14 +03:00
from modules.keyboards import Keyboards
2024-06-08 17:56:40 +03:00
class TGSenderBot:
"""..."""
def __init__(self) -> None:
"""..."""
self.config = Configuration("config.yaml")
self.bot = telebot.TeleBot(self.config.token)
self.start_cmd = BotCommand(command="start", description="Start bot")
self.start_mailing = BotCommand(command="mailing", description="Prepare to mailing")
2024-06-09 15:35:14 +03:00
self.keyboards = Keyboards()
2024-06-08 17:56:40 +03:00
self.company = None
self.template_msg_path = Path()
self.mailing_method = None
self.waiting_template = bool
self.template_type = None
self.bot.set_my_commands([self.start_cmd, self.start_mailing])
# Commands
@self.bot.message_handler(commands=["start"])
def __start_bot(message) -> None: ...
@self.bot.message_handler(commands=["mailing"])
def __start_mailing(message) -> None:
self.__clear_old_data()
self.bot.send_message(
message.chat.id,
"Привет! Давай начнем подготовку к рассылке.\n\n"
"Для начала - нужно выбрать компанию, от имени которой ты будешь делать рассылку.",
2024-06-09 15:35:14 +03:00
reply_markup=self.keyboards.create_buttons(("COZY COTTON", "MixFix", "chic chick", "Ky Ky", "WOLF&OWL", "NOW")),
2024-06-08 17:56:40 +03:00
)
# Messages
@self.bot.message_handler(func=lambda message: True, content_types=["document","text","contact"]) # noqa: ARG005
def __send_message(message) -> None:
if self.waiting_template and message.document:
if message.document.mime_type.split("/")[1] == self.template_type:
template_info = self.bot.get_file(message.document.file_id)
download_file = self.bot.download_file(template_info.file_path)
self.template_msg_path = Path(f"./templates/{message.document.file_name}")
with self.template_msg_path.open("w+b") as file:
file.write(download_file)
self.bot.send_message(
message.chat.id,
"Отлично! Шаблон сохранен. Осталось лишь проверить все данные, для рассылки.",
2024-06-09 15:35:14 +03:00
reply_markup=self.keyboards.create_buttons(("Проверить данные",)),
2024-06-08 17:56:40 +03:00
)
else:
self.bot.send_message(
message.chat.id,
"Неверный формат файла. Пожалуйста, отправь файл в формате "
f"{'.txt' if self.template_type == 'plain' else '.html'}",
)
match message.text:
case "COZY COTTON" | "MixFix" | "chic chick" | "Ky Ky" | "WOLF&OWL" | "NOW":
self.company = message.text
self.bot.send_message(
message.chat.id,
f'Выбрана компания "{self.company}"\n\nТеперь необходимо выбрать метод,'
"которым будут рассылаться сообщения.\n"
"Пожалуйста, выбери формат шаблона.",
2024-06-09 15:35:14 +03:00
reply_markup=self.keyboards.create_buttons(("E-Mail", "WatsApp"))
2024-06-08 17:56:40 +03:00
)
case "E-Mail" | "WatsApp":
self.mailing_method = "mail" if message.text == "E-Mail" else "whatsapp"
msg = "по E-Mail" if self.mailing_method == "mail" else "сообщениями в WatsApp"
self.bot.send_message(
message.chat.id,
f"Рассылка будет произведена методом {msg}.\n\n"
"Далее мы с тобой напишем шаблон сообщения для рассылки.",
2024-06-09 15:35:14 +03:00
reply_markup=self.keyboards.create_buttons(("Текст", "HTML"))
2024-06-08 17:56:40 +03:00
)
case "Текст" | "HTML":
self.template_type = "plain" if message.text == "Текст" else "html"
self.bot.send_message(
message.chat.id,
"Отлично. Теперь отправь мне шаблон сообщения файлом.",
)
self.waiting_template = True
case "Проверить данные":
with self.template_msg_path.open() as file: # type: ignore # noqa: PGH003
txt = file.read()
msg = str(f'Отлично! Мы на финишной прямой. Проверь все данные. '
f'если все верно - нажми на кнопку "Начать", '
f"если где-то ошибка, пожалуйста, нажми на кнопку, что ты хочешь изменить.\n\n"
f"Компания: {self.company}\n"
f"Метод: {self.mailing_method}\n"
f"Текст:\n\n{txt}",
)
2024-06-09 15:35:14 +03:00
self.bot.send_message(message.chat.id, msg,reply_markup=self.keyboards.create_buttons(("Изменить компанию", "Изменить метод", "Изменить шаблон", "Начать")))
2024-06-08 17:56:40 +03:00
case "Изменить компанию":
self.bot.send_message(
message.chat.id,
"Выбери компанию, от имени которой ты будешь делать рассылку.",
2024-06-09 15:35:14 +03:00
reply_markup=self.keyboards.create_buttons(("COZY COTTON", "MixFix", "chic chick", "Ky Ky", "WOLF&OWL", "NOW"))
2024-06-08 17:56:40 +03:00
)
case "Начать":
self.bot.send_message(
message.chat.id,
"Рассылка начата. По ее окончанию - я сообщу Вам.",
)
def __clear_old_data(self) -> None:
self.company = None
self.template_msg_path = None
self.mailing_method = None
self.waiting_template = bool
self.template_type = None