Esempio n. 1
0
    async def unsubscribe(self, ctx, *, role=None):
        """Désabonnez-vous ou un rôle dans un ticket."""
        thread = ctx.thread

        if not role:
            mention = ctx.author.mention
        elif role.lower() in ('here', 'everyone'):
            mention = '@' + role
        else:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, role)
            mention = role.mention

        if str(thread.id) not in self.bot.config['subscriptions']:
            self.bot.config['subscriptions'][str(thread.id)] = []

        mentions = self.bot.config['subscriptions'][str(thread.id)]

        if mention not in mentions:
            embed = discord.Embed(color=discord.Color.red(),
                                  description=f"{mention} n'est pas "
                                  'abonné à ce ticket.')
        else:
            mentions.remove(mention)
            await self.bot.config.update()
            embed = discord.Embed(color=self.bot.main_color,
                                  description=f'{mention} est maintenant désabonné '
                                  'à ce ticket.')
        return await ctx.send(embed=embed)
Esempio n. 2
0
    async def unsubscribe(self, ctx, *, role=None):
        """Unsubscribes a given role or yourself from a thread."""
        thread = await self.bot.threads.find(channel=ctx.channel)
        if thread is None:
            return

        if not role:
            mention = ctx.author.mention
        elif role.lower() in ('here', 'everyone'):
            mention = '@' + role
        else:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, role)
            mention = role.mention

        if str(thread.id) not in self.bot.config['subscriptions']:
            self.bot.config['subscriptions'][str(thread.id)] = []

        mentions = self.bot.config['subscriptions'][str(thread.id)]

        if mention not in mentions:
            return await ctx.send(embed=discord.Embed(
                color=discord.Color.red(),
                description=
                f'{mention} is not already subscribed to this thread.'))

        mentions.remove(mention)
        await self.bot.config.update()

        em = discord.Embed(color=discord.Color.green())
        em.description = f'{mention} is now unsubscribed to this thread.'
        await ctx.send(embed=em)
Esempio n. 3
0
    async def notify(self, ctx, *, role=None):
        """
        Avertissez un rôle ou vous-même au prochain ticket ouvert.

        Vous serez notifié une fois dès qu'un ticket est ouvert.
        """
        thread = ctx.thread

        if not role:
            mention = ctx.author.mention
        elif role.lower() in ('here', 'everyone'):
            mention = '@' + role
        else:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, role)
            mention = role.mention

        if str(thread.id) not in self.bot.config['notification_squad']:
            self.bot.config['notification_squad'][str(thread.id)] = []

        mentions = self.bot.config['notification_squad'][str(thread.id)]

        if mention in mentions:
            embed = discord.Embed(color=discord.Color.red(),
                                  description=f'{mention} va déjà '
                                  'être mentionné.')
        else:
            mentions.append(mention)
            await self.bot.config.update()
            embed = discord.Embed(color=self.bot.main_color,
                                  description=f'{mention} sera mentionné dans '
                                  'le prochain ticket.')
        return await ctx.send(embed=embed)
Esempio n. 4
0
 async def roleinfo(self, ctx, role=None):
     """shows information about the server roles"""
     role_converter = commands.RoleConverter()
     server = ctx.message.guild
     roles = server.roles
     embed = Embed()
     embed.set_thumbnail(url=server.icon_url)
     if not role:
         for role in roles:
             if role.name == "@everyone":
                 continue
             member_with_role = [
                 member for member in server.members if role in member.roles
             ]
             embed.add_field(name=role.name,
                             value="{} Member(s)".format(
                                 len(member_with_role)))
     else:
         role = await role_converter.convert(ctx=ctx, argument=role)
         member_with_role = [
             member for member in server.members if role in member.roles
         ]
         embed.add_field(name=role.name,
                         value="{} Member(s)".format(len(member_with_role)))
     await ctx.send(embed=embed)
Esempio n. 5
0
 async def _try_get_role(ctx, role_str):
     converter = commands.RoleConverter()
     try:
         role = await converter.convert(ctx, role_str)
     except:
         role = None
     return role
