Beispiel #1
0
 async def reload_extension(self, extension_name):
     name = extension_name.replace('-', '.')
     try:
         self.bot.reload_extension(name)
     except discord.ext.commands.errors.ExtensionNotLoaded as e:
         logger.exception("Couldn't load extension")
         return {"message": f"Extension Not Loaded: {e}"}, sc.SERVICE_UNAVAILABLE_503
     return {"message": "Reload signal sent"}, sc.OK_200
Beispiel #2
0
 async def on_member_join(self, member):
     logger.info("%s joined guild: %s" % (member.name, member.guild.name))
     settings = self.bot.settings[member.guild]
     try:
         default_role = discord.utils.get(member.guild.roles, id=settings.default_role_id)
         await member.add_roles(default_role)
     except Exception:
         logger.exception("could not add %s to %s" % (member.display_name, 'default role'))
Beispiel #3
0
    async def set(self, ctx, *args):
        """
        Sets an auto response
        use the syntax 'set trigger::response'
        check out the docs for advanced options:
        https://docs.archit.us/features/auto-responses/
        """
        settings = self.bot.settings[ctx.guild]
        prefix = re.escape(settings.command_prefix)

        match = re.match(f'{prefix}set (.+?)::(.+)', ctx.message.content,
                         re.IGNORECASE)
        if match:
            try:
                resp = await self.responses[ctx.guild.id].new_response(
                    match[1], match[2], ctx.guild, ctx.author)
            except TriggerCollisionException as e:
                msg = "❌ sorry that trigger collides with the following auto responses:\n"
                msg += '\n'.join([f"`{r}`" for r in e.conflicts[:4]])
                if len(e.conflicts) > 4:
                    msg += f"\n_...{len(e.conflicts) - 4} more not shown_"
                await ctx.send(msg)
            except LongResponseException:
                await ctx.send(
                    f"❌ that response is too long :confused: max length is "
                    f"{settings.responses_response_length} characters")
            except ShortTriggerException:
                await ctx.send(
                    f"❌ please make your trigger longer than {settings.responses_trigger_length} characters"
                )
            except UserLimitException:
                await ctx.send(
                    f"❌ looks like you've already used all your auto responses "
                    f"in this server ({settings.responses_limit}), try deleting some"
                )
            except ParseError as e:
                await ctx.send(f"❌ unable to parse that response: `{e}`")
            except NotParseable as e:
                await ctx.send(f"❌ unable to parse your trigger: `{e}`")
            except DisabledException as e:
                await ctx.send(
                    f"❌ {e} disabled, you can enable in `{settings.command_prefix}settings responses`"
                )
            except Exception:
                logger.exception("")
                await ctx.send("❌ unknown error 😵")
            else:
                await ctx.send(f"✅ `{resp}` _successfully set_")
        else:
            match = re.match(f'{prefix}set (.+?):(.+)', ctx.message.content,
                             re.IGNORECASE)
            if match:
                await ctx.send(
                    f"❌ **nice brain** use two `::`\n`{prefix}set {match[1]}::{match[2]}`"
                )
            else:
                await ctx.send("❌ use the syntax: `trigger::response`")
Beispiel #4
0
 def _run(self):
     while self.taskQueue.empty() is not True:
         try:
             oneTask = self.taskQueue.get(block=False)
             func = oneTask[0]
             args = oneTask[1]
             func(args[0], args[1], args[2])
         except Exception as E:
             logger.exception(E)
Beispiel #5
0
    def agane(self, trash):
        if self.playing_file:
            return

        if len(self.q) == 0:
            coro = self.voice.disconnect()
        else:
            coro = self.play()
        fut = asyncio.run_coroutine_threadsafe(coro, self.bot.loop)
        try:
            fut.result()
        except Exception:
            logger.exception('error playing next thing')
