Add files via upload

This commit is contained in:
suhail-c
2024-04-26 17:17:00 +05:30
committed by GitHub
parent f3b23aba70
commit 1cfe70638b
3 changed files with 133 additions and 0 deletions

View File

@@ -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)

View File

@@ -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)

View File

@@ -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()