Esempio n. 6
0
 def __init__(self, bot):
     self.bot = bot
     self.sdb = func_database.ServerDatabase()
     self.msg = func_msg_gen.MessageGenerator()
     self.prefix = func_prefix.Prefix()
     self.role_converter = commands.RoleConverter()
     self.channel_converter = commands.TextChannelConverter()
Esempio n. 7
0
    async def subscribe(self, ctx, *, role=None):
        """Notify yourself or a given role for every thread message recieved.
        You will be pinged for every thread message recieved until you unsubscribe.
        """
        thread = await self.bot.threads.find(channel=ctx.channel)
        if thread is None:
            return

        if not role:
            mention = ctx.author.mention
        elif role.lower() in ('here', 'everyone'):
            mention = '@' + role
        else:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, role)
            mention = role.mention

        if str(thread.id) not in self.bot.config['subscriptions']:
            self.bot.config['subscriptions'][str(thread.id)] = []

        mentions = self.bot.config['subscriptions'][str(thread.id)]

        if mention in mentions:
            return await ctx.send(embed=discord.Embed(
                color=discord.Color.red(),
                description=f'{mention} is already subscribed to this thread.')
                                  )

        mentions.append(mention)
        await self.bot.config.update()

        em = discord.Embed(color=discord.Color.green())
        em.description = f'{mention} is now subscribed to be notified of all messages received.'
        await ctx.send(embed=em)
Esempio n. 8
0
    async def notify(self, ctx, *, role=None):
        """Notify a given role or yourself to the next thread message received.
        
        Once a thread message is received you will be pinged once only.
        """
        thread = await self.bot.threads.find(channel=ctx.channel)
        if thread is None:
            return

        if not role:
            mention = ctx.author.mention
        elif role.lower() in ('here', 'everyone'):
            mention = '@' + role
        else:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, role)
            mention = role.mention

        if str(thread.id) not in self.bot.config['notification_squad']:
            self.bot.config['notification_squad'][str(thread.id)] = []

        mentions = self.bot.config['notification_squad'][str(thread.id)]

        if mention in mentions:
            return await ctx.send(embed=discord.Embed(
                color=discord.Color.red(),
                description=f'{mention} is already going to be mentioned.'))

        mentions.append(mention)
        await self.bot.config.update()

        em = discord.Embed(color=discord.Color.green())
        em.description = f'{mention} will be mentioned on the next message received.'
        await ctx.send(embed=em)
Esempio n. 9
0
 async def make_rank2role(self, ctx):
     converter = commands.RoleConverter()
     rank2role = {}
     for rank in cf.RATED_RANKS:
         rank2role[rank.title.lower()] = await converter.convert(
             ctx, rank.title)
     return rank2role
Esempio n. 10
0
    async def unsubscribe(self, ctx, *, role=None):
        """Unsubscribe yourself or a given role from a thread."""
        thread = ctx.thread

        if not role:
            mention = ctx.author.mention
        elif role.lower() in ('here', 'everyone'):
            mention = '@' + role
        else:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, role)
            mention = role.mention

        if str(thread.id) not in self.bot.config['subscriptions']:
            self.bot.config['subscriptions'][str(thread.id)] = []

        mentions = self.bot.config['subscriptions'][str(thread.id)]

        if mention not in mentions:
            embed = discord.Embed(color=discord.Color.red(),
                                  description=f'{mention} is not already '
                                  'subscribed to this thread.')
        else:
            mentions.remove(mention)
            await self.bot.config.update()
            embed = discord.Embed(color=self.bot.main_color,
                                  description=f'{mention} is now unsubscribed '
                                  'to this thread.')
        return await ctx.send(embed=embed)
Esempio n. 11
0
    def __init__(self, client):
        self.client = client
        self.tournament = Tournament()
        self.queue = Tournament.get_tournaments(client)
        self.attr = ['name', 'time', 'prize', 'host', 'roles', 'note']
        self.channels = Channel(client)
        self.roles = Role(client)
        self.checklist = None
        self.modifiers = [{
            'name': 'RequiredRole',
            'value': commands.RoleConverter()
        }, {
            'name': 'MaxParticipants',
            'value': int
        }, 'SpectatorsAllowed', {
            'name': 'PrizeType',
            'value': ModifierUtils.convert_to_prize_type
        }, {
            'name': 'AutoGiveCoins',
            'value': int
        }, {
            'name': 'AssistingTO',
            'value': commands.MemberConverter()
        }]

        asyncio.create_task(self.update_reminders())

        print(self.__class__.__name__ + " cog initialized!")
