File size: 3,596 Bytes
bc96bf6
 
 
 
cc1139c
bc96bf6
 
 
6b8a650
 
 
bc96bf6
 
 
cc1139c
bc96bf6
 
 
 
 
 
 
 
 
 
cc1139c
bc96bf6
 
cc1139c
bc96bf6
 
cc1139c
 
 
bc96bf6
cc1139c
 
bc96bf6
cc1139c
 
bc96bf6
 
 
 
 
 
 
 
 
 
 
 
cc1139c
 
 
 
 
 
 
 
 
bc96bf6
 
 
 
cc1139c
 
6b8a650
 
 
bc96bf6
cc1139c
bc96bf6
cc1139c
bc96bf6
cc1139c
 
bc96bf6
 
 
 
cc1139c
bc96bf6
 
cc1139c
bc96bf6
 
 
cc1139c
bc96bf6
6b8a650
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os, math, logging, datetime, pytz, logging.config
from aiohttp import web
from pyrogram import Client, types
from database.users_chats_db import db
from database.ia_filterdb import Media
from typing import Union, Optional, AsyncGenerator
from utils import temp, __repo__, __license__, __copyright__, __version__
from info import API_ID, API_HASH, BOT_TOKEN, LOG_CHANNEL, UPTIME, WEB_SUPPORT, LOG_MSG
import asyncio
import uvicorn
from fastapi_app import app as fastapi_app

# Get logging configurations
logging.config.fileConfig("logging.conf")
logger = logging.getLogger(__name__)

class Bot(Client):
    def __init__(self):
        super().__init__(
            name="Professor-Bot",
            api_id=API_ID,
            api_hash=API_HASH,
            bot_token=BOT_TOKEN,
            plugins=dict(root="plugins")
        )
        logger.info("Bot initialized.")

    async def start(self):
        logger.info("Starting bot...")
        b_users, b_chats = await db.get_banned()
        temp.BANNED_USERS = b_users
        temp.BANNED_CHATS = b_chats
        logger.info("Banned users and chats loaded.")

        await super().start()
        logger.info("Pyrogram client started.")

        await Media.ensure_indexes()
        logger.info("Indexes ensured for Media collection.")

        me = await self.get_me()
        temp.U_NAME = me.username
        temp.B_NAME = me.first_name
        self.id = me.id
        self.name = me.first_name
        self.mention = me.mention
        self.username = me.username
        self.log_channel = LOG_CHANNEL
        self.uptime = UPTIME
        curr = datetime.datetime.now(pytz.timezone("Asia/Kolkata"))
        date = curr.strftime('%d %B, %Y')
        tame = curr.strftime('%I:%M:%S %p')
        log_message = LOG_MSG.format(me.first_name, date, tame, __repo__, __version__, __license__, __copyright__)
        logger.info(log_message)

        try:
            await self.send_message(LOG_CHANNEL, text=log_message, disable_web_page_preview=True)
            logger.info("Log message sent to LOG_CHANNEL.")
        except Exception as e:
            logger.warning(f"Bot Isn't Able To Send Message To LOG_CHANNEL \n{e}")

        if bool(WEB_SUPPORT) is True:
            app = web.AppRunner(web.Application(client_max_size=30000000))
            await app.setup()
            await web.TCPSite(app, "0.0.0.0", 8080).start()
            logger.info("Web Response Is Running......🕸️")

        # Run FastAPI app in a separate task
        asyncio.create_task(uvicorn.run(fastapi_app, host="0.0.0.0", port=8000, log_level="info"))

    async def stop(self, *args):
        logger.info("Stopping bot...")
        await super().stop()
        logger.info(f"Bot Is Restarting ⟳...")

    async def iter_messages(self, chat_id: Union[int, str], limit: int, offset: int = 0) -> Optional[AsyncGenerator["types.Message", None]]:
        logger.info(f"Iterating messages in chat_id: {chat_id}, limit: {limit}, offset: {offset}")
        current = offset
        while True:
            new_diff = min(200, limit - current)
            if new_diff <= 0:
                logger.info("No more messages to iterate.")
                return
            messages = await self.get_messages(chat_id, list(range(current, current+new_diff+1)))
            logger.info(f"Retrieved {len(messages)} messages.")
            for message in messages:
                yield message
                current += 1
                logger.info(f"Yielding message with ID: {message.id}")

if __name__ == "__main__":
    bot = Bot()
    asyncio.run(bot.start())