Example #1
0
 async def eval(self, ctx, *, code):
     client = mystbin.Client()
     code = code.lstrip("```").rstrip("```")
     code = code.splitlines()
     lang = code.pop(0)
     code = "\n".join(code)
     json = {"language": lang, "source": code}
     async with self.bot.session.post(
             "https://emkc.org/api/v1/piston/execute", json=json) as resp:
         data = await resp.json()
     if data.get("message"):
         return await ctx.send(embed=ctx.embed(
             title="Something went wrong...",
             description=data.get("message"),
         ))
     if len(data.get("output")) > 2000:
         thing = await client.post(content=data.get("output"), syntax=lang)
         return await ctx.send(embed=ctx.embed(
             title="Your output was too long so I uploaded it here:",
             description=thing,
         ))
     await ctx.send(embed=ctx.embed(
         title=f"Ran your code in `{lang}`",
         description=f'```{lang}\n{data.get("output")}\n```',
     ))
Example #2
0
async def exc(e):
    user = models.User.get_from_cache()
    error_channel = bot.get_channel(836993491485458454)

    emb = discord.Embed(color=discord.Color.red(), title="Error Occured!")
    error = "".join(traceback.format_exception(type(e), e, e.__traceback__))
    if len(error) > 2000:
        mystbin_client = mystbin.Client()
        error = await mystbin_client.post(error, syntax='python')
    else:
        error = f"```py\n{error}```"
    emb.description = f"{error}"
    await error_channel.send(embed=emb, content="Error occured!")

    return await render_template(
        'errors/exception.html',
        not_found_icon=not_found_icon,
        color=WebsiteTheme.color,
        icon=image,
        staff=cache.get_from_cache(cache, 'staff_open'),
        logged_in=await discord_session.authorized,
        is_staff=verify_staff(db, user),
        announcement=cache.get_from_cache(cache, 'announcement'),
        announcement_color=cache.get_from_cache(cache, 'announcement_color'),
        error=e,
        user=user)
Example #3
0
    def __init__(self):
        _allowed_mentions = discord.AllowedMentions(users=True,
                                                    replied_user=False,
                                                    roles=False,
                                                    everyone=False)
        _intents = discord.Intents.all()
        super().__init__(command_prefix=get_prefix,
                         case_insensitive=True,
                         allowed_mentions=_allowed_mentions,
                         intents=_intents,
                         help_command=ShrimpMasterHelpCommand(),
                         owner_id=414556245178056706)

        self.db = None
        self.timers = None
        self.evaluator = None
        self.command_usage = {}
        self.up_since = datetime.datetime.utcnow()
        self.handler = handler.Handler()
        self.session = aiohttp.ClientSession()
        self.mystbin = mystbin.Client()
        self.gist = Gist(self.session)
        self.crime_messages = {"good": [], "bad": [], "die": []}

        self._setup()
Example #4
0
 def __init__(self, bot):
     self.bot = bot
     self._last_result = None
     self.help_icon = ''
     self.big_icon = ''
     self.anti_spam_commands = CooldownByContent.from_cooldown(17, 15.0, commands.BucketType.member)  # 12 commands per 15 seconds
     self.pre_anti_spam = CooldownByContent.from_cooldown(5, 10, commands.BucketType.member)  # 5 commands per 10 seconds
     self.mystbin_client = mystbin.Client()
Example #5
0
 def __init__(self, bot):
     self.bot = bot
     self.token = bot.config["githubkey"]
     self.bot.snipe = {}
     self.bot.editsnipe = {}
     self.mystbin = mystbin.Client()
     self.cleverbot = async_cleverbot.Cleverbot(
         self.bot.config['travitiakey'])
Example #6
0
    def __init__(self, *args, **kwargs):
        super().__init__(get_prefix,
                         description="A moderation / fun bot",
                         intents=intents,
                         allowed_mentions=discord.AllowedMentions.none(),
                         activity=discord.Activity(
                             type=discord.ActivityType.listening,
                             name="@Penguin"),
                         owner_ids={447422100798570496},
                         **kwargs)

        self._logger = logging.getLogger(__name__)

        self.loop = asyncio.get_event_loop()
        self.session = aiohttp.ClientSession()

        self.start_time = dt.datetime.now()

        with open("config.json") as res:
            self.config = json.load(res)

        self.ipc = ipc.Server(self, "localhost", self.config['ipc-port'],
                              self.config['ipc-key'])
        self.load_extension("utils.ipc")

        self.db = self.loop.run_until_complete(
            asyncpg.create_pool(**self.config['db']))

        # Cache stuff
        self.stats = {}
        self.prefixes = {}
        self.cache = {}
        self.disabledCommands = []
        self.blacklistedUsers = []
        self.reactionRoleDict = self.loop.run_until_complete(
            self.cache_reactionroles())

        records = self.loop.run_until_complete(
            self.db.fetch("SELECT * FROM blacklist"))
        for i in records:
            self.blacklistedUsers.append(i["id"])

        records = self.loop.run_until_complete(
            self.db.fetch("SELECT * FROM guild_config"))
        self.prefixes = dict(
            self.loop.run_until_complete(
                self.db.fetch("SELECT id, prefix FROM guild_config")))

        for record in records:
            d = self.refresh_template(record)
            self.cache.update(d)

        self.get_announcement()
        self.dagpi_client = Client(self.config['dagpi'])
        self.command_stats = {}
        self.mystbin = mystbin.Client()

        self.load_cogs()
