From 947e0161a337b22b6866aaf706c5f4c220953508 Mon Sep 17 00:00:00 2001 From: un1xx Date: Sat, 2 Mar 2024 21:07:44 +0530 Subject: [PATCH] zzzz --- .gitignore | 2 + botclass.py | 47 +++++++++ brahmos.py | 247 +++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 4 + 4 files changed, 300 insertions(+) create mode 100644 .gitignore create mode 100644 botclass.py create mode 100644 brahmos.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6fd0fed --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.python-version +__pycache__ \ No newline at end of file diff --git a/botclass.py b/botclass.py new file mode 100644 index 0000000..d799e68 --- /dev/null +++ b/botclass.py @@ -0,0 +1,47 @@ +import base64 +import json +import os +from typing import List, Literal, Optional, Union + +import aiohttp +import discord +import jishaku +from discord.ext.commands import Bot, Context + +OWNER = [407135783678640128, 341958485724102668] + + +class CustomCtx(Context): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.session = aiohttp.ClientSession(loop=self.bot.loop) + + + +class Brahmos(Bot): + """ + Custom bot class + """ + + def __init__(self, **kwargs): + kwargs["command_prefix"] = ["fr "] + super().__init__(**kwargs, help_command=None) + self.exts = [i[:-3] for i in os.listdir("exts") if i.endswith(".py")] + self.name = "brahmos" + + async def is_owner(self, user: discord.user): + if user.id in OWNER: + return True + return False + + async def setup_hook(self): + print(f"logged in as: {self.user.name}") + await self.load_extension("jishaku") + for ext in self.exts: + await self.load_extension(f"exts.{ext}") + + async def get_context(self, message, *, cls=CustomCtx): + return await super().get_context(message, cls=cls) + + def update_exts(self): + self.exts = [i[:-3] for i in os.listdir("exts") if i.endswith(".py")] diff --git a/brahmos.py b/brahmos.py new file mode 100644 index 0000000..927a47b --- /dev/null +++ b/brahmos.py @@ -0,0 +1,247 @@ +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 botclass import CustomCtx, Brahmos +from discord.ext import commands +from jishaku.codeblocks import codeblock_converter +from psutil import Process + +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/1213505724307607572/m2bQKEKNc3qcw-r8CzcOVjgefAltzbp4gEfePPuEMB4wVc4f9-mwNB-Db1nRW2olEH7d" + + +logger = logging.getLogger("discord") +logging.getLogger("discord.http").setLevel(logging.INFO) + +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.INFO) + + +class Main(commands.Cog): + def __init__(self, bot: Brahmos): + self.bot = bot + + @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, aliases=["sex"]) + @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): + """restart bot""" + await ctx.message.add_reaction("\u2611") + os.system(f"pm2 restart {int(id)}") + await self.bot.close() + + @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 + jskgit = bot.get_command("jsk sh") + await ctx.invoke(jskgit, argument=cmd) + + @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()) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..027d021 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +discord.py[speed] +aiofiles +uvloop +jishaku