RenameBot / bot.py
Thaimozhi
channel feature and keep audio track
4743369
Raw History Blame Contribute Delete
4.61 kB
import time
import urllib.request
import email.utils
import aiohttp
import asyncio
import warnings
import pytz
import inspect
try:
req = urllib.request.urlopen("https://google.com", timeout=3)
server_time = email.utils.parsedate_to_datetime(req.headers["Date"]).timestamp()
offset = server_time - time.time()
original_time = time.time
time.time = lambda: original_time() + offset
except Exception as e:
print("Time sync patch failed:", e)
from datetime import datetime, timedelta
from pytz import timezone
from pyrogram import Client
from config import Config
from aiohttp import web
from route import web_server
from utils.job_queue import worker
import pyrogram.utils
import pyromod
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
import os
pyrogram.utils.MIN_CHANNEL_ID = -1009147483647
SUPPORT_CHAT = int(os.environ.get("SUPPORT_CHAT", "-1001953724858"))
if os.environ.get("SPACE_ID") or os.environ.get("SPACE_HOST"):
PORT = 7860
else:
try:
PORT = int(os.environ.get("PORT", "7860"))
except ValueError:
PORT = 7860
class Bot(Client):
def __init__(self):
# max_concurrent_transmissions exists in newer Pyrogram builds but is
# missing from some deployed/forked versions. Keep startup compatible.
try:
transmission_options = (
{"max_concurrent_transmissions": 4}
if "max_concurrent_transmissions" in inspect.signature(Client.__init__).parameters
else {}
)
except (TypeError, ValueError):
transmission_options = {}
super().__init__(
name="codeflixbots",
api_id=Config.API_ID,
api_hash=Config.API_HASH,
bot_token=Config.BOT_TOKEN,
workers=20,
plugins={"root": "plugins"},
sleep_threshold=15,
**transmission_options,
)
self.start_time = time.time()
async def start(self, *args, **kwargs):
if Config.WEBHOOK:
try:
app = web.AppRunner(await web_server())
await app.setup()
await web.TCPSite(app, "0.0.0.0", PORT).start()
print(f"Web server started on port {PORT} for health checks.")
except Exception as e:
print(f"Failed to start web server: {e}")
await super().start(*args, **kwargs)
me = await self.get_me()
self.mention = me.mention
self.username = me.username
print(f"{me.first_name} Is Started.....✨️")
self.worker_task = asyncio.create_task(worker(self))
uptime_seconds = int(time.time() - self.start_time)
uptime_string = str(timedelta(seconds=uptime_seconds))
caption = (
"›› ʜᴇʏ sᴇɴᴘᴀɪ!!\n"
"ɪ'ᴍ ᴀʟɪᴠᴇ ɴᴏᴡ 🍃...\n\n"
f"ɪ ᴅɪᴅɴ'ᴛ sʟᴇᴘᴛ sɪɴᴄᴇ​: `{uptime_string}`"
)
reply_markup = InlineKeyboardMarkup([[
InlineKeyboardButton("ᴜᴘᴅᴀᴛᴇs", url="https://t.me/AnimePiratesTamil")
]])
# Send to Channels
for chat_id in [Config.LOG_CHANNEL, SUPPORT_CHAT]:
try:
await self.send_photo(
chat_id=chat_id,
photo=Config.START_PIC,
caption=caption,
reply_markup=reply_markup
)
print(f"✅ Message sent to chat: {chat_id}")
except Exception as e:
print(f"❌ Failed to send in chat {chat_id}: {e}")
# 🔥 Send to Owner DM
try:
owner_id = Config.OWNER_ID
print(f"🔄 Trying to send DM to OWNER_ID: {owner_id}")
await self.send_photo(
chat_id=owner_id,
photo=Config.START_PIC,
caption=caption,
reply_markup=reply_markup
)
print("✅ START MESSAGE SENT TO OWNER (DM) SUCCESSFULLY!")
except Exception as e:
print(f"❌ FAILED to send DM to Owner: {e}")
print(f" Check OWNER_ID → Current value: {getattr(Config, 'OWNER_ID', 'NOT FOUND')}")
async def stop(self, *args, **kwargs):
if hasattr(self, 'worker_task'):
self.worker_task.cancel()
await super().stop(*args, **kwargs)
print("Bot is gracefully shutting down...")
if __name__ == "__main__":
try:
Bot().run()
except Exception as e:
print(f"Stopped: {e}")