From 1cfe70638b01242564b3136695771e7cc10b90c0 Mon Sep 17 00:00:00 2001 From: suhail-c <106970070+suhail-c@users.noreply.github.com> Date: Fri, 26 Apr 2024 17:17:00 +0530 Subject: [PATCH] Add files via upload --- TelegramBot/database/MongoDb.py | 71 ++++++++++++++++++++++++++++++++ TelegramBot/database/database.py | 25 +++++++++++ TelegramBot/database/sqdb.py | 37 +++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 TelegramBot/database/MongoDb.py create mode 100644 TelegramBot/database/database.py create mode 100644 TelegramBot/database/sqdb.py diff --git a/TelegramBot/database/MongoDb.py b/TelegramBot/database/MongoDb.py new file mode 100644 index 0000000..91fe8ed --- /dev/null +++ b/TelegramBot/database/MongoDb.py @@ -0,0 +1,71 @@ +from sys import exit as exiter + +from motor.motor_asyncio import AsyncIOMotorClient + +from TelegramBot.config import MONGO_URI +from TelegramBot.logging import LOGGER + + +# from one string uri you can create multiple databases for different projects/bots. within each database you can store multiple collections, and within each collection you can store multiple documents. + + +class MongoDb: + """ + MongoDb class to help with basic CRUD ( Create, Read, Delete, Update) + operations of documents for a specific collection. + """ + + def __init__(self, collection): + self.collection = collection + + async def read_document(self, document_id): + """ + Read the document using document_id. + """ + return await self.collection.find_one({"_id": document_id}) + + async def update_document(self, document_id, updated_data): + """ + Update as well as create document from document_id. + """ + updated_data = {"$set": updated_data} + await self.collection.update_one({"_id": document_id}, updated_data, upsert=True) + + async def delete_document(self, document_id): + """ + Delete the document using document_id from collection. + """ + await self.collection.delete_one({'_id': document_id}) + + async def total_documents(self): + """ + Return total number of documents in that collection. + """ + return await self.collection.count_documents({}) + + async def get_all_id(self): + """ + Return list of all document "_id" in that collection. + """ + return await self.collection.distinct("_id") + + +async def check_mongo_uri(MONGO_URI: str) -> None: + try: + mongo = AsyncIOMotorClient(MONGO_URI) + await mongo.server_info() + except: + LOGGER(__name__).error( + "Error in Establishing connection with MongoDb URI. Please enter valid uri in the config section.") + exiter(1) + + +# Initiating MongoDb motor client +mongodb = AsyncIOMotorClient(MONGO_URI) + +# Database Name (TelegramBot). +database = mongodb.OdesliBot + +# initiating collections from database TelegramBot. +users = MongoDb(database.users) +chats = MongoDb(database.chats) diff --git a/TelegramBot/database/database.py b/TelegramBot/database/database.py new file mode 100644 index 0000000..37ee414 --- /dev/null +++ b/TelegramBot/database/database.py @@ -0,0 +1,25 @@ +from TelegramBot.database import MongoDb as db +from datetime import datetime, timezone + + +async def saveUser(user): + """ + Save the new user id in the database if it is not already there. + """ + + insert_format = { + "name": (user.first_name or " ") + (user.last_name or ""), + "username": user.username, + "date": datetime.now(timezone.utc)} + await db.users.update_document(user.id, insert_format) + + +async def saveChat(chatid): + """ + Save the new chat id in the database if it is not already there. + """ + + insert_format = {"date": datetime.now(timezone.utc)} + await db.chats.update_document(chatid, insert_format) + + diff --git a/TelegramBot/database/sqdb.py b/TelegramBot/database/sqdb.py new file mode 100644 index 0000000..f127c33 --- /dev/null +++ b/TelegramBot/database/sqdb.py @@ -0,0 +1,37 @@ +import aiosqlite + +# Function to create the database and table asynchronously +async def create_database(): + async with aiosqlite.connect("mydatabase.db") as db: + cursor = await db.cursor() + await cursor.execute(""" + CREATE TABLE IF NOT EXISTS mytable ( + id TEXT, + link TEXT, + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id) + ) + """) + await db.commit() + +# Function to store values in the database asynchronously +async def store_values(id, link): + async with aiosqlite.connect("mydatabase.db") as db: + cursor = await db.cursor() + await cursor.execute("INSERT INTO mytable (id, link) VALUES (?, ?)", (id, link)) + await db.commit() + +# Function to retrieve values by ID asynchronously +async def retrieve_values_by_id(id): + async with aiosqlite.connect("mydatabase.db") as db: + cursor = await db.cursor() + await cursor.execute("SELECT link FROM mytable WHERE id=?", (id,)) + result = await cursor.fetchone() + return result + +# Function to delete entries older than a specified number of hours from a table asynchronously +async def delete_old_entries_by_hours(table_name, hours_threshold): + async with aiosqlite.connect("mydatabase.db") as db: + cursor = await db.cursor() + await cursor.execute(f"DELETE FROM {table_name} WHERE timestamp < datetime('now', '-{hours_threshold} hours')") + await db.commit()