Example #7
0
 async def funky_shit(self):
     """ A quick coro to set the bot's owner. """
     await self.wait_until_ready()
     # if not self.owner_id:
     #     self.owner_id = (await self.application_info()).owner.id
     if not self.session:
         self.session = aiohttp.ClientSession()
     if not self.mb_client:
         self.mb_client = mystbin.Client(session=self.session)
 def run(self, *args, **kwargs):
     # self.ipc.start()
     subprocess.check_output("pip install speedtest-cli", shell=True)
     self.before_invoke(self.start_typing)
     self.utils = utils
     self.deleted_message_cache = LimitedSizeDict()
     self.concurrency = []
     self.color = 0x00ff6a
     self.psutil_process = psutil.Process()
     self._message_cache = {}
     self.prefixes = {}
     self.socket_receive = 0
     self.start_time = time.time()
     self.socket_stats = Counter()
     self.command_counter = 0
     self.commandsusages = Counter()
     self.session = aiohttp.ClientSession(
         headers={
             "User-Agent":
             f"python-requests/2.25.1 The Anime Bot/1.1.0 Python/{sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]} aiohttp/{aiohttp.__version__}"
         })
     self.mystbin = mystbin.Client(session=self.session)
     self.vacefron_api = vacefron.Client(session=self.session,
                                         loop=self.loop)
     self.dag = Client(api_token, session=self.session, loop=self.loop)
     self.alex = alexflipnote.Client(alex_,
                                     session=self.session,
                                     loop=self.loop)
     self.ball = eight_ball.ball()
     self.zaneapi = aiozaneapi.Client(zane_api)
     for command in self.commands:
         self.command_list.append(str(command))
         self.command_list.extend([alias for alias in command.aliases])
         if isinstance(command, commands.Group):
             for subcommand in command.commands:
                 self.command_list.append(str(subcommand))
                 self.command_list.extend([
                     f"{command} {subcommand_alias}"
                     for subcommand_alias in subcommand.aliases
                 ])
                 if isinstance(subcommand, commands.Group):
                     for subcommand2 in subcommand.commands:
                         self.command_list.append(str(subcommand2))
                         self.command_list.extend([
                             f"{subcommand} {subcommand2_alias}"
                             for subcommand2_alias in subcommand2.aliases
                         ])
                         if isinstance(subcommand2, commands.Group):
                             for subcommand3 in subcommand2.commands:
                                 self.command_list.append(str(subcommand3))
                                 self.command_list.extend([
                                     f"{subcommand2} {subcommand3_alias}"
                                     for subcommand3_alias in
                                     subcommand3.aliases
                                 ])
     super().run(*args, **kwargs)
