Пример #1
0
    async def _aprisionar(self, ctx: commands.Context):
        original_roles = [x for x in ctx.author.roles if x.name != '@everyone']
        try:
            for role in original_roles:
                await ctx.author.remove_roles(role)
        except Exception as e:
            if 'missing permissions' in str(e).lower():
                ctx.send(u"Deu sorte, malandro. Não tenho permissão pra te mandar pro xilindró.")
            return

        await ctx.send("Por causa disso, você vai virar prisioneiro por dois minutos.")
        await ctx.author.add_roles(ctx.guild.get_role(778774271869583480))
        await sleep(120)
        try:
            await ctx.author.remove_roles(ctx.guild.get_role(778774271869583480))
            for role in original_roles:
                await ctx.author.add_roles(role)
            await ctx.send(f"{ctx.author.mention}: Você não é mais prisioneiro.")
        except Exception as e:
            if 'unknown member' in str(e).lower():
                # needed to avoid weird indentation shenanigans
                escaped = f"Bem, parece que {ctx.author.name} fugiu da prisão...\n"
                escaped += f"Ele(a) tinha essas roles: `{[r.name for r in original_roles]}`\n"
                escaped += "Se ele(a) for visto(a) novamente, entreguem essas roles de volta porque eu tô me lixando."
                await ctx.send(escaped)
Пример #2
0
  async def ss13_status(self, ctx: commands.Context, ip_port:str):
    ipp = ip_port.split(":")
    dat = self.__standardnizeData(Topic(ipp[0], ipp[1], "status"))

    ourembed: discord.Embed = discord.Embed()
    # We do this first!
    in_the_field = [
      {"name": "Map Name", "value": dat["map_name"]},
      {"name": "Gamemode", "value": dat["mode"]},
      {"name": "Round ID", "value": dat["round_id"]},
      {"name": "Players", "value": dat["players"], "inline": True},
      {"name": "Player Cap", "value": dat["popcap"], "inline": True},
      # DO NOT BLAME ME, SOMEONE STOLE PYTHON'S SWITCH OP
      {"name": "Game State", "value": {0:"Initializing game",1:"Waiting on Lobby",2:"Starting",3:"Started",4:"Round ended"}.get(dat["gamestate"],"Started?")},
      {"name": "Round Duration", "value": dat["round_duration"]+" second(s)"},
      {"name": "Revision", "value": dat["revision"]}
    ]
    ourembed.from_dict({
      "title": "Server Status of "+ip_port,
      "type": "rich",
      "description": "GenericDesc",
      "url": "byond://"+ip_port,
      "fields": in_the_field
    })
    ctx.send(None, embed=ourembed)
    return
Пример #3
0
 async def fantasy_roster(self,
                          ctx: commands.Context,
                          league: str,
                          week: int = None):
     """
     Get your team roster for a specific week
     Defaults to current week
     """
     team = await get_user_team(league, None, ctx)
     if team:
         roster = team.roster(week=week)
         embed = discord.Embed(
             title="Roster for " +
             ("current week" if week is None else "Week " + str(week)))
         count = 1
         for p in roster:
             if count < 24:
                 embed.add_field(
                     name=p['name'] + " - " + p['selected_position'],
                     value=(p['status'] if p['status'] else '\u200b'))
                 count += 1
             else:
                 ctx.send(embed=embed)
                 embed = discord.Embed(
                     title="Roster for " +
                     ("current week" if week is None else "Week " +
                      str(week)) + " (Page " + str(count / 24) + ")")
         await ctx.send(embed=embed)
Пример #4
0
    async def degenerates(self, ctx: commands.Context):
        """
        Returns a list of the top anime posters
        """
        userPosts = {}
        for instance in self.postsDB.query(posts).order_by(posts.name):
            userPosts[instance.name] = instance.animePosts

        userPosts = sorted(userPosts.items(), key=lambda x: x[1], reverse=True)

        totalAnime = 0
        output = ""
        embed = discordEmbed(title="Degeneracy per User this Month",
                             color=0xbf5700)
        try:
            for person in userPosts[:10]:
                output += f"{str(person[0])} - {str(person[1])} posts\n"
        except:
            print("10 users haven't posted yet")

        #Get the total anime posts
        for person in userPosts:
            totalAnime += person[1]

        embed.add_field(name="Posts in #anime", value=output, inline=False)
        totalAnimeMessage = f"{str(totalAnime)} total posts made in #anime"
        embed.add_field(name="Collective degeneracy",
                        value=totalAnimeMessage,
                        inline=False)
        await ctx.send(embed=embed)

        #This is getting out of hand
        if totalAnime > 100:
            ctx.send("https://tenor.com/WmUi.gif")
