mirror of
https://github.com/miloszowi/everyone-mention-telegram-bot.git
synced 2025-05-20 09:14:07 +00:00
PEP-8 coding standards, used dataclasses for User and UpdateData classes
This commit is contained in:
parent
2b0728b58c
commit
bbb1706dbe
@ -14,15 +14,15 @@ class App:
|
||||
self.updater = Updater(BOT_TOKEN)
|
||||
|
||||
def run(self) -> None:
|
||||
self.registerHandlers()
|
||||
self.register_handlers()
|
||||
|
||||
self.updater.start_polling()
|
||||
self.updater.idle()
|
||||
|
||||
def registerHandlers(self) -> None:
|
||||
def register_handlers(self) -> None:
|
||||
for handler in AbstractHandler.__subclasses__():
|
||||
self.updater.dispatcher.add_handler(
|
||||
handler().getBotHandler()
|
||||
handler().get_bot_handler()
|
||||
)
|
||||
|
||||
|
||||
|
@ -8,7 +8,7 @@ from pymongo.database import Database
|
||||
|
||||
|
||||
class Client():
|
||||
mongoClient: MongoClient
|
||||
mongo_client: MongoClient
|
||||
database: Database
|
||||
|
||||
def __init__(self) -> None:
|
||||
@ -17,19 +17,19 @@ class Client():
|
||||
MONGODB_HOSTNAME, MONGODB_PORT, MONGODB_DATABASE
|
||||
)
|
||||
|
||||
self.mongoClient = MongoClient(uri)
|
||||
self.database = self.mongoClient[MONGODB_DATABASE]
|
||||
self.mongo_client = MongoClient(uri)
|
||||
self.database = self.mongo_client[MONGODB_DATABASE]
|
||||
|
||||
def insertOne(self, collection: str, data: dict) -> None:
|
||||
def insert_one(self, collection: str, data: dict) -> None:
|
||||
self.database.get_collection(collection).insert_one(data)
|
||||
|
||||
def findOne(self, collection: str, query: dict) -> dict:
|
||||
def find_one(self, collection: str, query: dict) -> dict:
|
||||
return self.database.get_collection(collection).find_one(query)
|
||||
|
||||
def findMany(self, collection: str, filter: dict) -> dict:
|
||||
def find_many(self, collection: str, filter: dict) -> dict:
|
||||
return self.database.get_collection(collection).find(filter)
|
||||
|
||||
def updateOne(self, collection: str, filter: dict, data: dict) -> None:
|
||||
def update_one(self, collection: str, filter: dict, data: dict) -> None:
|
||||
self.database.get_collection(collection).update_one(
|
||||
filter,
|
||||
{ "$set" : data }
|
||||
|
@ -1,52 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
@dataclass
|
||||
class User():
|
||||
collection: str = 'users'
|
||||
idIndex: str = '_id'
|
||||
chatsIndex: str = 'chats'
|
||||
usernameIndex: str = 'username'
|
||||
|
||||
userId: str
|
||||
user_id: str
|
||||
username: str
|
||||
chats: Iterable[str]
|
||||
|
||||
def __init__(self, userId, username, chats) -> None:
|
||||
self.userId = userId
|
||||
self.username = username
|
||||
self.chats = chats
|
||||
collection: str = 'users'
|
||||
id_index: str = '_id'
|
||||
chats_index: str = 'chats'
|
||||
username_index: str = 'username'
|
||||
|
||||
def getUserId(self) -> str:
|
||||
return self.userId
|
||||
def is_in_chat(self, chat_id: str) -> bool:
|
||||
return chat_id in self.chats
|
||||
|
||||
def getUsername(self) -> str:
|
||||
return self.username
|
||||
def add_to_chat(self, chat_id: str) -> None:
|
||||
self.chats.append(chat_id)
|
||||
|
||||
def getChats(self) -> Iterable[str]:
|
||||
return self.chats
|
||||
def remove_from_chat(self, chat_id: str) -> None:
|
||||
if chat_id in self.chats:
|
||||
self.chats.remove(chat_id)
|
||||
|
||||
def isInChat(self, chatId: str) -> bool:
|
||||
return chatId in self.getChats()
|
||||
|
||||
def addToChat(self, chatId: str) -> None:
|
||||
self.chats.append(chatId)
|
||||
|
||||
def removeFromChat(self, chatId: str) -> None:
|
||||
if chatId in self.getChats():
|
||||
self.chats.remove(chatId)
|
||||
|
||||
def toMongoDocument(self) -> dict:
|
||||
def to_mongo_document(self) -> dict:
|
||||
return {
|
||||
self.usernameIndex: self.getUsername(),
|
||||
self.chatsIndex: self.getChats()
|
||||
self.username_index: self.username,
|
||||
self.chats_index: self.chats
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def fromMongoDocument(mongoDocument: dict) -> User:
|
||||
def from_mongo_document(mongo_document: dict) -> User:
|
||||
return User(
|
||||
mongoDocument[User.idIndex],
|
||||
mongoDocument[User.usernameIndex],
|
||||
mongoDocument[User.chatsIndex]
|
||||
mongo_document[User.id_index],
|
||||
mongo_document[User.username_index],
|
||||
mongo_document[User.chats_index]
|
||||
)
|
||||
|
@ -8,17 +8,14 @@ from handler.vo.updateData import UpdateData
|
||||
|
||||
|
||||
class AbstractHandler:
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def getBotHandler(self) -> Handler: raise Exception('getBotHandler method is not implemented')
|
||||
def get_bot_handler(self) -> Handler: raise Exception('get_bot_handler method is not implemented')
|
||||
|
||||
@abstractmethod
|
||||
def handle(self, update: Update, context: CallbackContext) -> None: raise Exception('handle method is not implemented')
|
||||
|
||||
def getUpdateData(self, update: Update) -> UpdateData:
|
||||
return UpdateData.createFromUpdate(update)
|
||||
def get_update_data(self, update: Update) -> UpdateData:
|
||||
return UpdateData.create_from_update(update)
|
||||
|
||||
def reply(self, update: Update, message: str) -> None:
|
||||
update.effective_message.reply_markdown_v2(text=message)
|
||||
|
@ -9,30 +9,30 @@ from handler.abstractHandler import AbstractHandler
|
||||
|
||||
|
||||
class InHandler(AbstractHandler):
|
||||
botHandler: CommandHandler
|
||||
userRepository: UserRepository
|
||||
bot_handler: CommandHandler
|
||||
user_repository: UserRepository
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.botHandler = CommandHandler('in', self.handle)
|
||||
self.userRepository = UserRepository()
|
||||
self.bot_handler = CommandHandler('in', self.handle)
|
||||
self.user_repository = UserRepository()
|
||||
|
||||
def handle(self, update: Update, context: CallbackContext) -> None:
|
||||
updateData = self.getUpdateData(update)
|
||||
update_data = self.get_update_data(update)
|
||||
|
||||
try:
|
||||
user = self.userRepository.getById(updateData.getUserId())
|
||||
user = self.user_repository.get_by_id(update_data.user_id)
|
||||
|
||||
if user.isInChat(updateData.getChatId()):
|
||||
if user.is_in_chat(update_data.chat_id):
|
||||
self.reply(update, opted_in_failed)
|
||||
return
|
||||
|
||||
user.addToChat(updateData.getChatId())
|
||||
self.userRepository.save(user)
|
||||
user.add_to_chat(update_data.chat_id)
|
||||
self.user_repository.save(user)
|
||||
|
||||
except NotFoundException:
|
||||
self.userRepository.saveByUpdateData(updateData)
|
||||
self.user_repository.save_by_update_data(update_data)
|
||||
|
||||
self.reply(update, opted_in)
|
||||
|
||||
def getBotHandler(self) -> CommandHandler:
|
||||
return self.botHandler
|
||||
def get_bot_handler(self) -> CommandHandler:
|
||||
return self.bot_handler
|
||||
|
@ -11,37 +11,37 @@ from handler.abstractHandler import AbstractHandler
|
||||
|
||||
|
||||
class MentionHandler(AbstractHandler):
|
||||
botHandler: CommandHandler
|
||||
userRepository: UserRepository
|
||||
bot_handler: CommandHandler
|
||||
user_repository: UserRepository
|
||||
silent: str = 'silent'
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.botHandler = CommandHandler('everyone', self.handle)
|
||||
self.userRepository = UserRepository()
|
||||
self.bot_handler = CommandHandler('everyone', self.handle)
|
||||
self.user_repository = UserRepository()
|
||||
|
||||
def handle(self, update: Update, context: CallbackContext) -> None:
|
||||
updateData = self.getUpdateData(update)
|
||||
users = self.userRepository.getAllForChat(updateData.getChatId())
|
||||
updateData = self.get_update_data(update)
|
||||
users = self.user_repository.get_all_for_chat(updateData.chat_id)
|
||||
|
||||
if users:
|
||||
self.reply(update, self.buildMentionMessage(users, self.isSilent(context)))
|
||||
self.reply(update, self.build_mention_message(users, self.isSilent(context)))
|
||||
return
|
||||
|
||||
self.reply(update, mention_failed)
|
||||
|
||||
def getBotHandler(self) -> CommandHandler:
|
||||
return self.botHandler
|
||||
def get_bot_handler(self) -> CommandHandler:
|
||||
return self.bot_handler
|
||||
|
||||
def buildMentionMessage(self, users: Iterable[User], silent: bool = False) -> str:
|
||||
def build_mention_message(self, users: Iterable[User], silent: bool = False) -> str:
|
||||
result = ''
|
||||
|
||||
for user in users:
|
||||
if not silent:
|
||||
result += f'*[{user.getUsername()}](tg://user?id={user.getUserId()})* '
|
||||
result += f'*[{user.username}](tg://user?id={user.user_id})* '
|
||||
else:
|
||||
result += f'*{user.getUsername()}\({user.getUserId()}\)*\n'
|
||||
result += f'*{user.username}\({user.user_id}\)*\n'
|
||||
|
||||
return result
|
||||
|
||||
def isSilent(self, context: CallbackContext) -> bool:
|
||||
return context.args and context.args[0] == self.silent
|
||||
return self.silent in context.args
|
@ -9,28 +9,29 @@ from handler.abstractHandler import AbstractHandler
|
||||
|
||||
|
||||
class OutHandler(AbstractHandler):
|
||||
botHandler: CommandHandler
|
||||
userRepository: UserRepository
|
||||
bot_handler: CommandHandler
|
||||
user_repository: UserRepository
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.botHandler = CommandHandler('out', self.handle)
|
||||
self.userRepository = UserRepository()
|
||||
self.bot_handler = CommandHandler('out', self.handle)
|
||||
self.user_repository = UserRepository()
|
||||
|
||||
def handle(self, update: Update, context: CallbackContext) -> None:
|
||||
updateData = self.getUpdateData(update)
|
||||
updateData = self.get_update_data(update)
|
||||
|
||||
try:
|
||||
user = self.userRepository.getById(updateData.getUserId())
|
||||
if not user.isInChat(updateData.getChatId()):
|
||||
user = self.user_repository.get_by_id(updateData.user_id)
|
||||
|
||||
if not user.is_in_chat(updateData.chat_id):
|
||||
raise NotFoundException()
|
||||
except NotFoundException:
|
||||
self.reply(update, opted_off_failed)
|
||||
return
|
||||
|
||||
user.removeFromChat(updateData.getChatId())
|
||||
self.userRepository.save(user)
|
||||
user.remove_from_chat(updateData.chat_id)
|
||||
self.user_repository.save(user)
|
||||
|
||||
self.reply(update, opted_off)
|
||||
|
||||
def getBotHandler(self) -> CommandHandler:
|
||||
return self.botHandler
|
||||
def get_bot_handler(self) -> CommandHandler:
|
||||
return self.bot_handler
|
||||
|
@ -1,35 +1,24 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import names
|
||||
from telegram.update import Update
|
||||
|
||||
|
||||
@dataclass
|
||||
class UpdateData():
|
||||
userId: str
|
||||
chatId: str
|
||||
user_id: str
|
||||
chat_id: str
|
||||
username: str
|
||||
|
||||
def __init__(self, userId: str, chatId: str, username: str) -> None:
|
||||
self.userId = userId
|
||||
self.chatId = chatId
|
||||
self.username = username
|
||||
|
||||
def getUserId(self) -> str:
|
||||
return self.userId
|
||||
|
||||
def getChatId(self) -> str:
|
||||
return self.chatId
|
||||
|
||||
def getUsername(self) -> str:
|
||||
return self.username
|
||||
|
||||
@staticmethod
|
||||
def createFromUpdate(update: Update) -> UpdateData:
|
||||
userId = str(update.effective_user.id)
|
||||
chatId = str(update.effective_chat.id)
|
||||
def create_from_update(update: Update) -> UpdateData:
|
||||
user_id = str(update.effective_user.id)
|
||||
chat_id = str(update.effective_chat.id)
|
||||
username = update.effective_user.username or update.effective_user.first_name
|
||||
|
||||
if not username:
|
||||
username = names.get_first_name()
|
||||
|
||||
return UpdateData(userId, chatId, username)
|
||||
return UpdateData(user_id, chat_id, username)
|
||||
|
@ -12,11 +12,11 @@ class UserRepository():
|
||||
def __init__(self) -> None:
|
||||
self.client = Client()
|
||||
|
||||
def getById(self, id: str) -> User:
|
||||
user = self.client.findOne(
|
||||
def get_by_id(self, id: str) -> User:
|
||||
user = self.client.find_one(
|
||||
User.collection,
|
||||
{
|
||||
User.idIndex: id
|
||||
User.id_index: id
|
||||
}
|
||||
)
|
||||
|
||||
@ -24,41 +24,41 @@ class UserRepository():
|
||||
raise NotFoundException(f'Could not find user with "{id}" id')
|
||||
|
||||
return User(
|
||||
user[User.idIndex],
|
||||
user[User.usernameIndex],
|
||||
user[User.chatsIndex]
|
||||
user[User.id_index],
|
||||
user[User.username_index],
|
||||
user[User.chats_index]
|
||||
)
|
||||
|
||||
def save(self, user: User) -> None:
|
||||
self.client.updateOne(
|
||||
self.client.update_one(
|
||||
User.collection,
|
||||
{ User.idIndex: user.getUserId() },
|
||||
user.toMongoDocument()
|
||||
{ User.id_index: user.user_id },
|
||||
user.to_mongo_document()
|
||||
)
|
||||
|
||||
def saveByUpdateData(self, data: UpdateData) -> None:
|
||||
self.client.insertOne(
|
||||
def save_by_update_data(self, data: UpdateData) -> None:
|
||||
self.client.insert_one(
|
||||
User.collection,
|
||||
{
|
||||
User.idIndex: data.getUserId(),
|
||||
User.usernameIndex: data.getUsername(),
|
||||
User.chatsIndex: [data.getChatId()]
|
||||
User.id_index: data.user_id,
|
||||
User.username_index: data.username,
|
||||
User.chats_index: [data.chat_id]
|
||||
}
|
||||
)
|
||||
|
||||
def getAllForChat(self, chatId: str) -> Iterable[User]:
|
||||
def get_all_for_chat(self, chat_id: str) -> Iterable[User]:
|
||||
result = []
|
||||
users = self.client.findMany(
|
||||
users = self.client.find_many(
|
||||
User.collection,
|
||||
{
|
||||
User.chatsIndex: {
|
||||
"$in" : [chatId]
|
||||
User.chats_index: {
|
||||
"$in" : [chat_id]
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
for record in users:
|
||||
result.append(User.fromMongoDocument(record))
|
||||
result.append(User.from_mongo_document(record))
|
||||
|
||||
return result
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user