Beispiel #6
0
 async def notify_deletion(self, emoji: discord.Emoji) -> None:
     """send a dm to whomever's emoji we just deleted"""
     user = emoji.user
     if user is None:
         logger.debug("I don't know who created this emoji")
         return
     try:
         await user.send(
             f"**Notice:** your emoji has been deleted from {self.guild.name} because it is a duplicate.\n"
             f"Type the emoji name as you normally would (`:{emoji.name}:`) if it was cached.\n"
             f"emoji: {emoji.url}")
     except Exception:
         logger.exception('')
Beispiel #7
0
    async def play_file(self, filepath):
        self.playing_file = True
        self.stop()
        if self.voice is None:
            return
        # if (self.player and self.player.is_playing()):
            # return await self.skip()

        try:
            self.player = self.voice.create_ffmpeg_player(filepath, after=self.agane, stderr=subprocess.STDOUT)
            self.player.start()
        except Exception:
            logger.exception("can't create new player")
        self.playing_file = False
        return True
Beispiel #8
0
 async def get_value(self, ctx, settings):
     await ctx.send(self.description)
     user_msg = await ctx.bot.wait_for(
         'message', check=lambda m: m.author == ctx.author and self.check(m))
     try:
         value = await self.parse(ctx, user_msg, settings)
     except ValueError:
         await ctx.send(self.failure_msg)
     except Exception:
         await ctx.send("Something bad happened... try again?")
         logger.exception(f"Caught exception, continuing...")
         return
     else:
         setattr(settings, self.setting, value)
         await ctx.send(self.success_msg)
Beispiel #9
0
 async def cache_guild(self, guild):
     '''cache interesting information about all the messages in a guild'''
     logger.debug(f"Downloading messages in {len(guild.channels)} channels for '{guild.name}'...")
     for channel in guild.text_channels:
         try:
             await self.cache_channel(channel)
         except Forbidden:
             logger.warning(f"Insuffcient permissions to download messages from '{guild.name}.{channel.name}'")
         except HTTPException as e:
             logger.error(f"Caught {e} when downloading '{guild.name}.{channel.name}'")
             logger.error("trying again in 10 seconds...")
             await asyncio.sleep(10)
             try:
                 await self.cache_channel(channel)
             except Exception:
                 logger.exception("failed to download channel a second time, giving up :(")
Beispiel #10
0
    async def scan(self, msg):
        """scans a message for cached emoji and, if it finds any, loads the emoji and replaces the message"""
        if msg.author.bot:
            return
        content = msg.content
        matches = self.emoji_pattern.finditer(content)
        replace = False
        did_match = False

        for match in matches:
            did_match = True
            if match['nameonly']:
                emoji = self.find_emoji(name=match['nameonly'])
                if emoji is not None:
                    emoji.num_uses += 1
                    replace = replace if emoji.loaded else True
                    await self.bump_emoji(emoji)
                    content = content.replace(f":{emoji.name}:",
                                              emoji.to_discord_str())
            else:
                emoji = self.find_emoji(d_id=match['id'],
                                        a_id=match['id'],
                                        name=match['name'])
                if emoji is not None:
                    emoji.num_uses += 1
                    replace = replace if emoji.loaded else True
                    await self.bump_emoji(emoji)
                    content = content.replace(f"<:{emoji.name}:{match['id']}>",
                                              emoji.to_discord_str())
        if did_match:
            await self._update_emojis_db(self.emojis)
        if replace and self.settings.manage_emojis:
            try:
                await send_message_webhook(
                    msg.channel,
                    content,
                    username=msg.author.display_name,
                    avatar_url=str(msg.author.avatar_url_as(format='png')))
            except Exception:
                logger.exception(f"Couldn't send message with webhook")
            else:
                self.bot.deletable_messages.append(msg.id)
                await msg.delete()
