Esempio n. 1
0
    async def unmute(self, ctx, user: str):
        """Unmute command"""

        server = ctx.message.server

        # Check for permissions before proceed
        if not commands.bot_has_permissions(manage_roles=True):
            await self.bot.say(
                "I'm not able to manage permissions without `Manage Roles` permission."
            )
            return
        elif not not commands.bot_has_permissions(mute_members=True):
            await self.bot.say(
                "I'm not able to mute voice without `Mute Members` permission."
            )

        members = await utils.get_members(self.bot, ctx.message, user)

        if members is None:
            return

        member = ctx.message.server.get_member_named(members[0])

        # Reset permissions
        await self.set_permissions(server, member, None)

        # Remove mute task for a member and remove him from database
        if member.id in self.timers_storage[server.id]:
            self.timers_storage[server.id][member.id].cancel()
            self.remove_muted_member(member, server)

        await self.send("Member {} has been unmuted by command.".format(
            member.name))
Esempio n. 2
0
    def __init__(self, config: configparser.ConfigParser,
                 redis: aredis.StrictRedis, **kwargs):
        super().__init__(activity=discord.Activity(
            name='out for new incidents', type=discord.ActivityType.watching),
                         command_prefix=self.get_command_prefix,
                         intents=INTENTS,
                         **kwargs)
        self.config = config
        self.default_prefix = self.config.get('general', 'default_prefix')
        # eval() for supporting hex colors, should be safe because it's
        # directly from the config
        self.colorsg = {
            key: eval(value)
            for key, value in self.config.items('colors:generic')
        }

        self.errorlog = None
        if self.config.getboolean('errorlog', 'enabled'):
            self.errorlog = Path(self.config.get('errorlog', 'path'))

        self.storage = Storage(redis)
        self.shoppy = httpx.AsyncClient(headers={
            'Authorization':
            self.config.get('shoppy', 'api key'),
            'User-Agent':
            'python-httpx (Incident Reporter Bot)'
        },
                                        base_url='https://shoppy.gg/')

        self._loaded_extensions = False

        self.add_check(
            commands.bot_has_permissions(embed_links=True).predicate,
            call_once=True)
        self.add_check(is_guild_banned().predicate, call_once=True)
Esempio n. 3
0
def has_perms():
    perms = {
        'send_messages': True,
        'embed_links': True,
        'external_emojis': True
    }

    return commands.bot_has_permissions(**perms)
Esempio n. 4
0
def setup(bot):
    bot._original_help_command = bot.help_command

    bot.help_command = MyHelp(
        command_attrs={"brief": "Get information about my commands!"})
    bot.help_command.add_check(
        commands.bot_has_permissions(embed_links=True, send_messages=True))
    bot.help_command.cog = bot.cogs["Info"]
Esempio n. 5
0
    def __init__(self, bot: TTSBot):
        help_command = FancyHelpCommand()

        bot.help_command = help_command
        bot.help_command.cog = self
        bot.help_command.add_check(
            commands.bot_has_permissions(
                send_messages=True, embed_links=True).predicate  # type: ignore
        )
Esempio n. 6
0
async def on_member_join(user):
    channel = user.guild.system_channel
    if commands.bot_has_permissions(send_message=False):
        return
    with open('./cogs/fun/JoinMessages.json') as f:
        d = json.load(f)

    greeting = random.choice(list(d.values()))
    if channel is not None:
        await channel.send(f"*{greeting.replace('{user}', f'**{user}**')}*")
Esempio n. 7
0
    async def unmute(self, ctx, user : discord.Member=None):
        """- Unmute command"""
        server = ctx.message.guild

        #check for permissions before proceeding
        if not commands.bot_has_permissions(manage_roles=True):
            await ctx.message.channel.send("I'm not able to manage permissions without `Manage Roles` permission.")
        elif not commands.bot_has_permissions(mute_members=True):
            await ctx.message.channel.send("I'm not able to mute voice without `Mute Members` permission.")

        if not user:
            await ctx.message.channel.send("Specify a user, fren")
        
        #reset permissions
        await self.set_permission(server, user, None)

        #remove mute task for a member and remove him from database
        if user.id in self.timers_storage[server.id]:
            self.timers_storage[server.id][user.id].cancel()
            self.remove_muted_member(user, server)
        
        await ctx.message.channel.send("Member {} has been unmuted by command.".format(user.name))