Example #9
0
    def __init__(self) -> None:
        super().__init__(
            status=discord.Status.dnd,
            activity=discord.Activity(type=discord.ActivityType.playing,
                                      name="aaaaa!"),
            allowed_mentions=discord.AllowedMentions(everyone=False,
                                                     users=True,
                                                     roles=True,
                                                     replied_user=False),
            help_command=custom.HelpCommand(),
            intents=discord.Intents.all(),
            command_prefix=self.get_prefix,
            case_insensitive=True,
            owner_ids=config.OWNER_IDS,
        )
        self._BotBase__cogs = commands.core._CaseInsensitiveDict()

        self.session: aiohttp.ClientSession = aiohttp.ClientSession()
        self.process: psutil.Process = psutil.Process()
        self.socket_stats: collections.Counter = collections.Counter()

        self.ERROR_LOG: discord.Webhook = discord.Webhook.from_url(
            session=self.session, url=config.ERROR_WEBHOOK_URL)
        self.GUILD_LOG: discord.Webhook = discord.Webhook.from_url(
            session=self.session, url=config.GUILD_WEBHOOK_URL)
        self.DMS_LOG: discord.Webhook = discord.Webhook.from_url(
            session=self.session, url=config.DM_WEBHOOK_URL)

        self.db: asyncpg.Pool = utils.MISSING
        self.redis: aioredis.Redis | None = None

        self.scheduler: aioscheduler.Manager = aioscheduler.Manager()
        self.mystbin: mystbin.Client = mystbin.Client(session=self.session)
        self.slate: obsidian.NodePool[Life, custom.Context,
                                      custom.Player] = obsidian.NodePool()
        self.ipc: ipc.Server = ipc.Server(bot=self,
                                          secret_key=config.SECRET_KEY,
                                          multicast_port=config.MULTICAST_PORT)

        self.topgg: topgg.DBLClient | None = topgg.DBLClient(
            bot=self, token=config.TOPGG, autopost=True
        ) if config.ENV is enums.Environment.PRODUCTION else None

        self.user_manager: managers.UserManager = managers.UserManager(
            bot=self)
        self.guild_manager: managers.GuildManager = managers.GuildManager(
            bot=self)

        self.first_ready: bool = True
        self.start_time: float = time.time()

        self.add_check(checks.global_check, call_once=True)  # type: ignore

        self.converters |= values.CONVERTERS
Example #10
0
    async def look_at(self, ctx):
        if isinstance(ctx.message.channel, discord.TextChannel):
            message_emojis = ""
            for x in ctx.guild.emojis:
                message_emojis = message_emojis + " " + str(x) + "\n"
            mystbin_client = mystbin.Client(session=self.client.session)
            paste = await mystbin_client.post(message_emojis)
            await ctx.send(paste.url)

        if isinstance(ctx.channel, discord.DMChannel):
            await ctx.send("We can't use that in DMS")
Example #11
0
    def __init__(self):
        intents = discord.Intents.all()

        super().__init__(
            command_prefix=_prefix_callable,
            description=DESCRIPTION,
            allowed_mentions=discord.AllowedMentions.none(),
            intents=intents,
            application_id=565095015874035742,
        )
        self.session = aiohttp.ClientSession()
        self.mb_client = mystbin.Client(session=self.session)
        self.hentai_client = nhentaio.Client()
        md_user = config.mangadex_auth["username"]
        assert md_user is not None
        md_pass = config.mangadex_auth["password"]
        assert md_pass is not None
        md_token = config.mangadex_auth["refresh_token"]
        self.manga_client = hondana.Client(username=md_user,
                                           password=md_pass,
                                           refresh_token=md_token)
        self._prev_events = deque(maxlen=10)
        self.prefixes = Config("prefixes.json")
        self.blacklist = Config("blacklist.json")

        self.emoji = {
            True: "<:TickYes:735498312861351937>",
            False: "<:CrossNo:735498453181923377>",
            None: "<:QuestionMaybe:738038828928860269>",
        }
        self.colour: discord.Colour = discord.Colour(0xEC9FED)

        # in case of even further spam, add a cooldown mapping
        # for people who excessively spam commands
        self.spam_control = commands.CooldownMapping.from_cooldown(
            10, 12.0, commands.BucketType.user)

        # A counter to auto-ban frequent spammers
        # Triggering the rate limit 5 times in a row will auto-ban the user from the bot.
        self._auto_spam_count = Counter()

        for extension in EXTENSIONS:
            try:
                self.load_extension(extension)
            except Exception:
                print(f"Failed to load extension {extension}.",
                      file=sys.stderr)
                traceback.print_exc()
Example #12
0
    def __init__(self, **kwargs):
        super().__init__(
            **kwargs,
            command_prefix=get_prefix,
            owner_ids=[668906205799907348, 746807014658801704],
            case_insensitive=True,
        )

        # Cogs

        self.coglist = [
            f"cogs.{item[:-3]}"
            for item in os.listdir("/storage/emulated/0/PacMe/cogs")
            if item != "__pycache__"
        ] + ["jishaku"] + ["listeners.error"]
        for extension in self.coglist:
            try:
                self.load_extension(extension)
            except Exception as e:
                print(e)

        # Cache

        self.cache = {}

        # Config
        self.ipc = ipc.Server(self, secret_key="ConfirmItsMe")
        self._token = secret_file["token"]
        self.dagpi = secret_file["dagpi"]
        self.asyncpg = secret_file['postgres']
        self.blacklist = set()
        self.embed_color = 0x8936FF
        self.embed_colour = self.embed_color
        self.maint = False
        self.maintenence = False
        self._underscore = True
        self.mystbin = mystbin.Client()
        self.start_time = datetime.datetime.utcnow()
        self.emoji_dict = {
            "greyTick": "<:greyTick:596576672900186113>",
            "greenTick": "<:greenTick:820316551340490752>",
            "redTick": "<:redTick:820319748561829949>",
            "dpy": "<:dpy:596577034537402378>",
            "py": "<:python:286529073445076992>"
        }
        self.custom_errors = utils.errors