Beispiel #11
0
    async def api_entry(self, method_name, *args, **kwargs):
        """Callback method for the rpc server

        :param method_name: name of the method to execute
        :param *args: args to pass through
        :param **kwargs: kwargs to pass through
        """
        try:
            assert not method_name.startswith('_')
            method = getattr(self, method_name)
        except (AttributeError, AssertionError):
            logger.warning(f"Someone tried to call '{method}' but it doesn't exist (or is private)")
            return {"message": "No such method"}, sc.NOT_FOUND_404

        try:
            return await method(*args, **kwargs)
        except Exception as e:
            logger.exception(f"caught exception while handling remote request")
            return {"message": f"'{e}'"}, sc.INTERNAL_SERVER_ERROR_500
Beispiel #12
0
async def quote(ctx, message: discord.Message):
    '''Quotes a previous message in a pretty format. Use url or id.'''

    utc = message.created_at.replace(tzinfo=timezone('UTC'))
    est = utc.astimezone(timezone('US/Eastern'))
    em = discord.Embed(title=est.strftime("%Y-%m-%d %I:%M %p"),
                       description=message.content,
                       colour=0x42f468)
    em.set_author(name=message.author.display_name,
                  icon_url=message.author.avatar_url)
    em.set_footer(text='#' + message.channel.name)
    try:
        if message.embeds:
            em.set_image(url=message.embeds[0].url)
        elif message.attachments:
            em.set_image(url=message.attachments[0].url)
    except (IndexError, KeyError):
        logger.exception("tried to attach image, couldn't")
    await ctx.channel.send(embed=em)
Beispiel #13
0
 def login(self, ipaddress, port, user_passwd_pair_list):
     try:
         conn = pymongo.MongoClient(ipaddress, port)
         dbname = conn.list_database_names()
         log_success("MongoDB", ipaddress, port, None)
         conn.close()
         return
     except Exception as E:
         logger.debug(E)
     finally:
         pass
     for user_passwd_pair in user_passwd_pair_list:
         try:
             client = pymongo.MongoClient(
                 host=ipaddress,
                 port=port,
                 maxIdleTimeMS=int(self.timeout * 1000),
                 socketTimeoutMS=int(self.timeout * 1000),
                 connectTimeoutMS=int(self.timeout * 1000),
                 serverSelectionTimeoutMS=int(self.timeout * 1000),
                 waitQueueTimeoutMS=int(self.timeout * 1000),
                 wTimeoutMS=int(self.timeout * 1000),
                 socketKeepAlive=False,
                 connect=False
             )
         except Exception as E:
             logger.exception(E)
             logger.debug('ConnectException: {} {} {}'.format(E, ipaddress, port))
             return
         try:
             db = client.admin
             db.authenticate(user_passwd_pair[0], user_passwd_pair[1])
             log_success("MongoDB", ipaddress, port, user_passwd_pair)
         except Exception as E:
             logger.debug('AuthenticationException: %s' % E)
             continue
         finally:
             client.close()
             pass
Beispiel #14
0
 async def pool_request(self,
                        guild_id,
                        pool_type: str,
                        entity_id,
                        fetch=False):
     guild = self.bot.get_guild(int(guild_id)) if guild_id else None
     try:
         if pool_type == PoolType.MEMBER:
             return {
                 'data': await
                 self.pools.get_member(guild, entity_id, fetch)
             }, 200
         elif pool_type == PoolType.USER:
             return {
                 'data': await self.pools.get_user(entity_id, fetch)
             }, 200
         elif pool_type == PoolType.EMOJI:
             return {
                 'data': await self.pools.get_emoji(guild, entity_id, fetch)
             }, 200
     except Exception:
         logger.exception('')
         return {'data': {}}, sc.NOT_FOUND_404
Beispiel #15
0
 async def handle_task(self, method, *args, **kwargs):
     try:
         return (await (getattr(self, method)(*args, **kwargs)), 200)
     except Exception as e:
         logger.exception(f"caught: '{e}' while executing '{method}'")
         return {'message': f"caught: '{e}' while executing '{method}'"}
