Files
brahmos/brahmos.py
T
2025-11-10 01:54:57 +05:30

265 lines
8.0 KiB
Python

import asyncio
import datetime
import io
import json
import logging
import os
import random
from os import getpid
from typing import List, Literal, Optional, Union
import aiofiles
import discord
import pytz
from discord.ext import commands
from jishaku.codeblocks import codeblock_converter
from psutil import Process
from botclass import Brahmos, CustomCtx
try:
import uvloop
except:
print("failed to import uvloop")
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
from discord_logging.handler import DiscordHandler
intents = discord.Intents.all()
bot = Brahmos(case_insensitive=True, intents=intents)
tree = bot.tree
# check for store folder
if "store" not in os.listdir():
os.mkdir("store")
class Formatter(logging.Formatter):
def converter(self, timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
tzinfo = pytz.timezone("Asia/Kolkata")
return tzinfo.localize(dt)
def formatTime(self, record, datefmt="%H:%M:%S"):
dt = self.converter(record.created)
if datefmt:
s = dt.strftime(datefmt)
else:
try:
s = dt.isoformat(timespec="milliseconds")
except TypeError:
s = dt.isoformat()
return s
webhook_url = "https://discord.com/api/webhooks/1367760254477140021/vsl7vs6oVDjrtWK8sfqxxQpLd8ijEJ0u7eNt6BYp9TP4Wkxrl2Hdu1PR_SM6NVKDh7vc"
logger = logging.getLogger("discord")
logging.getLogger("discord.http").setLevel(logging.WARNING)
stream_format = Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
discord_format = Formatter("%(message)s")
discord_handler = DiscordHandler(
bot.name,
webhook_url,
# avatar_url=,
)
# discord_handler = DiscordHandler("Happy Bot", webhook_url, emojis={})
discord_handler.setFormatter(discord_format)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(stream_format)
# Add the handlers to the Logger
logger.addHandler(discord_handler)
logger.addHandler(stream_handler)
logger.setLevel(logging.WARNING)
class Main(commands.Cog):
def __init__(self, bot: Brahmos):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
logger.warning(f"Logged in as {self.bot.user} (ID: {self.bot.user.id})")
@commands.command(aliases=["p"])
async def ping(self, ctx):
"""Returns bot's latency."""
m = await ctx.send("hello...? \U0001f44b")
delta = (m.created_at - ctx.message.created_at).microseconds / 1000
await m.edit(
content=f"`\U0001f3d3` : **{delta}ms** `\u2764` : **{int(self.bot.latency*1000)}ms**"
)
@commands.command()
async def say(self, ctx, *, content: commands.clean_content = None):
"""Makes bot say something."""
if not content:
await ctx.send("\U0001f612")
return
await asyncio.sleep(0.5)
try:
await ctx.message.delete()
except:
pass
await ctx.send(content)
@commands.command(name="reload", hidden=True)
@commands.is_owner()
async def reloadexts(self, ctx: commands.Context):
"reload all extensions"
for i in list(self.bot.extensions):
await self.bot.reload_extension(i)
await ctx.send("`reloaded all extensions`")
@commands.command(name="loadall", hidden=True, aliases=["lall"])
@commands.is_owner()
async def loadallexts(self, ctx: commands.Context):
"load all extensions"
loaded = []
for i in self.bot.exts:
try:
await self.bot.load_extension(f"exts.{i}")
loaded.append(i)
except:
pass
await ctx.send(f"`loaded : {', '.join(ext for ext in loaded)}`")
@commands.command(name="unloadall", hidden=True, aliases=["uall"])
@commands.is_owner()
async def unloadallexts(self, ctx: commands.Context):
"unload all extensions"
unloaded = []
try:
for i in list(self.bot.extensions):
await self.bot.unload_extension(i)
unloaded.append(i)
except:
pass
await ctx.send(f"`unloaded : {', '.join(ext for ext in unloaded)}`")
@commands.command(name="load", hidden=True)
@commands.is_owner()
async def loadext(self, ctx: commands.Context, *, ext: str):
"load an extension"
try:
await self.bot.load_extension(f"exts.{ext}")
await ctx.send(f"`laoded exts.{ext}`")
except Exception as e:
return await ctx.send(f"`{e}`")
@commands.command(name="unload", hidden=True)
@commands.is_owner()
async def unloadext(self, ctx: commands.Context, *, ext: str):
"unload an extension"
try:
await self.bot.unload_extension(f"exts.{ext}")
await ctx.send(f"`unloaded exts.{ext}`")
except Exception as e:
return await ctx.send(f"`{e}`")
@commands.command(name="mem")
@commands.is_owner()
async def mem(self, ctx):
await ctx.send(f"{round(Process(getpid()).memory_info().rss/1024/1024, 2)} MB")
@commands.command(name="showexts", hidden=True)
@commands.is_owner()
async def showexts(self, ctx: commands.Context):
"show all loaded extensions"
await ctx.send(f"`{', '.join(i for i in ctx.bot.extensions)}`")
@commands.command(name="restart", hidden=True)
@commands.is_owner()
async def restart(self, ctx: commands.Context, id: Optional[int]=0):
"""restart bot"""
await ctx.message.add_reaction("\u2611")
# stop the bot
logger.warn("closing the bot")
self.bot.db_pool.close()
self.bot.close()
os.system(f"pm2 restart {id}")
@commands.command(name="git")
@commands.is_owner()
async def git(self, ctx: commands.Context, *, cmd: codeblock_converter = None):
if cmd is None:
return
jskgit = bot.get_command("jsk git")
await ctx.invoke(jskgit, argument=cmd)
@commands.command(name="shell", aliases=["sh"])
@commands.is_owner()
async def shell(self, ctx: commands.Context, *, cmd: codeblock_converter = None):
if cmd is None:
return
jsksh = bot.get_command("jsk sh")
await ctx.invoke(jsksh, argument=cmd)
@commands.is_owner()
@commands.command(name="pullr")
async def pullr(self, ctx: CustomCtx):
"""
git pull and restart the bot.
"""
git = bot.get_command("jsk git")
await ctx.invoke(git, argument=codeblock_converter("pull"))
restart = bot.get_command("restart")
await ctx.invoke(restart)
@commands.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
self,
ctx: commands.Context,
guilds: commands.Greedy[discord.Object],
spec: Optional[Literal["~", "*", "^"]] = None,
) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
async def main():
async with bot:
await bot.add_cog(Main(bot))
await bot.start(os.getenv("TOKEN"))
if __name__ == "__main__":
asyncio.run(main())