Example #13
0
	def __init__(self):
		super().__init__(
			command_prefix=get_prefix,
			description="A multipurpose discord bot made in python.",
			intents=intents,
			case_insensitive=True,
			owner_ids=[int(owner_id)
					   for owner_id in os.environ.get("OWNERIDS").split(" ")],
			allowed_mentions=mentions
		)
		self.ready = False
		self.__name__ = 'Saturn'
		self.src = 'https://github.com/SynchronousDev/saturn-discord-bot'

		self.path = str(Path(__file__).parents[0])
		self.__version__ = '1.1.0'

		self.mongo_connection_url = os.environ.get("MONGO")
		self.TOKEN = os.environ.get("TOKEN")

		self.edit_snipes = {}
		self.snipes = {}
		self.banned_users = {}
		self.muted_users = {}
		self.message_cache = {}

		self.mongo = motor.motor_asyncio.AsyncIOMotorClient(
			str(self.mongo_connection_url))
		self.db = self.mongo[self.__name__]
		self.config = self.db["config"]
		self.mutes = self.db["mutes"]
		self.blacklists = self.db["blacklists"]
		self.tags = self.db["tags"]
		self.mod = self.db["mod"]
		self.bans = self.db["bans"]
		self.starboard = self.db["starboard"]

		self.paste = mystbin.Client()

		self.topgg_client = topgg.DBLClient(self, os.environ.get(
			"TOPGGTOKEN"), autopost=False)
		self.topgg_webhook = topgg.WebhookManager(
			self).dbl_webhook("/dblwebhook", os.environ.get("TOPGGAUTH"))
		self.topgg_webhook.run(5678)
Example #14
0
    def __init__(self):
        intents = discord.Intents.all()

        super().__init__(
            command_prefix=_prefix_callable,
            description=DESCRIPTION,
            activity=discord.Game(name="a!help for help."),
            allowed_mentions=discord.AllowedMentions.none(),
            intents=intents,
        )
        self.session = aiohttp.ClientSession()
        self.mb_client = mystbin.Client(session=self.session)
        self.hentai_client = nhentaio.Client()
        self._prev_events = deque(maxlen=10)
        self.prefixes = Config("prefixes.json")
        self.blacklist = Config("blacklist.json")

        self.emoji = {
            True: "<:TickYes:735498312861351937>",
            False: "<:CrossNo:735498453181923377>",
            None: "<:QuestionMaybe:738038828928860269>",
        }
        self.colour: Dict[str, Union[Tuple[int, ...], discord.Colour]] = {
            "dsc": discord.Colour(0xEC9FED),
            "rgb": (236, 159, 237),
            "hsv": (299, 33, 93),
        }

        # in case of even further spam, add a cooldown mapping
        # for people who excessively spam commands
        self.spam_control = commands.CooldownMapping.from_cooldown(
            10, 12.0, commands.BucketType.user)

        # A counter to auto-ban frequent spammers
        # Triggering the rate limit 5 times in a row will auto-ban the user from the bot.
        self._auto_spam_count = Counter()

        for extension in EXTENSIONS:
            try:
                self.load_extension(extension)
            except Exception:
                print(f"Failed to load extension {extension}.",
                      file=sys.stderr)
                traceback.print_exc()
Example #15
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.remove_command('help')
     self._commands = 0
     self.currency_cache = {}
     self.session = ClientSession(loop=self.loop)
     self.dag = Client(dagpi_token, loop=self.loop)
     self.mystbin = mystbin.Client()
     self._start = time.time()
     self._prefixes = json.load(open('./prefixes.json', 'r'))
     self._banned = json.load(open('./bans.json', 'r'))
     self._edit_cache = {}
     self.cse = cse.Search(google_key)
     self.ipc = ipc.Server(self, 'localhost', 8080, secret_key=ipc_key)
     self.ball = ball()
     self.load_extension('jishaku')
     os.environ["JISHAKU_NO_UNDERSCORE"] = "true"
     os.environ["JISHAKU_NO_DM_TRACEBACK"] = "true"
     os.environ["JISHAKU_HIDE"] = "true"