Esempio n. 8
0
    def __init__(self, **kwargs):
        self.cluster_name = kwargs.pop("cluster_name")
        self.cluster_idx = kwargs.pop("cluster_idx")
        self.config = kwargs.pop("config", None)
        if self.config is None:
            self.config = __import__("config")

        self.ready = False
        self.menus = {}

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        super().__init__(**kwargs, loop=loop, command_prefix=determine_prefix)

        # Load extensions

        self.load_extension("jishaku")
        for i in cogs.default:
            self.load_extension(f"cogs.{i}")

        self.add_check(
            commands.bot_has_permissions(
                read_messages=True,
                send_messages=True,
                embed_links=True,
                attach_files=True,
                read_message_history=True,
                add_reactions=True,
                external_emojis=True,
            ).predicate)
        self.add_check(is_enabled)

        # Run bot

        self.log.info(
            f'[Cluster#{self.cluster_name}] {kwargs["shard_ids"]}, {kwargs["shard_count"]}'
        )

        self.loop.create_task(self.do_startup_tasks())
        self.run(kwargs["token"])
Esempio n. 9
0
    async def on_message(self, message):

        if not self.bot.ready():
            return

        user = message.author
        stats = self.bot.stats

        if user.bot:
            return
        if not commands.bot_has_permissions(send_messages=True):
            stats.other_messages_processed += 1
            return
        if str(message.channel.type) == "private":
            guild_id = fn.guild.id
        else:
            guild_id = message.guild.id

        prefix = fn.getprefix(self.bot, message)
        commandcheck = message.content[len(prefix):]
        for command in cm.commands:
            if commandcheck.startswith(command):
                return
        for command in cm.devcmds:
            if commandcheck.startswith(command):
                return

        priority, status = "all", "on"
        if str(message.channel.type) != "private":
            db.addchannel(message.channel.id, guild_id)
            priority = db.getpriority(guild_id)
            status = db.getstatus(message.channel.id)
        if status == "on":
            trigger_detected = tr.respond(message, priority)[0]
            if trigger_detected:
                stats.triggers_processed += 1
                db.usetrigger(user.id)
                return
        stats.other_messages_processed += 1
Esempio n. 10
0
    def __init__(self, **kwargs):
        self.cluster_name = kwargs.pop("cluster_name")
        self.cluster_idx = kwargs.pop("cluster_idx")
        self.config = kwargs.pop("config", None)
        if self.config is None:
            self.config = __import__("config")

        self.ready = False
        self.menus = ExpiringDict(max_len=300, max_age_seconds=300)

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        super().__init__(**kwargs, loop=loop, command_prefix=determine_prefix)

        # Load extensions

        self.load_extension("jishaku")
        for i in cogs.default:
            self.load_extension(f"cogs.{i}")

        self.add_check(
            commands.bot_has_permissions(
                read_messages=True,
                send_messages=True,
                embed_links=True,
                attach_files=True,
                read_message_history=True,
                add_reactions=True,
                external_emojis=True,
            ).predicate)
        self.add_check(is_enabled)

        self.activity = discord.Game("p!help • poketwo.net")
        self.http_session = aiohttp.ClientSession()

        # Run bot

        self.loop.create_task(self.do_startup_tasks())
        self.run(kwargs["token"])
Esempio n. 11
0
    def __init_subclass__(cls,
                          *,
                          game_cls,
                          name=None,
                          cmd=None,
                          aliases=(),
                          **kwargs):
        super().__init_subclass__(**kwargs)

        cls.name = name or cls.__name__
        cls.__game_class__ = game_cls
        cmd_name = cmd or cls.__name__.lower()

        group_help = inspect.getdoc(cls._game).format(name=cls.name)
        # We can't use the decorator because all the check decorator does is
        # add the predicate to an attribute called __commands_checks__, which
        # gets deleted after the first command.
        group = commands.group(name=cmd_name,
                               aliases=aliases,
                               help=group_help,
                               invoke_without_command=True)
        group_command = group(
            commands.bot_has_permissions(embed_links=True)(cls._game))
        setattr(cls, f'{cmd_name}', group_command)

        gc = group_command.command
        for name, member in inspect.getmembers(cls):
            if not name.startswith('_game_'):
                continue

            name = name[6:]

            game_help = inspect.getdoc(member).format(name=cls.name,
                                                      cmd=cmd_name)
            command = gc(name=name, help=game_help)(member)
            setattr(cls, f'{cmd_name}_{name}', command)

        setattr(cls, f'_{cls.__name__}__error', cls._error)