Пример #5
0
 async def plex_top(self, ctx: commands.Context, searchTerm: str, timeRange: int):
     """
     Most popular media or most active users during time range (in days)
     Use 'movies','shows','artists' or 'users'
     """
     embed = discord.Embed(title=('Most popular '+searchTerm.lower() if searchTerm.lower() != 'users' else 'Most active users')+' in past '+str(timeRange)+(' days' if int(timeRange) > 1 else ' day'))
     count = 1
     if searchTerm.lower() == "movies":
         for m in self.request("get_home_stats","time_range="+str(timeRange)+"&stats_type=duration&stats_count=5")['response']['data'][0]['rows']:
             embed.add_field(name=str(count)+". "+str(m['title']),value=str(m['total_plays'])+(" plays" if int(m['total_plays']) > 1 else " play"),inline=False)
             count = count+1
         await ctx.send(embed=embed)
     elif searchTerm.lower() == "shows":
         for m in self.request("get_home_stats","time_range="+str(timeRange)+"&stats_type=duration&stats_count=5")['response']['data'][1]['rows']:
             embed.add_field(name=str(count)+". "+str(m['title']),value=str(m['total_plays'])+(" plays" if int(m['total_plays']) > 1 else " play"),inline=False)
             count = count+1
         await ctx.send(embed=embed)
     elif searchTerm.lower() == "artists":
         for m in self.request("get_home_stats","time_range="+str(timeRange)+"&stats_type=duration&stats_count=5")['response']['data'][2]['rows']:
             embed.add_field(name=str(count)+". "+str(m['title']),value=str(m['total_plays'])+(" plays" if int(m['total_plays']) > 1 else " play"),inline=False)
             count = count+1
         await ctx.send(embed=embed)
     elif searchTerm.lower() == "users":
         for m in self.request("get_home_stats","time_range="+str(timeRange)+"&stats_type=duration&stats_count=5")['response']['data'][7]['rows']:
             embed.add_field(name=str(count)+". "+str(m['friendly_name']),value=str(m['total_plays'])+(" plays" if int(m['total_plays']) > 1 else " play"),inline=False)
             count = count+1
         await ctx.send(embed=embed)
     else:
         ctx.send("Please try again. Use 'movies','shows','artists' or 'users'")
Пример #6
0
    def predicate(self, ctx: commands.Context, announcement: discord.Message,
                  reaction: discord.Reaction, user: discord.Member) -> bool:
        # If they've joined a game since requesting a player 2
        if self.already_playing(ctx.author):
            return True  # Is dealt with later on
        if (user.id not in (ctx.me.id, ctx.author.id)
                and str(reaction.emoji) == ACCEPT
                and reaction.message.id == announcement.id):
            if self.already_playing(user):
                self.bot.loop.create_task(
                    ctx.send(f"{user.mention} You're already playing a game!"))
                self.bot.loop.create_task(
                    announcement.remove_reaction(reaction, user))
                return False

            if user in self.waiting:
                self.bot.loop.create_task(
                    ctx.send(
                        f"{user.mention} Please cancel your game first before joining another one."
                    ))
                self.bot.loop.create_task(
                    announcement.remove_reaction(reaction, user))
                return False

            return True

        if (user.id == ctx.author.id and str(reaction.emoji) == CANCEL
                and reaction.message.id == announcement.id):
            return True
        return False
Пример #7
0
    async def shitpost(self, ctx: commands.Context, length=1023, seed=None):
        """Let the ai throw out some gibberish. First param is length"""

        out = gpt2.generate(self.tf_instance,
                            length=int(length),
                            return_as_list=True,
                            seed=seed)[0]
        ctx.send(out)
Пример #8
0
async def send_notice(ctx: commands.Context, message_url: str):
    event_message_id = re.search(r"([0-9]*)$", message_url).groups()[0]
    event_message = await ctx.fetch_message(event_message_id)
    event_datetime = await fetch_event_datetime(event_message)
    if event_datetime is not None:
        await send_notification(event_message, event_datetime)
    else:
        ctx.send("This doesn't seem to be a future event.")