Example #16
0
 async def text_backup(self, ctx):
     if ctx.message.attachments:
         for x in ctx.message.attachments:
             file = await x.read()
             if len(file) > 0:
                 encoding = chardet.detect(file)["encoding"]
                 if encoding:
                     text = file.decode(encoding)
                     mystbin_client = mystbin.Client(
                         session=self.client.session)
                     paste = await mystbin_client.post(text)
                     await ctx.send(
                         content=f"Added text file to mystbin: \n{paste.url}"
                     )
                 if encoding is None:
                     await ctx.send(
                         "it looks like it couldn't decode this file, if this is an issue DM JDJG Inc. Official#3439 or it wasn't a text file."
                     )
             if len(file) < 1:
                 await ctx.send("this doesn't contain any bytes.")
Example #17
0
 async def setup_hook(self) -> None:
     self.session: ClientSession = ClientSession()
     self.cache: Cache = Cache(self)
     self.pool: asyncpg.Pool = await asyncpg.create_pool(
         **self.settings["postgresql"])
     self.topgg: DBLClient = DBLClient(self,
                                       self.api["TopGG"],
                                       autopost_interval=None,
                                       session=self.session)
     self.topgg_webhook: WebhookManager = WebhookManager(self).dbl_webhook(
         "/dbl", self.api["TopGGWH"])
     self.gist: asyncgist.Client = asyncgist.Client(self.api["GitHub"],
                                                    self.session)
     self.sr: sr_api.Client = sr_api.Client()
     self.dagpi: asyncdagpi.Client = asyncdagpi.Client(self.api["DagpiAPI"],
                                                       session=self.session)
     self.myst: mystbin.Client = mystbin.Client(session=self.session)
     self.loop.create_task(self.cache.populate_cache())
     self.loop.create_task(self.load_extensions())
     self.loop.create_task(self.start_nodes())
     self.loop.create_task(self.find_restart_message())
     self.topgg_webhook.run(8025)
Example #18
0
                                                          replied_user=False),
                 embed_color=0x31A1F1,
                 activity=activity,
                 owner_ids={447422100798570496})


@bot.event
async def on_ready():
    print("Logged in! \n"
          f"{'-' * 20}\n"
          f"Bot Name: {bot.user} \n"
          f"Bot ID: {bot.user.id} \n"
          f"{'-' * 20}")


bot.mystbin = mystbin.Client()


@bot.event
async def on_error(event, *args, **kwargs):
    ignored_events = ["on_member_join", "on_message", "on_raw_reaction_add"]
    if event in ignored_events:
        return
    else:
        raise


if __name__ == "__main__":
    bot.ipc.start()
    for extension in startup_extensions:
        try:
 def __init__(self, bot):
     self.bot = bot
     self.mystbin_client = mystbin.Client()
     self.description = "Some random fun and usefull commands."
Example #20
0


async def get_prefix(bot, message):
    if message.guild is None:
        prefixes = ["th,", "th.", "th ", "please dont find this one, "]
    elif message.author.id == 787800565512929321:
        prefixes = ["th,", "th.", "th ", ""]
    else:
        prefixes = ["th,", "th.", "th ", "please dont find this one,"]

    return commands.when_mentioned_or(*prefixes)(bot, message)

bot = commands.Bot(command_prefix=get_prefix, intents=intents, help_command=Help(),  allowed_mentions=discord.AllowedMentions(users=True, roles=False, everyone=False, replied_user=True),case_insensitive=True)
bot.db = aiosqlite.connect("main.sqlite")
bot.mystbin_client = mystbin.Client()
bot.version = "15"
START_BAL = 250
token = open("toke.txt", "r").read()
bot.load_extension("jishaku")
hce = bot.get_command("help")
hce.hidden = True
dagpitoken = open("asy.txt", "r").read()
robloxcookie = open("roblox.txt", "r").read()
topastoken = open("top.txt", "r").read()
chatbottoken = open("chat.txt", "r").read()
hypixel = open("hypixel.txt", "r").read()
bot.robloxc = f"{robloxcookie}"
bot.hypixel = f"{hypixel}"
bot.topken = f"{topastoken}"
bot.chatbot = ac.Cleverbot(f"{chatbottoken}")
Example #21
0
 def __init__(self, bot):
     self.bot = bot
     self.myst = mystbin.Client()
     self.translator = google_translator()
Example #22
0
 def __init__(self, bot):
     self.bot = bot
     self.session = aiohttp.ClientSession()
     self.myst = mystbin.Client()
Example #23
0
 def __init__(self, bot):
     self.bot = bot
     self.mystbin = mystbin.Client()
Example #24
0
    def __init__(self, bot: Life) -> None:
        self.bot = bot

        self.bot.error_formatter = prettify_exceptions.DefaultFormatter()
        self.bot.mystbin = mystbin.Client()