Esempio n. 12
0
    async def buy(self, ctx, item_name):
        db = self.db
        
        found_items = []
        items = db.items.find({"guild_id": ctx.guild.id})
        if items[0] is None: return

        for item in items:
            if item_name in item['name']:
                found_items.append(item)

        if len(found_items) == 0:
            await ctx.send("Couldn't find an item with that name sadly")
        else:
            item = found_items[0]

            for reply in enumerate([item['reply'], item['dm_msg']]):
                response = await self.parse_msg(reply[1])
                if not response['content']:
                    response['content'] = '👍'
                if reply[0] == 0:
                    await ctx.send(**response)
                else:
                    await ctx.author.dm_channel.send(**response)
            
            converter = commands.RoleConverter().convert
            roles = [str(item['given_role']), str(item['removed_role'])]
            if roles[0]:
                await ctx.author.add_roles(await converter(ctx, roles[0]))
            if roles[1]:
                await ctx.author.remove_roles(await converter(ctx, roles[1]))

            db.members.update_one({'guild_id': ctx.guild.id, 'user_id': ctx.author.id}, {'$inc': {'points': -item['price']}})
            db.items.update_one([])
Esempio n. 13
0
 async def _grant_to_role(self, ctx, badge_id: int = 0, *, role):
     """**Usage**: `!grant_to_role/givetr/gbtr <badge_id> <rolename>`
     Gives the provided badge to all users assigned to the provided role."""
     converter = commands.RoleConverter()
     try:
         role = await converter.convert(ctx, role)
     except:
         role = None
     if badge_id == 0 or role is None:
         await ctx.message.add_reaction(self.bot.failed_react)
         return await ctx.send("Must provide a badge id and Role name.",
                               delete_after=10)
     badge_to_give = BadgeTable.get(BadgeTable.id == badge_id)
     if badge_to_give:
         if badge_to_give.guild.snowflake != ctx.guild.id:
             await ctx.message.add_reaction(self.bot.failed_react)
             return await ctx.channel.send(embed=discord.Embed(
                 colour=discord.Colour.red(),
                 description=
                 f"No badge with id {badge_id} found on this server."))
         try:
             trainer_ids = []
             errored = []
             __, __ = GuildTable.get_or_create(snowflake=ctx.guild.id)
             for trainer in role.members:
                 try:
                     trainer_obj, __ = TrainerTable.get_or_create(
                         snowflake=trainer.id, guild=ctx.guild.id)
                     trainer_ids.append(
                         (badge_to_give.id, trainer_obj.snowflake))
                 except:
                     errored.append(trainer.id)
             with KyogreDB._db.atomic():
                 count = BadgeAssignmentTable.insert_many(trainer_ids,
                                                          fields=[BadgeAssignmentTable.badge_id,
                                                                  BadgeAssignmentTable.trainer])\
                         .on_conflict_ignore().execute()
             message = f"Could not assign the badge to: {', '.join(errored)}"
         except Exception as e:
             self.bot.logger.error(e)
             await ctx.message.add_reaction(self.bot.failed_react)
             return await ctx.channel.send(embed=discord.Embed(
                 colour=discord.Colour.red(),
                 description="Completely failed"),
                                           delete_after=12)
         if len(errored) > 0:
             colour = discord.Colour.from_rgb(255, 255, 0)
             await ctx.message.add_reaction(self.bot.failed_react)
             await ctx.message.add_reaction(self.bot.success_react)
             return await ctx.channel.send(embed=discord.Embed(
                 colour=colour, description=message),
                                           delete_after=12)
         await ctx.message.add_reaction(self.bot.success_react)
         await self._update_single_internal(ctx, badge_id)
         return await ctx.channel.send(embed=discord.Embed(
             colour=discord.Colour.green(),
             description=f"Successfully granted badge to {count} trainers.")
                                       )