Пример #9
0
    async def avatareasterify(self, ctx: commands.Context,
                              *colours: Union[discord.Colour, str]) -> None:
        """
        This "Easterifies" the user's avatar.

        Given colours will produce a personalised egg in the corner, similar to the egg_decorate command.
        If colours are not given, a nice little chocolate bunny will sit in the corner.
        Colours are split by spaces, unless you wrap the colour name in double quotes.
        Discord colour names, HTML colour names, XKCD colour names and hex values are accepted.
        """
        async def send(*args, **kwargs) -> str:
            """
            This replaces the original ctx.send.

            When invoking the egg decorating command, the egg itself doesn't print to to the channel.
            Returns the message content so that if any errors occur, the error message can be output.
            """
            if args:
                return args[0]

        async with ctx.typing():
            user = await self._fetch_user(ctx.author.id)
            if not user:
                await ctx.send(f"{Emojis.cross_mark} Could not get user info.")
                return

            egg = None
            if colours:
                send_message = ctx.send
                ctx.send = send  # Assigns ctx.send to a fake send
                egg = await ctx.invoke(self.bot.get_command("eggdecorate"),
                                       *colours)
                if isinstance(
                        egg,
                        str):  # When an error message occurs in eggdecorate.
                    await send_message(egg)
                    return
                ctx.send = send_message  # Reassigns ctx.send

            image_bytes = await user.display_avatar.replace(size=256).read()
            file_name = file_safe_name("easterified_avatar",
                                       ctx.author.display_name)

            file = await in_executor(PfpEffects.apply_effect, image_bytes,
                                     PfpEffects.easterify_effect, file_name,
                                     egg)

            embed = discord.Embed(
                title="Your Lovely Easterified Avatar!",
                description=
                "Here is your lovely avatar, all bright and colourful\nwith Easter pastel colours. Enjoy :D"
            )
            embed.set_image(url=f"attachment://{file_name}")
            embed.set_footer(text=f"Made by {ctx.author.display_name}.",
                             icon_url=user.display_avatar.url)

        await ctx.send(file=file, embed=embed)
Пример #10
0
    async def changesizeall(self, ctx: Context, new_size: str):
        if new_size not in cfg.PLATOON_SIZES:
            ctx.send("Invalid new size {}".format(new_size))
            return

        for event in EventDatabase.events.values():
            print("converting", event)
            await self._change_size(ctx, event, new_size)
        await ctx.send("All events resized succesfully")
        EventDatabase.toJson()
Пример #11
0
async def cc_helper(ctx: commands.Context, msg_func, atype, users):
    try:
        await ctx.defer()
    except AttributeError:
        pass
    filtered = {
        user
        for user in users if (not (user.bot or user.id == ctx.author.id))
        and await db.should_dm(user)
    }
    if filtered:
        last_msg = await utils.get_last_message_from(ctx)
        if last_msg is None:
            ctx.send(embed=await utils.errorize(
                f"Bruh, you have no messages to {atype}"))
        for user in filtered:
            await (user.dm_channel
                   or await user.create_dm()).send(embed=await msg_func(
                       ctx,
                       filtered,
                       from_message=last_msg,
                       to=user,
                   ))
        await ctx.send(  # XXX: Remove for BCC?
            embed=discord.Embed(
                title=f"I have {atype}'d the following people:",
                description=await
                make_list(person.mention for person in filtered),
                color=discord.Color.green(),
            ).add_field(
                name=f"Your message I {atype}'d them':",
                value=await utils.quote(last_msg.content) +
                f"\n\n[**Jump to message**]({last_msg.jump_url})",
                inline=False,
            ))

    if filtered != set(users):
        if filtered:
            await ctx.send("Wait, someone's missing? Here's why:")
        else:
            await ctx.send(f"You {atype}'d nobody. Here's why:")

        test = {user for user in users if not user.id == ctx.author.id}
        if test.issubset(filtered) or test == filtered:
            await ctx.channel.send(f":mirror: You can't {atype} yourself-")
        test = {user for user in users if await db.should_dm(user)}
        if test.issubset(filtered) or test == filtered:
            await ctx.channel.send(
                f":mute: Some of them do not want to be {atype}'d")
            return
        test = {user for user in users if not user.bot}
        if test.issubset(filtered) or test == filtered:
            await ctx.channel.send(
                ":robot: I can't dm other bots, you know. ~~They actually blocked me :sob:~~"
            )