Esempio n. 12
0
    async def mute(self, ctx, user : discord.Member=None, period=''):
        """ - Mute for specific time."""
        amount = 0
        if period:
            amount = int(period[:-1])
            if amount < 0:
                await ctx.message.channel.send("Invalid amount of time, fren")
                return
        
        server = ctx.message.guild

        #Check for permissions before proceeding
        if not commands.bot_has_permissions(manage_roles=True):
            await ctx.message.channel.send("I'm not able to manage permissions without `Manage Roles` permission")
            return
        elif not commands.bot_has_permissions(mute_members=True):
            await ctx.message.channel.send("I'm not able to mute voice without `Mute Members` permission.")

        if not user:
            await ctx.message.channel.send("Specify a user, fren")
        
        #member = ctx.message.guild.get_member_named(user)

        if user.id in self.timers_storage[server.id]:
            await ctx.message.channel.send("This member is already muted, fren")
            return

        #set permissions
        await self.set_permission(server, user, False)

        if amount:
            multiplier = period[-1] if period[-1] in ('s', 'm', 'h', 'd', 'y') else 's'

            def multiply_time(m, secs):
                return {
                    m == 's': secs * 1,
                    m == 'm': secs * 60,
                    m == 'h': secs * 60 * 60,
                    m == 'd': secs * 60 * 60 * 24,
                    m == 'y': secs * 60 * 60 * 24 * 365,
                }[True]

            period = multiply_time(multiplier, amount)
            period *= 10
            
            #Set unmute timer
            unmute_timer = self.bot.loop.create_task(self.unmute_timer(server, user, period))
            self.timers_storage[server.id].update({user.id: unmute_timer})

            #write muted user to database
            db = self.bot.db
            values = (user.id, user.name, period, server.id)
            db.execute("INSERT INTO mutes(member_id, member_name, mute_time, server_id) VALUES (?,?,strftime('%s','now') + ?,?)", values)
            db.commit()

            def convert_time(secs):
                return {
                    1 <= secs < 60: '{} second(s)'.format(secs),
                    60 <= secs < 3600: '{0[0]} minute(s) {0[1]} second(s)'.format(divmod(secs, 60)),
                    3600 <= secs < 86400: '{0[0]} hour(s) {0[1]} minute(s)'.format(divmod(secs, 60 * 60)),
                    86400 <= secs: '{0[0]} day(s) {0[1]} hour(s)'.format(divmod(secs, 60 * 60 * 24)),
                }[True]
            mute_time = convert_time(period)
            
            await ctx.message.channel.send("Member {} has been muted for {}".format(user.name, mute_time))
        else:
            await ctx.message.channel.send("Member {} has been muted permanently".format(user.name))
Esempio n. 13
0
    def __init__(self, **kwargs) -> None:
        self.pipe = kwargs.pop("pipe")
        self.cluster_name = kwargs.pop("cluster_name")

        # We need new loop, because the launcher is using one
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        config = self._load_config()
        self.config = config

        # Default prefix
        self.def_prefix = config['bot']['prefix']
        self._log_webhook = config['bot']['logs-webhook']
        self.maintenance_mode = config['bot']['start-in-maintenance']
        self.is_beta = config['bot']['beta']

        self.ipc_ping = 0

        # Common emojis
        emojis = config['emoji']
        self.check_emoji = emojis['check']
        self.gold_emoji = emojis['gold']
        self.gem_emoji = emojis['gem']
        self.tile_emoji = emojis['farm_tile']
        self.xp_emoji = emojis['xp']
        self.warehouse_emoji = emojis['warehouse']

        self._init_logger()
        self.log.info(f"Shards: {kwargs['shard_ids']}"
                      f", shard count: {kwargs['shard_count']}")

        self.enable_field_guard(config['bot']['startup-farm-guard-duration'])

        try:
            loop.run_until_complete(self._connect_db())
        except Exception:
            self.log.exception("Could not connect to Postgres")

        self._connect_redis()

        self.custom_prefixes = {}

        self.user_cache = UserManager(self.redis, self.db_pool)

        intents = discord.Intents.none()
        intents.guilds = True
        intents.guild_messages = True

        super().__init__(intents=intents,
                         chunk_guilds_at_startup=False,
                         max_messages=7500,
                         command_prefix=self.get_custom_prefix,
                         case_insensitive=True,
                         strip_after_prefix=True,
                         **kwargs,
                         loop=loop)

        self.global_cooldown = commands.CooldownMapping.from_cooldown(
            4, 9, commands.BucketType.user)
        self.spam_control = commands.CooldownMapping.from_cooldown(
            10, 12.0, commands.BucketType.user)
        self._auto_spam_count = Counter()
        self.add_check(self.check_global_cooldown, call_once=True)

        self.add_check(
            commands.bot_has_permissions(read_message_history=True,
                                         embed_links=True,
                                         add_reactions=True).predicate)

        for extension in self.config['bot']['initial-cogs']:
            try:
                self.log.debug(f"Loading extension: {extension}")
                self.load_extension(extension)
            except Exception:
                self.log.exception(f"Failed to load extension: {extension}")

        if self.is_beta:
            self.log.warning("Loading the beta debug extension")
            self.load_extension("bot.cogs.beta")

        self.run()