Esempio n. 14
0
async def _dm_generic(ctx, *, online_only):
    '''
    See ``dm``.
    '''

    if ctx.channel.id not in BOT_DM_CHANNELS:
        raise ChannelPermissionMissing()

    # split argument string into roles and message
    args = ctx.message.content.partition(ctx.invoked_with + " ")[2]
    recipient_part, _, message = args.partition("--")
    recipient_part = recipient_part.strip()
    message = message.lstrip()

    if (len(message) == 0):
        raise commands.BadArgument()

    # extract roles and Members and collect recipients
    recipients = set()
    for recipient in recipient_part.split(" "):
        if recipient == "":
            continue

        try:
            conv = commands.RoleConverter()
            recipient = await conv.convert(ctx, recipient)
            recipients |= set(recipient.members)
        except commands.BadArgument:
            #This gets triggered when there is no Role for the string 'recipients'
            member_converter = commands.MemberConverter()
            recipient = await member_converter.convert(ctx, recipient)
            recipients.add(recipient)

    sent = 0
    offline = 0
    blocked = 0

    for member in recipients:
        if online_only and member.status == discord.Status.offline:
            offline += 1
            continue
        try:
            await member.send(message)
            sent += 1
        except discord.errors.Forbidden:
            blocked += 1
            await ctx.send(f"{member.mention} did not receive the message "
                           f"(bot was blocked).")
    message = (f"Message sending complete.\n"
               f"> Sent to a total of {sent} people\n")
    if offline > 0 or blocked > 0:
        message += (f"> {offline+blocked} people did not receive a message\n"
                    f"> - {offline} offline\n"
                    f"> - {blocked} blocked")
    await ctx.send(message)
Esempio n. 15
0
 async def predicate(ctx):
     if "dj" in CONFIG:
         author = ctx.author
         converter = commands.RoleConverter()
         dj_role = await converter.convert(ctx, CONFIG["dj"])
         if dj_role in author.roles:
             return True
         else:
             return False
     else:
         return True
Esempio n. 16
0
    async def convert(self, ctx, argument):
        try:
            role_converter = commands.RoleConverter()
            role = await role_converter.convert(ctx, argument)
        except commands.RoleNotFound:
            role = discord.utils.find(
                lambda r: r.name.lower().startswith(argument), ctx.guild.roles)

        if role is None:
            raise commands.RoleNotFound(f"Role \"{argument}\" not found.")

        return role
Esempio n. 17
0
 def __init__(self, bot):
     self.bot = bot
     self.blue = discord.Color.blue()
     self.accepted_values = {
         'prefix': 'Anything',
         'public_log': 'Any text channel',
         'private_log': 'Any text channel',
         'mod_role': 'Any role',
         'muted_role': 'Any role'
     }  # text used for an embed
     self.tc_conv = commands.TextChannelConverter()
     self.role_conv = commands.RoleConverter()
Esempio n. 18
0
    async def toggle_module(self, ctx: commands.Context, *, str_modules: str):
        """Command Handler for the `module` command.

        Allows members to assign/remove so called mod roles to/from themselves. This way users can toggle text channels
        about specific courses to be visible or not to them. When the operation is finished, SAM will send an overview
        about the changes he did per direct message to the user who invoked the command.
        Keep in mind that this only works if the desired role has been whitelisted as a module role by the bot owner.

        If the command is invoked outside of the configured role channel, the bot will post a short info that this
        command should only be invoked there and delete this message shortly after.

        Args:
            ctx (discord.ext.commands.Context): The context in which the command was called.
            str_modules (str): A string containing abbreviations of all the modules a user would like to toggle.
        """
        if ctx.channel.id != self.ch_role.id:
            if not self._db_connector.is_botonly(ctx.channel.id):
                await ctx.message.delete()

            await ctx.channel.send(content=f"Dieser Befehl wird nur in {self.ch_role.mention} unterstützt. Bitte "
                                   f"versuche es dort noch einmal.", delete_after=constants.TIMEOUT_INFORMATION)
            return

        converter = commands.RoleConverter()
        modules = list(set(str_modules.split()))  # Removes duplicates

        modules_error = []
        modules_added = []
        modules_removed = []

        for module in modules:
            module_upper = module.upper()
            try:
                role = await converter.convert(ctx, module_upper)

                if not self._db_connector.check_module_role(role.id):
                    raise commands.BadArgument("The specified role hasn't been whitelisted as a module role.")

                if role in ctx.author.roles:
                    await ctx.author.remove_roles(role, atomic=True, reason="Selbstständig entfernt via SAM.")
                    modules_removed.append(module_upper)
                else:
                    await ctx.author.add_roles(role, atomic=True, reason="Selbstständig zugewiesen via SAM.")
                    modules_added.append(module_upper)
            except commands.BadArgument:
                modules_error.append(module_upper)

        if len(modules_error) < len(modules):
            log.info("Module roles of the member %s have been changed.", ctx.author)

        embed = _create_embed_module_roles(modules_added, modules_removed, modules_error)
        await ctx.author.send(embed=embed)