Пример #12
0
async def cat(
    ctx: commands.Context,
    timedesc: str,
    selector: Optional[Union[discord.CategoryChannel, str]],
):
    "What are the most active channels in these categories?"

    look_at = []
    if not selector:
        look_at = ctx.channel.category.channels
    elif isinstance(selector, discord.CategoryChannel):
        look_at = selector.channels
    elif isinstance(selector, str):
        look_at = [
            channel for channel in ctx.guild.channels if channel.category
            and selector in channel.category.name.casefold()
        ]

    look_at = [
        channel for channel in look_at
        if channel.permissions_for(ctx.author).read_messages
    ]

    if not look_at:
        ctx.send(f"No channels found for '{selector}'")
        return

    channels = []

    for channel in look_at:
        row = tuple()
        if timedesc == "all":
            row = select(
                """SELECT count(*), count(distinct author) FROM messages
                WHERE channelid=:channelid""",
                {"channelid": channel.id},
            )[0]
        else:
            row = select(
                """SELECT count(*), count(distinct author) FROM messages
                WHERE channelid=:channelid AND created_at >= datetime('now', :ago)""",
                {
                    "channelid": channel.id,
                    "ago": sql_time(timedesc)
                },
            )[0]
        channels.append((channel.name, row[0], row[1]))

    reply = ""

    for channel in sorted(channels, key=lambda tup: tup[1], reverse=True):
        reply += f"{channel[0]}: {channel[1]} messages from {channel[2]} users\n"

    await paged_send(ctx, reply)
Пример #13
0
async def cc_helper(ctx: commands.Context, msg_func, atype, users):
    await ctx.defer()
    filtered = [
        user for user in users if not (user.bot or user.id == ctx.author.id)
    ]
    if filtered:
        last_msg = await utils.get_last_message_from(ctx.author,
                                                     channel=ctx.channel)
        if last_msg is None:
            ctx.send(embed=await utils.errorize(
                f"Bruh, you have no messages to {atype}"))
        assert last_msg is None
        for user in filtered:
            await (user.dm_channel
                   or await user.create_dm()).send(embed=await msg_func(
                       ctx,
                       filtered,
                       from_message=last_msg,
                       to=user,
                   ))
        await ctx.send(  # XXX: Remove for BCC?
            embed=discord.Embed(
                title=f"I have {atype}'d the following people:",
                description=await
                make_list(person.mention for person in filtered),
                color=discord.Color.green(),
            ).add_field(
                name=f"Your message I {atype}'d them':",
                value=await utils.quote(last_msg.content) +
                f"\n\n[**Jump to message**]({last_msg.jump_url})",
                inline=False,
            ))
    if set(filtered) != set(users):
        if filtered:
            await ctx.channel.send("Wait, someone's missing? Here's why:")
        else:
            await ctx.send(f"You {atype}'d nobody. Here's why:")
        if {user for user in users if not user.bot} == set(filtered):
            await ctx.channel.send(
                ":robot: I can't dm other bots, you know. ~~They actually blocked me :sob:~~"
            )
        elif {user
              for user in users
              if not user.id == ctx.author.id} == set(filtered):
            await ctx.channel.send(f":mirror: You can't {atype} yourself-")
        else:  # Both
            await ctx.channel.send(
                ":robot: I can't dm other bots, you know. ~~They actually blocked me :sob:~~"
            )
            await ctx.channel.send(
                f":mirror: Also, you can't {atype} yourself.")
Пример #14
0
async def add_to_playlist(ctx: Context, url):
    '''function to be called to add url or keywords to play musics in thing'''
    if type(url) == list:
        url = " ".join(url)
    if type(url) != str:
        ctx.send(f"Fudeu: ErrIntern, url not str, it's {type(url)}")
        return
    if not ctx.message.author.voice:
        await ctx.send(f"{ctx.message.author.name} is not connected to a voice channel")
        return
    print(url)
    playlist.append(url)
    if len(playlist) == 1:
        await true_play(ctx, playlist[0])
