azils3 commited on
Commit
5ea5763
·
verified ·
1 Parent(s): cef4c33

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +87 -27
bot.py CHANGED
@@ -1,36 +1,96 @@
1
- # Dockerfile
2
- FROM python:3.10
3
 
4
- # Create a non-root user with valid username format
5
- RUN adduser --disabled-password --gecos '' professor && \
6
- mkdir -p /app && \
7
- chown -R professor:professor /app
 
 
 
 
8
 
9
- # Install system dependencies
10
- RUN apt-get update && apt-get upgrade -y
 
11
 
12
- # Copy requirements and install
13
- COPY requirements.txt /requirements.txt
14
- RUN pip install --upgrade pip && \
15
- pip install -r /requirements.txt
 
 
 
 
 
 
16
 
17
- # Switch to non-root user
18
- USER professor
19
- WORKDIR /app
 
 
 
20
 
21
- # Copy application files
22
- COPY --chown=professor:professor . .
23
 
24
- # Set environment variables
25
- ENV LOG_PATH=/app/BotLog.txt
26
- ENV UVICORN_HOST=0.0.0.0
27
- ENV UVICORN_PORT=8000
28
 
29
- # Ensure the log file is writable
30
- RUN touch $LOG_PATH && chmod 666 $LOG_PATH
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- # Expose port for FastAPI
33
- EXPOSE 8000
 
 
 
34
 
35
- # Start the FastAPI app
36
- CMD ["uvicorn", "fastapi_app:app", "--host", "$UVICORN_HOST", "--port", "$UVICORN_PORT", "--log-level", "info"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # bot.py
 
2
 
3
+ import os, math, logging, datetime, pytz, logging.config
4
+ from pyrogram import Client, types
5
+ from database.users_chats_db import db
6
+ from database.ia_filterdb import Media
7
+ from typing import Union, Optional, AsyncGenerator
8
+ from utils import temp, __repo__, __license__, __copyright__, __version__
9
+ from info import API_ID, API_HASH, BOT_TOKEN, LOG_CHANNEL, UPTIME, WEB_SUPPORT, LOG_MSG
10
+ import asyncio
11
 
12
+ # Get logging configurations
13
+ logging.config.fileConfig("logging.conf")
14
+ logger = logging.getLogger(__name__)
15
 
16
+ class Bot(Client):
17
+ def __init__(self):
18
+ super().__init__(
19
+ name="Professor-Bot",
20
+ api_id=API_ID,
21
+ api_hash=API_HASH,
22
+ bot_token=BOT_TOKEN,
23
+ plugins=dict(root="plugins")
24
+ )
25
+ logger.info("Bot initialized.")
26
 
27
+ async def start(self):
28
+ logger.info("Starting bot...")
29
+ b_users, b_chats = await db.get_banned()
30
+ temp.BANNED_USERS = b_users
31
+ temp.BANNED_CHATS = b_chats
32
+ logger.info("Banned users and chats loaded.")
33
 
34
+ await super().start()
35
+ logger.info("Pyrogram client started.")
36
 
37
+ await Media.ensure_indexes()
38
+ logger.info("Indexes ensured for Media collection.")
 
 
39
 
40
+ me = await self.get_me()
41
+ temp.U_NAME = me.username
42
+ temp.B_NAME = me.first_name
43
+ self.id = me.id
44
+ self.name = me.first_name
45
+ self.mention = me.mention
46
+ self.username = me.username
47
+ self.log_channel = LOG_CHANNEL
48
+ self.uptime = UPTIME
49
+ curr = datetime.datetime.now(pytz.timezone("Asia/Kolkata"))
50
+ date = curr.strftime('%d %B, %Y')
51
+ tame = curr.strftime('%I:%M:%S %p')
52
+ log_message = LOG_MSG.format(me.first_name, date, tame, __repo__, __version__, __license__, __copyright__)
53
+ logger.info(log_message)
54
 
55
+ try:
56
+ await self.send_message(LOG_CHANNEL, text=log_message, disable_web_page_preview=True)
57
+ logger.info("Log message sent to LOG_CHANNEL.")
58
+ except Exception as e:
59
+ logger.warning(f"Bot Isn't Able To Send Message To LOG_CHANNEL \n{e}")
60
 
61
+ if bool(WEB_SUPPORT) is True:
62
+ app = web.AppRunner(web.Application(client_max_size=30000000))
63
+ await app.setup()
64
+ await web.TCPSite(app, "0.0.0.0", 8080).start()
65
+ logger.info("Web Response Is Running......🕸️")
66
+
67
+ async def stop(self, *args):
68
+ logger.info("Stopping bot...")
69
+ await super().stop()
70
+ logger.info(f"Bot Is Restarting ⟳...")
71
+
72
+ async def iter_messages(self, chat_id: Union[int, str], limit: int, offset: int = 0) -> Optional[AsyncGenerator["types.Message", None]]:
73
+ logger.info(f"Iterating messages in chat_id: {chat_id}, limit: {limit}, offset: {offset}")
74
+ current = offset
75
+ while True:
76
+ new_diff = min(200, limit - current)
77
+ if new_diff <= 0:
78
+ logger.info("No more messages to iterate.")
79
+ return
80
+ messages = await self.get_messages(chat_id, list(range(current, current+new_diff+1)))
81
+ logger.info(f"Retrieved {len(messages)} messages.")
82
+ for message in messages:
83
+ yield message
84
+ current += 1
85
+ logger.info(f"Yielding message with ID: {message.id}")
86
+
87
+ if __name__ == "__main__":
88
+ bot = Bot()
89
+ loop = asyncio.get_event_loop()
90
+ try:
91
+ loop.run_until_complete(bot.start())
92
+ loop.run_forever()
93
+ except KeyboardInterrupt:
94
+ loop.run_until_complete(bot.stop())
95
+ finally:
96
+ loop.close()