Beispiel #16
0
    async def gulag(self, ctx, comrade: discord.Member):
        '''
        Starts a vote to move a member to the gulag.
        Each vote over the threshold will add additional time.
        '''
        settings = self.bot.settings[ctx.guild]
        filtered = filter(lambda role: role.name == "kulak", ctx.guild.roles)
        try:
            gulag_role = next(filtered)
            gulag_emoji = settings.gulag_emoji
            assert gulag_emoji is not None
        except Exception:
            logger.warning("gulag role/emoji not found")
            await ctx.send(
                "Please create a role called `kulak` and an emoji called `gulag` to use this feature."
            )
            return
        if comrade == self.bot.user:
            await ctx.channel.send(file=discord.File('res/treason.gif'))
            comrade = ctx.author

        t_end = time.time() + 60 * 30
        user_list = []
        timer_msg = None
        timer_msg_gulag = None
        generated = False
        msg = await ctx.send(
            f"{settings.gulag_threshold} more {gulag_emoji}'s to gulag {comrade.display_name}"
        )
        await msg.add_reaction(gulag_emoji)
        while time.time() < t_end:
            user = None

            def check(r, u):
                return r.message.id == msg.id and str(r.emoji) == gulag_emoji

            with suppress(asyncio.TimeoutError):
                react, user = await self.bot.wait_for('reaction_add',
                                                      timeout=5,
                                                      check=check)

            if user and user not in user_list and user != self.bot.user:
                user_list.append(user)
                await msg.edit(
                    content=
                    f"{max(0, (settings.gulag_threshold - len(user_list)))} more {gulag_emoji}'s "
                    f"to gulag {comrade.display_name}")
                t_end += int((settings.gulag_severity / 2) * 60)
            if len(
                    user_list
            ) >= settings.gulag_threshold and gulag_role not in comrade.roles:
                try:
                    logger.debug(comrade.avatar_url)
                    img = gulaggen.generate(await comrade.avatar_url_as(
                        format='png', size=1024).read())
                    generated = True
                except Exception:
                    logger.exception("gulag generator error")
                    pass
                if generated:
                    await ctx.channel.send(file=discord.File(
                        img,
                        filename=f'{self.bot.hoarfrost_gen.generate()}.png'))
                else:
                    await ctx.channel.send(f"gulag'd {comrade.display_name}")

                timer_msg = await ctx.channel.send(
                    f"⏰ {int(settings.gulag_severity * 60)} seconds")
                with suppress(AttributeError):
                    timer_msg_gulag = await (
                        discord.utils.get(ctx.guild.text_channels,
                                          name='gulag')
                    ).send(
                        f"⏰ {int(settings.gulag_severity * 60)} seconds, {comrade.display_name}"
                    )
                await comrade.add_roles(gulag_role)

                t_end = time.time() + int(60 * settings.gulag_severity)

            elif timer_msg or timer_msg_gulag:
                await timer_msg.edit(
                    content=f"⏰ {int(max(0, t_end - time.time()))} seconds")
                with suppress(AttributeError):
                    await timer_msg_gulag.edit(
                        content=f"⏰ {int(max(0, t_end - time.time()))} seconds,"
                        f" {comrade.display_name}")

        if gulag_role not in comrade.roles:
            await msg.edit(
                content=f"Vote for {comrade.display_name} failed to pass")

        await comrade.remove_roles(gulag_role)
        logger.info('ungulag\'d ' + comrade.display_name)
Beispiel #17
0
from ftplib import FTP

from bruteforce.password import Password_total
from lib.config import logger, log_success

SSL_FLAG = True

try:
    import bmemcached
    import pymongo
    import pymysql
    import redis
    from pssh.clients import ParallelSSHClient
    from impacket.smbconnection import SMBConnection
except Exception as E:
    logger.exception(E)
try:
    from bruteforce.rdp_check import check_rdp
    import psycopg2
except Exception as E:
    SSL_FLAG = False

import gevent
from Crypto.Cipher import DES
from gevent import socket
from gevent.monkey import patch_all


class SSH_login(object):
    def __init__(self, timeout=1):
        self.timeout = timeout