Пример #15
0
    async def changesize(self, ctx: Context, event: EventEvent, new_size: str):
        if new_size not in cfg.PLATOON_SIZES:
            ctx.send("Invalid new size {}".format(new_size))
            return

        ret = event.changeSize(new_size)
        if ret is None:
            await ctx.send("{}: nothing to be done".format(event))
            return
        if ret.strip() != "":
            await ctx.send(ret)

        await self._update_event(event)
        await ctx.send("Event resized succesfully")
Пример #16
0
async def createNewController(ctx: commands.Context) -> None:
    # determine if this channel is already connected to a controller
    existingController = getControllerForMessageContext(ctx)
    if existingController is not None:
        ctx.send("This channel is already registered to a controller")
        raise ChannelAlreadyRegistered(ctx.message.channel)

    # Create the new controller
    ctx.bot.emulatorControllerGroup.createController(ctx.message.channel)
    # Find new controller
    controller = getControllerForMessageContext(ctx)
    if controller is None:
        ctx.send("Failed to create controller")
    else:
        await ctx.send(craftControllerStatus(controller))
Пример #17
0
 async def restart(self, ctx: commands.Context):
     '''
     Restart the Secret Santa after pause
     '''
     currAuthor = ctx.author
     is_paused = True
     if ((currAuthor.top_role == ctx.guild.roles[-1]) and is_paused):
         # ensure all users have all info submitted
         all_fields_complete = True
         for user in self.usr_list:
             if (user.wishlisturl_is_set() and user.pref_is_set()):
                 pass
             else:
                 all_fields_complete = False
                 try:
                     await currAuthor.send(
                         BOT_ERROR.HAS_NOT_SUBMITTED(user.name))
                     await ctx.send(
                         "`Partner assignment cancelled: participant info incomplete.`"
                     )
                 except Exception as e:
                     BOT_ERROR.output_exception(e, self.logger)
                     await ctx.send(currAuthor.mention +
                                    BOT_ERROR.DM_FAILED)
                     BOT_ERROR.output_error(
                         currAuthor.mention + BOT_ERROR.DM_FAILED,
                         self.logger)
         list_changed = self.SecretSantaHelper.usr_list_changed_during_pause(
             self.usr_list, self.user_left_during_pause)
         if (list_changed):
             ctx.send(
                 f"User list changed during the pause. Partners must be picked again with `{CONFIG.prefix}start`."
             )
         else:
             self.exchange_started = True
             is_paused = False
             self.config['programData']['exchange_started'] = True
             self.config.write()
             await ctx.send(
                 "No change was made during the pause. Secret Santa resumed with the same partners."
             )
     elif (currAuthor.top_role != ctx.guild.roles[-1]):
         await ctx.send(BOT_ERROR.NO_PERMISSION(ctx.guild.roles[-1]))
     elif (not is_paused):
         await ctx.send(BOT_ERROR.NOT_PAUSED)
     else:
         await ctx.send(BOT_ERROR.UNREACHABLE)
     return
Пример #18
0
    async def _help(self, ctx: commands.Context):
        embed = discord.Embed(
            title='� GMBT 봇 전체 �령어',
            description=
            '(�괄�)� 필� �력, [�괄�]� 선� �력��다. *별�� 여�� �력할 � �� 부분��다.\n\n',
            color=colors.PRIMARY)
        for name, value in help.gethelps():
            embed.add_field(name='�' + name,
                            value=value.format(p=self.prefix),
                            inline=False)

        if ctx.channel.type != discord.ChannelType.private:
            msg, sending = await asyncio.gather(
                ctx.author.send(embed=embed),
                ctx.send(embed=discord.Embed(
                    title='{} �움�� 전송�고 ���다...'.
                    format(self.emj.get(ctx, 'loading')),
                    color=colors.PRIMARY)))
            await sending.edit(embed=discord.Embed(
                title='{} �움�� 전송���다!'.format(
                    self.emj.get(ctx, 'check')),
                description=
                f'**[DM 메�지]({msg.jump_url})**를 확��세�!',
                color=colors.SUCCESS))
        else:
            msg = await ctx.author.send(embed=embed)
Пример #19
0
    async def anonymity(self, ctx: commands.Context, value: str):
        """Set anonymity level

		value: [none | guild | full]
		"""
        opts = ['none', 'guild', 'full']
        if value not in opts:
            ctx.send("Options are: " + ', '.join(opts))
        else:
            config['anonymity'] = value
            self.__save()
            await self.send(
                message=ctx.message,
                announcement=True,
                text="> New anonymity policy: **{}**".format(value))
        await self.tryDelete(ctx.message)