Esempio n. 19
0
    def __init__(self, bot):
        self.bot = bot

        self.future_contests = None
        self.active_contests = None
        self.finished_contests = None
        self.start_time_map = defaultdict(list)
        self.task_map = defaultdict(list)

        self.member_converter = commands.MemberConverter()
        self.role_converter = commands.RoleConverter()

        self.logger = logging.getLogger(self.__class__.__name__)
Esempio n. 20
0
 async def convert(cls, ctx: commands.Context,
                   argument: str) -> discord.Role:
     converter = commands.RoleConverter()
     try:
         role = await converter.convert(ctx, argument)
     except commands.BadArgument:
         raise commands.BadArgument(f'Role "{argument}" not found.')
     if role.managed:
         raise commands.BadArgument(
             f"`{role}` is an integrated role and cannot be assigned.")
     allowed = my_role_hierarchy(ctx.guild, role)
     if not allowed:
         raise commands.BadArgument(
             f"I am not higher than `{role}` in hierarchy.")
     return role
 async def role_addcategory(self, ctx, category: str, *roles):
     # I'm going full mONKE!!!!
     converter = commands.RoleConverter().convert
     category_data = self.data[ctx.guild.id][category]
     for role_text in roles:
         try:
             role = await converter(ctx, role_text)
         except commands.RoleNotFound:
             await ctx.send(
                 response_bank.role_addcategory_error.format(role=role))
             continue
         category_data.add(role.id)
     self.data_save()
     await ctx.send(
         response_bank.role_addcategory_confirm.format(category=category))
Esempio n. 22
0
    def __init__(self):
        super().__init__(command_prefix='/')
        self.session = aiohttp.ClientSession(loop=self.loop)
        self.loop.create_task(self.user_input())
        self.channel = None
        self.is_bot = None
        self.paused = False
        self.role_converter = commands.RoleConverter()
        self.member_converter = commands.MemberConverter()
        self.remove_command('help')

        for i in [i.replace('.py', '') for i in os.listdir('commands') if i.endswith('.py')]:
            self.load_extension('commands.' + i)

        cprint('Logging in...', 'green')
        self.run()
Esempio n. 23
0
    def __init__(self, bot):
        self.bot = bot
        self.future_contests = None
        self.contest_cache = None
        self.active_contests = None
        self.finished_contests = None
        self.start_time_map = defaultdict(list)
        self.task_map = defaultdict(list)
        # Maps guild_id to `GuildSettings`
        self.guild_map = defaultdict(get_default_guild_settings)
        self.last_guild_backup_time = -1

        self.member_converter = commands.MemberConverter()
        self.role_converter = commands.RoleConverter()

        self.logger = logging.getLogger(self.__class__.__name__)