Esempio n. 14
0
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send(f"Hey, <@{ctx.author.id}>.. {error}!")
        elif isinstance(error, commands.CommandNotFound):
            await ctx.send(
                f"Yo, <@{ctx.author.id}>.. There's no such commands. " +
                "Try checking `a;help`!")
        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send("Not to be rude. But you've got " +
                           f"the parameters wrong, <@{ctx.author.id}>. " +
                           "Don't be lazy and read the `help` command!")
            await asyncio.sleep(0.5)
            await ctx.send_help(ctx.command)
        elif isinstance(error, commands.MemberNotFound):
            msg = await ctx.send(
                "No such members. Try again, but try with someone in the " +
                f"server, <@{ctx.author.id}>.")
            await asyncio.sleep(0.5)
            await msg.edit(
                content=msg.content +
                " Oh! And `everyone` or `roles` is not a valid option.")
        elif isinstance(error, commands.TooManyArguments):
            msg = await ctx.send(
                f"<@{ctx.author.id}>, there's too many arguments. " +
                "Don't be lazy and read the `help` command!")
            await asyncio.sleep(0.5)
            await ctx.send_help(ctx.command)
            await asyncio.sleep(0.5)
            await msg.edit(content=msg.content + " Read that!")
        elif isinstance(error, commands.UserInputError):
            msg = await ctx.send(
                f"<@{ctx.author.id}>, are you okay? I don't think " +
                "you're using the command correctly.")
            await asyncio.sleep(0.5)
            await ctx.send_help(ctx.command)
            await asyncio.sleep(0.5)
            await msg.edit(content=msg.content + " Will that help?")
        elif isinstance(error, commands.MaxConcurrencyReached):
            await ctx.send(f"Yo, <@{ctx.author.id}>! CHILL?")
        elif isinstance(error, commands.NotOwner):
            await ctx.send("That command is only for my awesome creator.")
        elif isinstance(error, commands.PrivateMessageOnly):
            await ctx.send(
                "That command can only be used within a Private Message. " +
                "Kindly, send me a Private Message and initiate the " +
                "command again. I won't bite.")
        elif isinstance(error, commands.NoPrivateMessage):
            await ctx.send(
                "That command can only be used within a Discord Server.")
        elif self.bot.is_ws_ratelimited():
            await ctx.send(
                "We are being rate limited. Nothing can be helped here. " +
                "Please wait and try again.")
        elif not commands.bot_has_permissions():
            await ctx.send("Please check that I have the permission, " +
                           "`View Channels`, `Send Messages`, `Embed Links` " +
                           "`Add Reactions`, `Read Message History`, " +
                           "and `Manage Messages`.")
        else:
            await self.notifyOwner(ctx, error)

            official_server = False
            if ctx.guild.id == int(os.getenv("GUILD_ID")):
                official_server = True

            if not official_server:
                await ctx.send("I encountered a bug. Don't worry. " +
                               "I've logged the bug. However, " +
                               "if it still happens, you might " +
                               "want to join the support server " +
                               "through the `server` command " +
                               "for a more thorough assistance.")
            else:
                await ctx.send("I encountered a bug. Don't worry. " +
                               "I've logged the bug.")