Пример #20
0
 async def king(self, ctx: Context, player1: Member, player2: Member,
                player3: Member, *players: Member):
     players = list(players)
     players.extend((player1, player2, player3))
     tasks = list()
     king = None
     i = 0
     count_description = literals('king')['count'] % (len(players) - 1)
     footer = literals('king')['footer']
     while len(players):
         player1 = players.pop(randrange(0, len(players)))
         if i == 0:
             king = player1
         else:
             embed = ChainedEmbed(title=literals('king')['number'] % i,
                                  description=count_description)
             embed.set_footer(text=footer)
             tasks.append(player1.send(embed=embed))
         i = i + 1
     embed = ChainedEmbed(title=literals('king')['king'] %
                          king.display_name,
                          description=count_description)
     embed.set_image(url=king.avatar_url)
     embed.set_footer(text=footer)
     tasks.append(
         ctx.send(' '.join(
             [member.mention for member in ctx.message.mentions]),
                  embed=embed))
     tasks.append(ctx.message.delete())
     await asyncio.wait(tasks)
Пример #21
0
    async def invite_list(self, ctx: Context) -> None:
        """Retrieves a list of active invites"""
        invit = ""
        invitations = await ctx.guild.invites()
        for invite in invitations:
            temp = "Max Age: " + str(invite["max_age"]) + "Code: " + str(
                invite["code"]) + "Guild: " + str(invite["guild"])
            invit += temp + "\n"
            invitelist.append(invit)

        embed.discord.Embed(title="Invites", colour=Colour.blurple())

        for i in range(len(invitelist)):
            embed.add_field(name="Invite", value=invitelist[i])

        ctx.send(embed=embed)
Пример #22
0
 def __init__(self, ctx: commands.Context, *args, **kargs):
     self.message_stack: typing.Sequence[
         discord.Message] = collections.deque()
     ctx._send = ctx.send
     ctx.send = self.push_message
     self.message: discord.Message
     super().__init__(ctx, *args, **kargs)
Пример #23
0
 async def rand_mac_hs(self, context: Context, num: int):
     assert num <= 20, context.send("Too many people!")
     people = filter(
         lambda user: 695383484092645426 in map(
             lambda role: role.id, user.roles), context.guild.members)
     chosen_people = random.sample(list(people), num)
     await context.send("\n".join(str(person) for person in chosen_people))
Пример #24
0
    async def spend(self, ctx: Context, amount: int, attribute_name: str):
        member = ctx.message.author
        character = self.bot.get_character(member.id)

        if not character:
            await ctx.send(f"Spieler nicht gefunden!")
            return

        attribute = character.get_attribute(attribute_name)

        if not attribute:
            await ctx.send(
                f"Der Charakter {character.name} hat kein Attribut namens '{attribute_name}'!"
            )
            return

        try:
            attribute.spend(amount)
        except NotSpendableException:
            await ctx.send(
                f"Das Attribut {attribute.name} kann man nicht ausgeben!")
            return
        except UnderflowAttributeException as e:
            await ctx.send(
                f"Du hast nur noch {e.current} {attribute.name} und kannst nicht unter {e.minium} sein!"
            )
            return

        self.bot.save_stats()
        await (ctx.send(
            f":bust_in_silhouette: {character.name} :clipboard: :arrow_lower_right: **{attribute} {attribute.name}**"
        ))
Пример #25
0
    async def gain(self, ctx: Context, amount: int, attribute_name: str):
        member = ctx.message.author
        character = self.bot.get_character(member.id)

        if not character:
            await ctx.send(f"Spieler nicht gefunden!")
            return

        attribute = character.get_attribute(attribute_name)

        if not attribute:
            await ctx.send(
                f"Der Charakter {character.name} hat kein Attribut namens '{attribute_name}'!"
            )
            return

        try:
            attribute.gain(amount)
        except NotSpendableException:
            await ctx.send(
                f"Das Attribut {attribute.name} kann man nicht ausgeben!")
            return
        except OverflowAttributeException as e:
            # For convenience, we simply set the attribute to its maximum instead of demanding a user action
            attribute.update(e.maximum)

        self.bot.save_stats()
        await (ctx.send(
            f":bust_in_silhouette: {character.name} :clipboard: :arrow_upper_right: **{attribute} {attribute.name}**"
        ))