Esempio n. 24
0
    async def _edit_item(self, ctx: commands.Context, option: str, name: str,
                         new_vlaue):
        item = await models.Item.query.where(
            (models.Item.guild_id == ctx.guild.id)
            & (models.Item.name == name)).gino.first()
        if (item):
            role_converter = commands.RoleConverter()

            if (option == "name"):
                await item.update(name=str(new_vlaue)).apply()
                return await ctx.reply("Updated name")
            elif (option == "price"):
                await item.update(price=abs(int(new_vlaue))).apply()
                return await ctx.reply("Updated price")
            elif (option == "description"):
                await item.update(description=str(new_vlaue)).apply()
                return await ctx.reply("Updated description")
            elif (option == "stock"):
                await item.update(stock=int(new_vlaue)).apply()
                return await ctx.reply("Updated stock")
            elif (option == "role_required"):
                role = await role_converter.convert(ctx, new_vlaue)
                await item.update(role_required=role.id).apply()
                return await ctx.reply("Updated role required")
            elif (option == "role_given"):
                role = await role_converter.convert(ctx, new_vlaue)
                await item.update(role_given=role.id).apply()
                return await ctx.reply("Updated role given")
            elif (option == "role_removed"):
                role = await role_converter.convert(ctx, new_vlaue)
                await item.update(role_removed=role.id).apply()
                return await ctx.reply("Updated role removed")
            elif (option == "required_balance"):
                await item.update(required_balance=abs(int(new_vlaue))).apply()
                return await ctx.reply("Updated required balance")
            elif (option == "reply"):
                await item.update(reply=str(new_vlaue)).apply()
                return await ctx.reply("Updated reply")
            else:
                return await ctx.reply("Invalid option!")
        else:
            return await ctx.reply("Item not found! Check the name spelling.")
Esempio n. 25
0
    async def convert(self, ctx, argument):
        if argument.lower().endswith("everyone"):
            return "@everyone"
        if argument.lower().endswith("here"):
            return "@here"

        try:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, argument)
            return role.mention
        except (commands.NoPrivateMessage, BadArgument):
            pass

        try:
            converter = commands.MemberConverter()
            user = await converter.convert(ctx, argument)
            return user.mention
        except BadArgument:
            pass

        raise BadArgument(f'mention for "{argument}" could not be created')
Esempio n. 26
0
    async def yes_no(self, ctx, question:str, *, question_number:int = sys.maxsize):
        """Adds a yes/no question to the survey.

        The question should be surrounded in quotation marks.
        Question number is optional. If not passed the question will be added
        to the end of the survey.
        """
        author = ctx.message.author
        channel = ctx.message.channel

        survey = self.egl_db.get('survey', {})

        await self.bot.say("What is the role that this question should grant? Type 'cancel' to quit.")

        for i in range(5):
            def check(m):
                return m.author.id == author.id and \
                    m.channel.id == channel.id

            reply = await self.bot.wait_for_message(check=check, timeout=300.0)
            if reply is None:
                return await self.bot.send_message(channel, 'You took too long. Goodbye.')
            if reply.content == 'cancel':
                return await self.bot.send_message(channel, 'Cancelling. Goodbye.')

            try:
                # Attempt to get the role for the response
                role = commands.RoleConverter(ctx, reply.content).convert()
                # Set up the question object
                q = {}
                q['text'] = question
                q['type'] = 'yes_no'
                q['role_granted'] = role.id
                await self.add_question_to_survey(q, survey, question_number)
                return await self.bot.send_message(channel, "Question added to the survey.")
            except BadArgument:
                # Role conversion failed
                await self.bot.send_message(channel, "Role not found, please try again. Tries remaining: {}".format(5-i))

        return await self.bot.send_message(channel, "Failed too many times. Please try again.")
Esempio n. 27
0
 async def addrero(self, ctx: aoi.AoiContext, message: discord.Message, *,
                   args: str):  # noqa c901
     split = ctx.group_list(args.split(), 2)
     role_converter = commands.RoleConverter()
     for i in split:
         print(i)
         try:
             emoji: discord.PartialEmoji = await partial_emoji_convert(
                 ctx, i[0])
             role: discord.Role = await role_converter.convert(ctx, i[1])
         except commands.PartialEmojiConversionFailure:
             return await ctx.send_error(f"Emoji {i[0]} invalid")
         except commands.RoleNotFound:
             return await ctx.send_error(f"Role {i[1]} invalid")
         if role >= ctx.author.top_role and ctx.guild.owner_id != ctx.author.id:
             raise aoi.RoleHierarchyError(
                 f"Role {role} must be lower than your highest")
         if role >= ctx.me.top_role:
             raise aoi.RoleHierarchyError(
                 f"Role {role} must be lower than mine")
         try:
             await message.add_reaction(emoji)
         except discord.Forbidden:
             return await ctx.send_error("I can't react to that message!")
         except discord.HTTPException:
             return await ctx.send_error(f"Emoji {i[0]} invalid")
         if message.id not in self._roles:
             self._roles[message.id] = {}
         if emoji.name in self._roles[message.id] or str(
                 emoji.id) in self._roles[message.id]:
             return await ctx.send_error("That emoji is already being used")
         self._roles[message.id][str(emoji.id) if emoji.id else emoji.
                                 name] = _ReactionRoleData(role)
         await self._db.conn.execute(
             "insert into rero values (?,?,?,?,?,0,0)",
             (ctx.guild.id, message.channel.id, message.id,
              str(emoji.id) if emoji.id else emoji.name, role.id))
         await self._db.conn.commit()
         await ctx.send_ok("Added!")