Esempio n. 15
0
top.gg-token: My top.gg API token
discord.boats-token: My discord.boats API token
discordbotlist.com-token: My discordbotlist.com API token
"""
scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]
creds = ServiceAccountCredentials.from_json_keyfile_dict(
    json.loads(os.environ['GOOGLE_CREDENTIALS']), scope)
gs_client = gspread.authorize(creds)
dictionary = PyDictionary()

client = commands.Bot(command_prefix="$")
client.remove_command("help")
client.add_check(commands.bot_has_permissions(send_messages=True).predicate)

rw = RandomWords()

authors = []
index = 0


@tasks.loop(seconds=15)
async def change_status():
    global index
    statuses = [
        'https://aadits-hangman.herokuapp.com',
        f'{len(client.guilds)} servers', '$help || $start', 'Youtube',
        'People winning hangman', 'Audit dev me', 'https://discord.gg/CRGE5nF',
        'https://dsc.gg/hangman',
Esempio n. 16
0
    def __init__(self, **kwargs):
        self.disabled_message = DEFAULT_DISABLED_MESSAGE
        self.pipe = kwargs.pop("pipe")
        self.cluster_name = kwargs.pop("cluster_name")
        self.cluster_idx = kwargs.pop("cluster_idx")
        self.env = kwargs.pop("env")
        self.embed_color = 0xF44336
        self.battles = None
        self.dbl_token = kwargs.pop("dbl_token")
        self.database_uri = kwargs.pop("database_uri")
        self.database_name = kwargs.pop("database_name")
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        super().__init__(**kwargs, loop=loop, command_prefix=determine_prefix)
        self.mongo = helpers.mongo.Database(self, self.database_uri, self.database_name)

        self._last_result = None
        self.waiting = False
        self.enabled = False
        self.sprites = None

        self.log = logging.getLogger(f"Cluster#{self.cluster_name}")
        self.log.setLevel(logging.DEBUG)
        handler = logging.FileHandler(
            filename=f"logs/commands-{self.cluster_name}.log",
            encoding="utf-8",
            mode="a",
        )
        handler.setFormatter(
            logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s")
        )
        self.log.handlers = [handler]

        discord_logger = logging.getLogger("discord")
        discord_logger.setLevel(logging.INFO)
        discord_handler = logging.FileHandler(
            filename=f"logs/discord-{self.cluster_name}.log", encoding="utf-8", mode="a"
        )
        discord_handler.setFormatter(
            logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s")
        )
        discord_logger.addHandler(discord_handler)

        self.log.info(
            f'[Cluster#{self.cluster_name}] {kwargs["shard_ids"]}, {kwargs["shard_count"]}'
        )

        # Load extensions

        self.load_extension("jishaku")
        for i in dir(cogs):
            if not i.startswith("_"):
                self.load_extension(f"cogs.{i}")

        self.add_check(helpers.checks.enabled(self))
        self.add_check(
            commands.bot_has_permissions(
                read_messages=True,
                send_messages=True,
                embed_links=True,
                attach_files=True,
                read_message_history=True,
                add_reactions=True,
                external_emojis=True,
            ).predicate
        )

        # Run bot

        self.ipc = Server(
            self, "localhost", 8765 + self.cluster_idx, kwargs["secret_key"]
        )

        @self.ipc.route()
        async def stop(data):
            try:
                await self.close()
                return {"success": True}
            except Exception as err:
                return {"success": False, "error": err}

        @self.ipc.route()
        async def stats(data):
            return {
                "success": True,
                "guild_count": len(self.guilds),
                "shard_count": len(self.shards),
                "user_count": sum(x.member_count for x in self.guilds),
                "latency": sum(x[1] for x in self.latencies),
            }

        @self.ipc.route()
        async def reload(data):
            try:
                await self.reload_modules()
                return {"success": True}
            except Exception as err:
                return {"success": False, "error": err}

        @self.ipc.route()
        async def disable(data):
            self.enabled = False
            if hasattr(data, "message") and data.message is not None:
                self.disabled_message = data.message
            else:
                self.disabled_message = DEFAULT_DISABLED_MESSAGE
            return {"success": True}

        @self.ipc.route()
        async def enable(data):
            self.enabled = True
            self.disabled_message = DEFAULT_DISABLED_MESSAGE
            return {"success": True}

        @self.ipc.route()
        async def move_request(data):
            self.dispatch(
                "move_request",
                data.cluster_idx,
                data.user_id,
                data.species_id,
                data.actions,
            )
            return {"success": True}

        @self.ipc.route()
        async def move_decide(data):
            self.dispatch("move_decide", data.user_id, data.action)
            return {"success": True}

        @self.ipc.route()
        async def send_dm(data):
            user = await self.fetch_user(data.user)
            await user.send(data.message)
            return {"success": True}

        @self.ipc.route()
        async def eval(data):
            data = await self.exec(data.code)
            return {"success": True, "result": data}

        self.ipc.start()

        self.ipc_client = Client(secret_key=kwargs["secret_key"])

        self.loop.create_task(self.do_startup_tasks())
        self.run(kwargs["token"])
Esempio n. 17
0
def has_administrator_permission(ctx: commands.Context) -> bool:
    is_guild(ctx)
    commands.has_permissions(administrator=True)(ctx)
    commands.bot_has_permissions(administrator=True)(ctx)
    return True