Пример #26
0
	async def _remove(self, ctx: commands.Context, index: int):
		if len(ctx.voice_state.songs) == 0:
			return ctx.send(embed=discord.Embed(title=':mute: 재생목록이 없습니다.',colour = 0x2EFEF7))
		
#		remove_result = '`{0}.` [**{1.source.title}**] 삭제 완료!\n'.format(index, ctx.voice_state.songs[index - 1])
		result = await ctx.send(embed=discord.Embed(title='`{0}.` [**{1.source.title}**] 삭제 완료!\n'.format(index, ctx.voice_state.songs[index - 1]),colour = 0x2EFEF7))
		ctx.voice_state.songs.remove(index - 1)
		await result.add_reaction('✅')
Пример #27
0
 async def spoiler(self, ctx: commands.Context, *, content=""):
     """
     Spoiler a message and its attachments.
     If you have manage message permissions, you can reply to a message with just `m.spoiler` to reupload the message spoilered and delete the original.
     """
     async with ctx.typing():
         outattachments = []
         for att in ctx.message.attachments:
             outattachments.append(await att.to_file(spoiler=True))
         embed = discord.Embed().set_author(name=ctx.author.display_name,
                                            icon_url=ctx.author.avatar_url)
         if content:
             content = f"|| {discord.utils.escape_markdown(content)} ||"
         if content or outattachments:
             await asyncio.gather(
                 ctx.send(content=content,
                          files=outattachments,
                          embed=embed,
                          allowed_mentions=discord.AllowedMentions.none()),
                 ctx.message.delete())
             return
         elif ctx.message.reference and (
                 ctx.author.permissions_in(ctx.channel).manage_messages
                 or ctx.message.reference.resolved.author == ctx.author):
             outattachments = []
             for att in ctx.message.reference.resolved.attachments:
                 outattachments.append(await att.to_file(spoiler=True))
             embed = discord.Embed().set_author(
                 name=ctx.message.reference.resolved.author.display_name,
                 icon_url=ctx.message.reference.resolved.author.avatar_url)
             embed.set_footer(
                 text=f"Spoilered by {ctx.author.display_name}",
                 icon_url=ctx.author.avatar_url)
             content = f"|| {discord.utils.escape_markdown(ctx.message.reference.resolved.content)} ||" \
                 if ctx.message.reference.resolved.content else ""
             await asyncio.gather(
                 ctx.send(content=content,
                          files=outattachments,
                          embed=embed,
                          allowed_mentions=discord.AllowedMentions.none()),
                 ctx.message.delete(),
                 ctx.message.reference.resolved.delete())
             return
         await ctx.reply(
             "❌ no content to spoiler or no replied message to spoiler.")
Пример #28
0
    async def queuespotify(self,
                           ctx: commands.Context,
                           limit: int = 5,
                           playlist_code: str = ""):
        """Gets the songs from our spotify playlist"""
        try:
            if playlist_code:
                songs = spotify_songs(playlist_code, limit)
            else:
                songs = spotify_songs(limit=limit)
        except SpotifyException as e:
            ctx.send(delete_after=STANDARD_DELETION_TIME,
                     embed=common_embed(name="Spotify Error",
                                        value=str(e),
                                        color=ERROR))

        for song in songs:
            await self.play(ctx, url=str(song))
Пример #29
0
    async def changesizeall(self, ctx: Context, new_size: str):
        if new_size not in cfg.PLATOON_SIZES:
            ctx.send("Invalid new size {}".format(new_size))
            return

        for event in EventDatabase.events.values():
            print("converting", event)
            ret = event.changeSize(new_size)
            if ret is None:
                await ctx.send("{}: nothing to be done".format(event))
                continue
            if ret.strip() != "":
                await ctx.send(ret)

            await self._update_event(event, export=False)
            await ctx.send("Event {} resized succesfully".format(event))
        await ctx.send("All events resized succesfully")
        EventDatabase.toJson()
Пример #30
0
 def cog_check(self, ctx: Context):
     role = get_role(ctx.guild, GuildSetting.MIN_MOD_ROLE)
     if role is None:
         # TODO !!!!
         create_task(
             ctx.send(
                 "Por favor configura el mínimo rol requerido para usar los comandos de moderación: "
                 f"`{ctx.prefix}set role minmod @Rol`."))
         return False
     return ctx.author.top_role and ctx.author.top_role >= role