Esempio n. 28
0
async def dm(ctx):
    if ctx.channel.id not in BOT_DM_CHANNELS:
        raise ChannelPermissionMissing()

    # split argument string into roles and message
    args = ctx.message.content.partition("dm ")[2]
    recipient_part, _, message = args.partition("--")
    recipient_part = recipient_part.strip()
    message = message.lstrip()

    if (len(message) == 0):
        raise commands.BadArgument()

    # extract roles and Members and collect recipients
    recipients = set()
    for recipient in recipient_part.split(" "):
        if recipient == "":
            continue

        try:
            conv = commands.RoleConverter()
            recipient = await conv.convert(ctx, recipient)
            recipients |= set(recipient.members)
        except commands.BadArgument:
            #This gets triggered when there is no Role for the string 'recipients'
            member_converter = commands.MemberConverter()
            recipient = await member_converter.convert(ctx, recipient)
            recipients.add(recipient)

    sent_members = []

    for member in recipients:
        try:
            await member.send(message)
            sent_members.append(member)
        except discord.errors.Forbidden:
            await ctx.send(member.mention + " did not receive the message.")
    await ctx.send("Messages sent successfully. Sent to a total of %i people." \
                   % len(sent_members))
Esempio n. 29
0
async def get_role_response(client, ctx, msg: discord.Message, member: discord.Member, embed: discord.Embed, channel: discord.TextChannel) -> Union[discord.Role, None]:
	""" Gets a role response from the user.
	:param ctx:
	:param msg:
	:param member:
	:param embed:
	:param channel: """

	while True:
		try:
			m = await client.wait_for(
				'message', timeout=60, check=lambda m: m.author.id == member.id and m.channel.id == channel.id
			)
		except asyncio.TimeoutError:
			embed.description = "**Timeout!**"
			embed.color = discord.Color.red()
			await msg.edit(embed=embed)
			return None

		else:
			try:
				content = m.content.strip().title()
				converter = commands.RoleConverter()
				role = await converter.convert(ctx, content)
			except discord.ext.commands.errors.RoleNotFound:
				await channel.send(f'**Invalid role, {member.mention}!**', delete_after=3)
				await m.delete()
				continue
			except Exception as e:
				print('===')
				print(e)
				print('===')
				continue
			else:
				await m.delete()
				return role
Esempio n. 30
0
    async def subscribe(self, ctx, *, role=None):
        """
        Être notifié pour chaque message reçu dans ce ticket.

        Vous recevrez un ping pour chaque message reçu 
        dans ce ticket jusqu'à votre désinscription (unsubscribe).
        """
        thread = ctx.thread

        if not role:
            mention = ctx.author.mention
        elif role.lower() in ('here', 'everyone'):
            mention = '@' + role
        else:
            converter = commands.RoleConverter()
            role = await converter.convert(ctx, role)
            mention = role.mention

        if str(thread.id) not in self.bot.config['subscriptions']:
            self.bot.config['subscriptions'][str(thread.id)] = []

        mentions = self.bot.config['subscriptions'][str(thread.id)]

        if mention in mentions:
            embed = discord.Embed(color=discord.Color.red(),
                                  description=f'{mention} est déjà '
                                  'abonné à ce ticket.')
        else:
            mentions.append(mention)
            await self.bot.config.update()
            embed = discord.Embed(
                color=self.bot.main_color,
                description=f'{mention} sera maintenant '
                'notifié pour tous les messages reçus dans ce ticket.'
            )
        return await ctx.send(embed=embed)