예제 #1
0
def startup(dispatcher):
    """
    This method is ran when the bot starts up. Currently used to persist aliases that are created
    @param dispatcher: command_dispatcher.CommandDispatcher
    """
    logger.info("Initializing saved commands")
    msg = Message(content="!alias !d !dankmemes")
    msg.server = Server(id='108769127627280384')
    dispatcher.run_command(msg)
    msg = Message(content="!alias !cf !cowsay $fortune=True")
    msg.server = Server(id='108769127627280384')
    dispatcher.run_command(msg)
    msg = Message(content="!alias !cf !cowsay $fortune=True")
    msg.author = User(id='108768204184113152')
    dispatcher.run_command(msg)
    msg = Message(content="!alias !d !dankmemes")
    msg.author = User(id='108768204184113152')
    dispatcher.run_command(msg)
예제 #2
0
    async def send(self, message: discord.Message,
                   destination: typing.Union[discord.TextChannel, discord.DMChannel,
                                             discord.User, discord.Member] = None,
                   from_mod: bool = False,
                   note: bool = False,
                   anonymous: bool = False) -> None:
        if self.close_task is not None:
            # cancel closing if a thread message is sent.
            self.bot.loop.create_task(
                self.cancel_closure()
            )
            self.bot.loop.create_task(
                self.channel.send(embed=discord.Embed(
                    color=discord.Color.red(),
                    description='Scheduled close has been cancelled.'
                ))
            )

        if not self.ready:
            await self.wait_until_ready()

        if not from_mod and not note:
            self.bot.loop.create_task(
                self.bot.api.append_log(message, self.channel.id)
            )

        destination = destination or self.channel

        author = message.author

        embed = discord.Embed(
            description=message.content,
            timestamp=message.created_at
        )

        system_avatar_url = 'https://discordapp.com/assets/' \
                            'f78426a064bc9dd24847519259bc42af.png'

        if not note:
            if anonymous and from_mod and \
                    not isinstance(destination, discord.TextChannel):
                # Anonymously sending to the user.
                tag = self.bot.config.get('mod_tag',
                                          str(message.author.top_role))
                name = self.bot.config.get('anon_username', tag)
                avatar_url = self.bot.config.get('anon_avatar_url',
                                                 self.bot.guild.icon_url)
            else:
                # Normal message
                name = str(author)
                avatar_url = author.avatar_url

            embed.set_author(name=name,
                             icon_url=avatar_url,
                             url=message.jump_url)
        else:
            # Special note messages
            embed.set_author(name=f'Note ({author.name})',
                             icon_url=system_avatar_url,
                             url=message.jump_url)

        delete_message = not bool(message.attachments)

        attachments = [(a.url, a.filename) for a in message.attachments]

        images = [x for x in attachments if is_image_url(*x)]
        attachments = [x for x in attachments if not is_image_url(*x)]

        image_links = [
            (link, None) for link in re.findall(r'(https?://[^\s]+)',
                                                message.content)
        ]
        image_links = [x for x in image_links if is_image_url(*x)]
        images.extend(image_links)

        embedded_image = False

        prioritize_uploads = any(i[1] is not None for i in images)

        additional_images = []
        additional_count = 1

        for att in images:
            if not prioritize_uploads or (
                    is_image_url(*att) and not embedded_image and att[1]
            ):
                embed.set_image(url=att[0])
                if att[1]:
                    embed.add_field(name='Image',
                                    value=f'[{att[1]}]({att[0]})')
                embedded_image = True
            elif att[1] is not None:
                if note:
                    color = discord.Color.blurple()
                elif from_mod:
                    color = self.bot.mod_color
                else:
                    color = self.bot.recipient_color

                img_embed = discord.Embed(color=color)
                img_embed.set_image(url=att[0])
                img_embed.title = att[1]
                img_embed.url = att[0]
                img_embed.set_footer(
                    text=f'Additional Image Upload ({additional_count})'
                )
                img_embed.timestamp = message.created_at
                additional_images.append(destination.send(embed=img_embed))
                additional_count += 1

        file_upload_count = 1

        for att in attachments:
            embed.add_field(name=f'File upload ({file_upload_count})',
                            value=f'[{att[1]}]({att[0]})')
            file_upload_count += 1

        if from_mod:
            # noinspection PyUnresolvedReferences,PyDunderSlots
            embed.color = self.bot.mod_color  # pylint: disable=E0237
            # Anonymous reply sent in thread channel
            if anonymous and isinstance(destination, discord.TextChannel):
                embed.set_footer(text='Anonymous Reply')
            # Normal messages
            elif not anonymous:
                tag = self.bot.config.get('mod_tag',
                                          str(message.author.top_role))
                embed.set_footer(text=tag)  # Normal messages
            else:
                embed.set_footer(
                    text=self.bot.config.get('anon_tag', 'Response')
                )
        elif note:
            # noinspection PyUnresolvedReferences,PyDunderSlots
            embed.color = discord.Color.blurple()  # pylint: disable=E0237
        else:
            embed.set_footer(text=f'Recipient')
            # noinspection PyUnresolvedReferences,PyDunderSlots
            embed.color = self.bot.recipient_color  # pylint: disable=E0237

        await destination.trigger_typing()

        if not from_mod:
            mentions = self.get_notifications()
        else:
            mentions = None

        await destination.send(mentions, embed=embed)
        if additional_images:
            self.ready = False
            await asyncio.gather(*additional_images)
            self.ready = True

        if delete_message:
            self.bot.loop.create_task(ignore(message.delete()))
예제 #3
0
 def set_message(self, msg: discord.Message) -> Awaitable:
     """Edit state message to show actual information
     """
     return msg.edit(content=self.title, embed=None)
async def on_message(self: discord.Client, message: discord.Message):
    if message.author.bot:
        return
    if message.channel.type == discord.ChannelType.private:
        channel = self.get_channel(Ids["Dm_bot_log_channel"])
        if message.author.id != self.id:
            await message.author.send("Hello !\nI am a bot, so I cannot answer you !\nSupport server:\nhttps://discord.gg/KQmstPw")
            if len(message.attachments) == 0:
                await channel.send(f"```{message.content}``` from:\n{message.author} (`{message.author.id}`)\nMessage_id: `{message.id}`")
            else:
                files = []
                for attachment in message.attachments:
                    response = requests.get(attachment.url)
                    img = BytesIO(response.content)
                    files += [discord.File(img, filename=f"file.{response.headers['Content-Type'].split('/')[1]}")]
                    if message.content == "":
                        message.content = " "
                await channel.send(f"```{message.content}``` from:\n{message.author} (`{message.author.id}`)\nMessage_id: `{message.id}`", files=files)
        return

    if not Config["message_content_intent"]:
        return

    # ----- Auto Moderation -----
    if message.guild.id == Ids["Support_server"]:
        if message.author.top_role < discord.utils.get(message.guild.roles, name="Staff"):
            text = message.content

            if Config["perspective_api"]:
                import googleapiclient
                from googleapiclient import discovery, errors

                client = googleapiclient.discovery.build(
                    "commentanalyzer",
                    "v1alpha1",
                    developerKey=Login["perspective_api"]["token"],
                    discoveryServiceUrl="https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1",
                    static_discovery=False,
                )
                analyze_request = {
                    "comment": {"text": text},
                    "requestedAttributes": {
                        "TOXICITY": {}
                    },
                    "doNotStore": True
                }
                try:
                    response = client.comments().analyze(body=analyze_request).execute()
                    d = {}
                    txt = f"Text: `{text}`\n"
                    for attribute, data in response["attributeScores"].items():
                        d[attribute] = data['spanScores'][0]['score']['value']
                        txt += f"{attribute}: {data['spanScores'][0]['score']['value']} ({data['spanScores'][0]['score']['type']})\n"
                    max_value = (max(d, key=d.get), d[max(d, key=d.get)])
                    if max_value[1] > 0.5:
                        channel = message.guild.get_channel(Ids["Perspective_api_channel"])
                        await channel.send(embed=create_embed(f"{max_value[0]}: {max_value[1]}", f"[This message]({message.jump_url}) with the content: ```{text}``` has been flagged for {max_value[0]} with a probability of {max_value[1]}", message.guild.me.color, "", message.guild.me.avatar.url))
                        await message.author.timeout(datetime.timedelta(minutes=5), reason=f"Toxic message:\n{text}")
                        await message.reply(f"{message.author.mention} has been timed out for {max_value[0]}\n\n*This message will be deleted in 5 minutes*", delete_after=300)

                except googleapiclient.errors.HttpError as e:
                    print("Error (PerspectiveApi):", e)
                    pass

            # Test Link
            import re
            pattern = re.compile("""(https?|ftp)://[^\s/$.?#].[^\s]*""", re.IGNORECASE + re.DOTALL)
            if pattern.search(text) is not None:
                await message.author.timeout(datetime.timedelta(minutes=5), reason=f"Link in:\n{text}")
                await message.delete()
                await message.channel.send(f"{message.author.mention} has been timed out for link\n\n*This message will be deleted in 5 minutes*", delete_after=300)

            # Test Discord Invite
            import re
            pattern = re.compile("""discord(?:\.com|app\.com|\.gg)[\/invite\/]?(?:[a-zA-Z0-9\-]{2,32})""", re.IGNORECASE + re.DOTALL)
            if pattern.search(text) is not None:
                await message.author.timeout(datetime.timedelta(minutes=5), reason=f"Link in:\n{text}")
                await message.delete()
                await message.channel.send(f"{message.author.mention} has been timed out for discord invite\n\n*This message will be deleted in 5 minutes*", delete_after=300)

    if message.author.id in Ids["Creators"]:
        if message.content.startswith("dltmsg") and message.channel.permissions_for(message.author).manage_messages:
            number = int(message.content.split(" ")[1])
            message_numbers = 0
            async for msg in message.channel.history(limit=number + 1):
                if not msg.pinned:
                    message_numbers += 1
                    await msg.delete()
            message_numbers -= 1
            embed = create_embed("Messages deleted", f"{message_numbers: ,} messages deleted", message.guild.me.color, "", message.guild.me.avatar.url)
            msg = await message.channel.send(embed=embed)
            import asyncio

            await asyncio.sleep(10)
            await msg.delete()
            return
    return
예제 #5
0
파일: thread.py 프로젝트: xetaah/modmail
    async def send(
        self,
        message: discord.Message,
        destination: typing.Union[
            discord.TextChannel, discord.DMChannel, discord.User, discord.Member
        ] = None,
        from_mod: bool = False,
        note: bool = False,
        anonymous: bool = False,
    ) -> None:

        self.bot.loop.create_task(
            self._restart_close_timer()
        )  # Start or restart thread auto close

        if self.close_task is not None:
            # cancel closing if a thread message is sent.
            self.bot.loop.create_task(self.cancel_closure())
            self.bot.loop.create_task(
                self.channel.send(
                    embed=discord.Embed(
                        color=discord.Color.red(),
                        description="Scheduled close has been cancelled.",
                    )
                )
            )

        if not self.ready:
            await self.wait_until_ready()

        if not from_mod and not note:
            self.bot.loop.create_task(self.bot.api.append_log(message, self.channel.id))

        destination = destination or self.channel

        author = message.author

        embed = discord.Embed(description=message.content, timestamp=message.created_at)

        system_avatar_url = (
            "https://discordapp.com/assets/f78426a064bc9dd24847519259bc42af.png"
        )

        if not note:
            if (
                anonymous
                and from_mod
                and not isinstance(destination, discord.TextChannel)
            ):
                # Anonymously sending to the user.
                tag = self.bot.config["mod_tag"]
                if tag is None:
                    tag = str(message.author.top_role)
                name = self.bot.config["anon_username"]
                if name is None:
                    name = tag
                avatar_url = self.bot.config["anon_avatar_url"]
                if avatar_url is None:
                    avatar_url = self.bot.guild.icon_url
            else:
                # Normal message
                name = str(author)
                avatar_url = author.avatar_url

            embed.set_author(name=name, icon_url=avatar_url, url=message.jump_url)
        else:
            # Special note messages
            embed.set_author(
                name=f"Note ({author.name})",
                icon_url=system_avatar_url,
                url=message.jump_url,
            )

        delete_message = not bool(message.attachments)

        ext = [(a.url, a.filename) for a in message.attachments]

        images = []
        attachments = []
        for attachment in ext:
            if is_image_url(attachment[0]):
                images.append(attachment)
            else:
                attachments.append(attachment)

        image_urls = re.findall(
            r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
            message.content,
        )

        image_urls = [(url, None) for url in image_urls if is_image_url(url)]
        images.extend(image_urls)

        embedded_image = False

        prioritize_uploads = any(i[1] is not None for i in images)

        additional_images = []
        additional_count = 1

        for url, filename in images:
            if not prioritize_uploads or (
                is_image_url(url) and not embedded_image and filename
            ):
                embed.set_image(url=url)
                if filename:
                    embed.add_field(name="Image", value=f"[{filename}]({url})")
                embedded_image = True
            elif filename is not None:
                if note:
                    color = discord.Color.blurple()
                elif from_mod:
                    color = self.bot.mod_color
                else:
                    color = self.bot.recipient_color

                img_embed = discord.Embed(color=color)
                img_embed.set_image(url=url)
                img_embed.title = filename
                img_embed.url = url
                img_embed.set_footer(
                    text=f"Additional Image Upload ({additional_count})"
                )
                img_embed.timestamp = message.created_at
                additional_images.append(destination.send(embed=img_embed))
                additional_count += 1

        file_upload_count = 1

        for url, filename in attachments:
            embed.add_field(
                name=f"File upload ({file_upload_count})", value=f"[{filename}]({url})"
            )
            file_upload_count += 1

        if from_mod:
            embed.colour = self.bot.mod_color
            # Anonymous reply sent in thread channel
            if anonymous and isinstance(destination, discord.TextChannel):
                embed.set_footer(text="Anonymous Reply")
            # Normal messages
            elif not anonymous:
                mod_tag = self.bot.config["mod_tag"]
                if mod_tag is None:
                    mod_tag = str(message.author.top_role)
                embed.set_footer(text=mod_tag)  # Normal messages
            else:
                embed.set_footer(text=self.bot.config["anon_tag"])
        elif note:
            embed.colour = discord.Color.blurple()
        else:
            embed.set_footer(text=f"Message ID: {message.id}")
            embed.colour = self.bot.recipient_color

        try:
            await destination.trigger_typing()
        except discord.NotFound:
            logger.warning("Channel not found.", exc_info=True)
            return

        if not from_mod and not note:
            mentions = self.get_notifications()
        else:
            mentions = None

        msg = await destination.send(mentions, embed=embed)

        if additional_images:
            self.ready = False
            await asyncio.gather(*additional_images)
            self.ready = True

        if delete_message:
            self.bot.loop.create_task(ignore(message.delete()))

        return msg
예제 #6
0
 async def trigger(self, cog: commands.Cog,
                   message: discord.Message) -> Any:
     if await self.check_constraints(cog.bot, message):
         message = MessageWrapper(message)
         message.detection = self
         cog.bot.loop.create_task(self.callback(cog, message))
 async def on_support(self, message: discord.Message):
     loop = asyncio.get_running_loop()
     loop.create_task(message.delete())
     loop.create_task(self.start_support_session(message))
     return True
예제 #8
0
async def on_message(message: Message):
    if message.is_system():
        if message.channel.id == 710597940573503518:
            await message.add_reaction("🇹")
            await message.add_reaction("🇭")
            await message.add_reaction("🇦")
            await message.add_reaction("🇳")
            await message.add_reaction("🇰")
            await message.add_reaction("🇾")
            await message.add_reaction("🇴")
            await message.add_reaction("🇺")
            await message.add_reaction("<a:as_black_hearts:710602475719229602>"
                                       )
            embed = discord.Embed(
                description=
                "**Thank you so much for deciding to boost Asmodeus✨!**\n\nYou're now eligible for all the stuff listed in <#710597943232692375>. You can also see them by using the ``!tag boosting`` command in any of the text channels.\n\nPlease contact <@680519129219727380> to collect your perks for boosting.\n\n``` ```",
                color=0xFFB6C1,
                timestamp=datetime.utcnow())
            embed.set_thumbnail(
                url=
                "https://cdn.discordapp.com/attachments/680521500352315423/685555150085029915/asmodeus_boosted_thumbnail.png"
            )
            embed.set_image(
                url=
                "https://cdn.discordapp.com/attachments/680521500352315423/685556831761989676/ily.gif"
            )
            await message.author.send("``` ```", embed=embed)
            await message.author.send("``` ```")
            await message.channel.send("<3 {}".format(message.author.mention))

    elif message.content.lower(
    ) == "nigger" or "nigger" in message.content.lower():
        await message.delete()
    elif message.channel.id == 710598783100256337:
        if message.author.bot == True:
            return
        await message.channel.set_permissions(message.author,
                                              send_messages=False)
        intros = message.channel
        chan = bot.get_channel(670392877800620033)
        print(chan)
        msg = None
        async for message in chan.history(limit=1):
            msg = await intros.fetch_message(int(message.content))
            await message.delete()
        await msg.delete()
        embed = discord.Embed(
            title="‧̍̊˙˚˙ᵕ꒳ᵕ˙˚˙─Reminder:─˙˚˙ᵕ꒳ᵕ˙˚˙‧̍̊",
            description=
            "**Before you post your introduction, keep in mind:**\n<a:as_black_hearts:710602475719229602> - You are allowed to post __one message__ in this channel, keep that in mind while making your introduction. After posting the introduction the channel will become __read-only__.\n<a:as_black_hearts:710602475719229602> - Deleting your introduction __will not__ let you type again, Please contact <@680519129219727380> if you want to edit your introduction.\n<a:as_black_hearts:710602475719229602> - Useless messages in this channel will be deleted.",
            color=0x000000,
            timestamp=datetime.utcnow())
        msg2 = await intros.send(embed=embed)
        await chan.send("{}".format(msg2.id))
    elif message.channel.id == 710597943232692375 and message.author.bot == False:
        boosters = message.channel
        chan = bot.get_channel(670392843508121652)
        print(chan)
        msg = None
        async for message in chan.history(limit=1):
            msg = await boosters.fetch_message(int(message.content))
            await message.delete()
        await msg.delete()
        embed = discord.Embed(
            title=".・゜-: ✧ :- Booster Perks -: ✧ :-゜・.",
            description=
            "<a:as_black_hearts:710602475719229602> ─ You will get permission to advertise whatever you want in <#710597943232692375>.\n\n<a:as_black_hearts:710602475719229602> ─ You will get the booster role that is hoisted above the members.\n\n<a:as_black_hearts:710602475719229602> ─ You get a special role, which you personalize with name and color.\n\n<a:as_black_hearts:710602475719229602> ─ You get a custom response when someone mentions your name in the chat. \n\n<a:as_black_hearts:710602475719229602> ─ You can apply for staff even if the applications are closed.\n\n<a:as_black_hearts:710602475719229602> ─ Higher chances in winning future giveaways, also booster only giveaways. \n\n<a:as_black_hearts:710602475719229602> ─ You will get your own voice channel and text channel, alike a blog, where it can be public or private. You can invite your friends in it and do whatever your hearts desire. \n\n<a:as_black_hearts:710602475719229602> ─ You'll get access to the logs (join/leave, deleted and edit messages, etc) without having to be staff.",
            color=0xB6B3FC,
            timestamp=datetime.utcnow())
        msg2 = await boosters.send(embed=embed)
        await chan.send("{}".format(msg2.id))
    elif bot.user.mentioned_in(message):
        if "ping" in message.content:
            await message.channel.send("{} pong".format(message.author.mention)
                                       )
        elif "pong" in message.content:
            await message.channel.send("{} ping".format(message.author.mention)
                                       )
        else:
            splitted = message.content.split(" ")
            if len(splitted) > 1:
                return
            prefix = None
            for key, value in serverPrefixes.items():
                if int(key) == message.guild.id:
                    prefix = str(value)
            if prefix is None:
                prefix = "! (Default)"
            sb = None
            for key, value in starboardChannels.items():
                if int(key) == message.guild.id:
                    sbb = bot.get_channel(int(value))
                    sb = sbb.mention
            if sb is None:
                sb = "Not enabled, use the ``scoreboard`` command to enable it."
            confess = None
            for key, value in confessChannels.items():
                if int(key) == message.guild.id:
                    confesss = bot.get_channel(int(value))
                    confess = confesss.mention
            if confess is None:
                confess = "Not enabled, use the ``setconfess`` command to enable it."
            muted = None
            for key, value in serverMuted.items():
                if int(key) == message.guild.id:
                    mutedd = message.guild.get_role(int(value))
                    muted = mutedd.mention
            if muted is None:
                muted = "Not set, use the ``setmuted`` command to set it. Otherwise ``mute`` wouldn't work."
            editLogsS = None
            deleteLogsS = None
            memberLogsS = None
            punishLogsS = None
            for key, value in deleteLogs.items():
                if int(key) == message.guild.id:
                    deleteLogss = bot.get_channel(int(value))
                    deleteLogsS = deleteLogss.mention
            if deleteLogs is None:
                deleteLogsS = ":x:"
            for key, value in editLogs.items():
                if int(key) == message.guild.id:
                    editLogss = bot.get_channel(int(value))
                    editLogsS = editLogss.mention
            if editLogs is None:
                editLogsS = ":x:"
            for key, value in memberLogs.items():
                if int(key) == message.guild.id:
                    memberLogss = bot.get_channel(int(value))
                    memberLogsS = memberLogss.mention
            if memberLogs is None:
                memberLogsS = ":x:"
            for key, value in punishLogs.items():
                if int(key) == message.guild.id:
                    punishLogss = bot.get_channel(int(value))
                    punishLogsS = punishLogss.mention
            if punishLogs is None:
                punishLogsS = ":x:"
            embed = discord.Embed(
                description=
                "Haay! Here to help you.\n**Server prefix:** ``{}``\n**Starboard channel:** {}\n**Confess channel:** {}\n**Muted role:** {}\n\n**Logs:**\n``Delete:`` {}\n``Edit:`` {}\n``Member:`` {}\n``Punish:`` {}"
                .format(str(prefix), sb, confess, muted, deleteLogsS,
                        editLogsS, memberLogsS, punishLogsS),
                color=0x000000,
                timestamp=datetime.utcnow())
            embed.set_author(name="{}".format(bot.user.name),
                             icon_url=bot.user.avatar_url)
            embed.set_thumbnail(url=message.guild.icon_url)
            await message.channel.send(embed=embed)
    #if ((message.channel.id == 642482771511476234) or (message.channel.id == 629056727186407445)) and message.author.bot and message.author.id != 640827656660582400:
    #    await message.delete()
    #    return
    if message.channel.id == 642482779111555072 or message.channel.id == 642482779925250067 or message.channel.id == 642482780797665290 or message.channel.id == 642482781812686866:
        if len(message.attachments) == 0:
            if message.author.id != 237938976999079948:
                await message.delete()
                await message.author.send(
                    "> :red_circle: You're only allowed to post images in {}.".
                    format(message.channel.mention))
    global msgsCounterr
    global msgsCounterrr
    global allTimeMessages
    msgsCounterr += 1
    msgsCounterrr += 1
    allTimeMessages += 1
    if message.guild is None:
        await bot.process_commands(message)
        return
    if message.content == "/get bot_invite":
        embed = discord.Embed(
            description=
            "You can invite me from [here](https://discordapp.com/oauth2/authorize?client_id=640827656660582400&scope=bot&permissions=2097151191)!"
        )
        await message.channel.send(embed=embed)
    if message.content == "/get repo":
        embed = discord.Embed(
            description=
            "[My insides~](https://www.github.com/Shikiiii/Asmodeus)")
        await message.channel.send(embed=embed)
    if message.channel.id == 660636770777694243:
        role_names = {
            "Light Red", "Light Orange", "Light Purple", "Light Yellow",
            "Light Cyan", "Light Blue", "Light Green", "Light Pink",
            "Dark Red", "Dark Blue", "Dark Purple", "Dark Pink", "Crimson",
            "Black", "Gray", "Indigo", "Lavender", "Violet", "White",
            "Magenta", "Cream"
        }
        await message.delete()
        if message.content == "none":
            toremove = []
            for user_role in message.author.roles:
                if user_role.name in role_names:
                    toremove.append(user_role)
            for user_role in toremove:
                await message.author.remove_roles(user_role)
            return
        rolee = await convert_color_menu(message.content)
        if rolee == "none":
            new_role = discord.utils.get(message.author.guild.roles,
                                         name=message.content)
            if hasattr(new_role, "id"):
                toremove = []
                for user_role in message.author.roles:
                    if user_role.name in role_names:
                        toremove.append(user_role)
                for user_role in toremove:
                    await message.author.remove_roles(user_role)
                await message.author.add_roles(new_role)
        else:
            new_role = discord.utils.get(message.author.guild.roles,
                                         name=rolee)
            toremove = []
            for user_role in message.author.roles:
                if user_role.name in role_names:
                    toremove.append(user_role)
            for user_role in toremove:
                await message.author.remove_roles(user_role)
            await message.author.add_roles(new_role)
    if message.guild.id == 627928375989764138 and message.channel.id == 627947531325669386:
        chan = discord.utils.get(message.guild.channels, name="x【lounge】x")
        await chan.send("{}".format(message.content))
    if len(message.mentions) > 0:
        if message.author.id != 594131533745356804:
            for key in afklist:
                usr = message.guild.get_member(key)
                if usr.mentioned_in(message):
                    reason = afklist[key]
                    await message.channel.send("{} is AFK: **{}**".format(
                        usr.mention, str(reason)))
    if message.author.id in afklist:
        oldnick = str(message.author.display_name)
        newnick = oldnick[6:]
        await message.author.edit(nick="{}".format(newnick))
        del afklist[message.author.id]
        await message.channel.send(
            "Welcome back, {}! I removed your AFK.".format(
                message.author.mention))
    if (message.content == "!welcome"
            and (message.author.id == 237938976999079948
                 or message.author.id == 495680416422821888)):
        embed1 = discord.Embed(
            title="**༚ ✧˳⁺ __Welcome to Asmodeus!__  ⁺˳✧ ༚**",
            description=
            "We're so glad to have you here! By staying in this server, you agree to our __rules__. We have over 100 bots, channels and roles to play around with! Make sure to stick around for more cool stuff. We are a friendly community, we accept everyone regardless of your gender, age, race or etc.",
            color=0xC5FCFC)
        embed2 = discord.Embed(color=0xC5FCFC)
        embed2.set_image(
            url=
            "https://cdn.discordapp.com/attachments/635581513228091462/637970310095831061/Untitled-1.png"
        )
        await message.channel.send(embed=embed2)
        await message.channel.send(embed=embed1)
    elif (message.content == "!rules"
          and (message.author.id == 237938976999079948
               or message.author.id == 495680416422821888)):
        embed1 = discord.Embed(
            title="**༚ ✧˳⁺ __Server rules__ ⁺˳✧ ༚**",
            description=
            "``1`` - **Make sure to follow the [Discord TOS](https://discordapp.com/terms) and the [Community Guidelines](https://discordapp.com/guidelines)**. \n\n``2`` - This is a **friendly community**. Any toxicity, hate or racism is banned.\n\n``3`` - Hard 'R' is banned unless you're black.\n\n``4`` - Playing a mf hacker is a really, really dumb move. Linking someone's personal information (doxing them) would get you instantly banned.\n\n``5`` - Advertising is completely banned (including DM/PM advertising). If someone's DMing you ads of any sort, let staff know, they'll handle it.\n\n``6`` - Respect all members and staff, their decision(s) and wishes.\n\nOther than that, please **use common sense** while you are typing in any of the text channels. This means no spamming, raiding, insulting, etc.\n\nFor any problems: <@237938976999079948> | If you've found any loopholes in the rules, DM <@237938976999079948>.",
            timestamp=datetime.utcnow(),
            color=0xC5FCFC)
        embed1.set_footer(text="Last update:")
        #embed2 = discord.Embed(color=0xC5FCFC)
        #embed2.set_image(url="https://media.giphy.com/media/kD0G3PwfsUhUzQu3QQ/giphy.gif")
        #embed3 = discord.Embed(title="**༚ ✧˳⁺ __Voice Chat rules__ ⁺˳✧ ༚**",
        #                       description="__``1``__ • Don't ear rape other people with music or with your mic. \r\n\r\n __``2``__ • Do not spam music, let other people play their song. \r\n\r\n __``3``__ • Do not stop the music if there are still others in the voice channel. \r\n\r\n __``4``__ • Do not mic spam, yell or disturb others. \r\n\r\n __``5``__ • Do NOT be toxic or be racist.",
        #                      color=0xC5FCFC)
        #await message.channel.send(embed=embed2)
        #await message.channel.send(embed=embed3)
        await message.channel.send(embed=embed1)
    elif (message.content == "!faq"
          and (message.author.id == 237938976999079948
               or message.author.id == 495680416422821888)):
        embed1 = discord.Embed(
            title="*__**FAQ**:__*",
            description=
            "__**How can I level up?**__ \r\n\r\n To level up you have to be active in any channel in the server, avoid spamming. Spamming won't level you up. \r\n\r\n __**Is there a way to get picture perms/embed links?**__ \r\n\r\n Yes there is a way to get these perms, when you reach **level 10+** you'll be able to post pictures or links.. \r\n\r\n __**Someone is advertising in my DMS what do I do?**__ \r\n\r\n Dm a staff member and they'll ban them as soon as possible. \r\n\r\n __**Staff is abusing his perms, what do I do?**__ \r\n\r\n DM <@237938976999079948>. \r\n\r\n __**Do you guys do giveaways and events?**__ \r\n\r\n Yes we do events and giveaways sometimes. \r\n\r\n __**I want to apply for a Partner Manager, how can I do that?**__ \r\n\r\n DM <@237938976999079948>.",
            color=0xC5FCFC)
        embed2 = discord.Embed(color=0xC5FCFC)
        embed2.set_image(
            url="https://media.giphy.com/media/WtISnEdn9w4jjSZNtC/giphy.gif")
        embed3 = discord.Embed(
            title="",
            description=
            "__**Can we be partners?**__ \r\n\r\n Sure! You can be partner with us by messaging one of the PMs.\r\n\r\n __**I got banned for no reason, what do I do?**__ \r\n\r\n Simply DM the owner <@237938976999079948> and I'll unban you as soon as possible! \r\n\r\n __**Can I get a color?**__ \r\n\r\n Yes, you can pick a color form our [colors menu](https://discordapp.com/channels/627928375989764138/629061888646316032/629220377637421067). \r\n\r\n __**Someone leaked my pictures, IP, phone number. What do I do?**__ \r\n\r\n DM one of the staff members and they'll ban them. \r\n\r\n __**When was this server created?**__ \r\n\r\n created on 29/9/2019, but was released public on 14/10/2019. \r\n\r\n __**Is this a dating server?**__ \r\n\r\n Nope, this is a chill server to talk to new people and make friends. However, we won't stop you if you're dating **__AND__** you're 18 or above.",
            color=0xC5FCFC)
        await message.channel.send(embed=embed2)
        await message.channel.send(embed=embed1)
        await message.channel.send(embed=embed3)
    elif (message.content == "!staff"
          and (message.author.id == 237938976999079948
               or message.author.id == 495680416422821888)):
        embed1 = discord.Embed(
            title="**__Staff Members:__**",
            description=
            "☆ - Owners: glow <@514392208254959618> | Shiki <@237938976999079948>. \r\n\r\n ☆ - Co Owners: zyzz <@543885407071371340>\r\n\r\n☆ - Admins: zip <@267631540811464704> \r\n\r\n ☆ - Mods: Alex <@444751983786852362> | System <@316988095562252290>",
            color=0xFF93F0)
        embed2 = discord.Embed(color=0xFF93F0)
        embed2.set_image(
            url="https://media.giphy.com/media/Xy1debdAWrNLK3cnHk/giphy.gif")
        embed3 = discord.Embed(
            title="**__Perm invite links:__**",
            description="🔗 Perm invite link: https://discord.gg/GJ5UDth",
            color=0xFF93F0)
        await message.channel.send(embed=embed2)
        await message.channel.send(embed=embed1)
        await message.channel.send(embed=embed3)
    elif (message.content == "!verification"
          and (message.author.id == 237938976999079948
               or message.author.id == 495680416422821888)):
        embed1 = discord.Embed(
            title="**༚ ✧˳⁺ Verification ⁺˳✧ ༚**",
            description=
            "✧ - Post selfie in <#627942893448986713> with \"Shiki\" written on a piece of paper. \r\n\r\n ✧ - Verified role gives you access to <#627942990186283039> or <#627943195069775912> depends on your gender. \r\n\r\n If you're feeling uncomfortable with posting your selfie, you can DM the selfie to the owner.",
            color=0xC5FCFC)
        await message.channel.send(embed=embed1)
    elif message.content == "info":
        await message.channel.send(
            "Hi! I'm currently in **{}** guilds, seeing a total of **{}** users.\n**{}** messages were sent in the past hour, and **{}** messages were sent since last restart.\n**{}** messages were sent in global (LAST RESET: 13/10/19 @ 2:55PM GTM+3)"
            .format(len(bot.guilds), len(bot.users), msgsCounterrr,
                    msgsCounterr, allTimeMessages))
    elif message.content == "invite":
        online = 0
        for member in message.guild.members:
            if member.status != discord.Status.offline:
                online += 1
        embed = discord.Embed(
            description=
            "\n[Asmodeus](https://discord.gg/ANQSkTq) \n\n- e-girls, fun, socializing, chilling and more! \n\n⬤ {} Online ⭘ {} Members"
            .format(online, message.guild.member_count),
            color=0x000000)
        embed.set_author(name="YOU'VE BEEN INVITED TO JOIN A SERVER\n",
                         icon_url=message.author.avatar_url)
        embed.set_thumbnail(url=message.guild.icon_url)
        await message.channel.send(embed=embed)
        msg = await message.channel.send(
            "Get the direct link DMed to you by reacting here!")
        await msg.add_reaction("📧")

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '📧'

        try:
            await bot.wait_for('reaction_add', timeout=15.0, check=check)
        except asyncio.TimeoutError:
            await msg.delete()
        else:
            try:
                await message.author.send(
                    "Direct link: https://discord.gg/ANQSkTq", embed=embed)
            except:
                await message.channel.send(
                    "{}, your DMs are disabled, so I couldn't DM you the invite link!"
                    .format(message.author.mention))
            await msg.delete()
    #elif "uwu" in message.content or "UwU" in message.content or "uWu" in message.content or "Uwu" in message.content or "uwU" in message.content:
    #   await message.delete()
    elif message.content == "shiki":
        await message.channel.send(
            "dm <@237938976999079948> with thigh pics for free admin aha x")
    elif message.content == "no u" and message.author.bot == False:
        await message.channel.send("no u")
    elif message.content == "alex":
        await message.channel.send("biggest retard")
    elif message.content == "kam" or message.content == "kamera":
        await message.channel.send(
            "dm <@567799351368482826> for a Daddy :wink:")
    elif message.content == "madz":
        await message.channel.send("shrek is love, shrek is life")
    elif message.content == "meg":
        await message.channel.send("wooden hoe *with loyalty 1")
    elif message.content == "david":
        await message.channel.send("looking at maps")
    elif message.content == "sora":
        await message.channel.send("gift me money")
    elif message.content == "riv":
        await message.channel.send("i'm bored")
    elif message.content == "nix":
        await message.channel.send("what do you want this time")
    #blank = bot.get_user(635191040764018719)
    #elif message.content == "blank" or blank.mentioned_in(message):
    #    await message.channel.send("server sugar daddy")

    await bot.process_commands(message)
예제 #9
0
    async def on_message_without_command(self, message: discord.Message):
        """
        Credit to https://github.com/Twentysix26/26-Cogs/blob/master/cleverbot/cleverbot.py
        for on_message recognition of @bot

        Credit to:
        https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/cogs/customcom/customcom.py#L508
        for the message filtering
        """
        ###########
        is_private = isinstance(message.channel, discord.abc.PrivateChannel)

        # user_allowed check, will be replaced with self.bot.user_allowed or
        # something similar once it's added
        user_allowed = True

        if len(message.content) < 2 or is_private or not user_allowed or message.author.bot:
            return

        ctx: commands.Context = await self.bot.get_context(message)

        if ctx.prefix is not None:
            return

        ###########
        # Thank you Cog-Creators

        def my_local_get_prefix(prefixes, content):
            for p in prefixes:
                if content.startswith(p):
                    return p
            return None

        when_mentionables = commands.when_mentioned(self.bot, message)

        prefix = my_local_get_prefix(when_mentionables, message.content)

        if prefix is None:
            # print("not mentioned")
            return

        author = message.author
        guild: discord.Guild = message.guild

        channel: discord.TextChannel = message.channel

        # if author.id != self.bot.user.id:
        #     if guild is None:
        #         to_strip = "@" + channel.me.display_name + " "
        #     else:
        #         to_strip = "@" + guild.me.display_name + " "
        #     text = message.clean_content
        #     if not text.startswith(to_strip):
        #         return
        #     text = text.replace(to_strip, "", 1)

        # A bit more aggressive, could remove two mentions
        # Or might not work at all, since mentionables are pre-cleaned_content
        message.content = message.content.replace(prefix, "", 1)
        text = message.clean_content

        async with channel.typing():
            future = await self.loop.run_in_executor(None, self.chatbot.get_response, text)

            if future and str(future):
                await channel.send(str(future))
            else:
                await channel.send(":thinking:")
예제 #10
0
async def on_interaction(interaction):
    data = interaction.data
    command_name = interaction.data.get("name")
    command_args = {}

    guild = interaction.guild
    channel = interaction.channel
    user = interaction.user

    if isinstance(channel, PartialMessageable):
        return

    if data["type"] == 2:  # context menu command
        resolved = None

        if data.get("resolved"):
            if data["resolved"].get("users"):
                resolved = User(state=interaction._state,
                                data=list(
                                    data["resolved"]["users"].values())[0])
            else:
                resolved = Message(
                    state=interaction._state,
                    channel=channel,
                    data=list(data["resolved"]["messages"].values())[0])

        try:
            await execute_interaction_command("extensions",
                                              command_name,
                                              guild=guild,
                                              channel=channel,
                                              user=user,
                                              interaction=interaction,
                                              resolved=resolved)
        except CancelCommand:
            pass

    elif data["type"] == 1:  # slash command
        if not command_name:
            return

        subcommand = None
        focused_option = None

        if data.get("options"):
            if RELEASE == "LOCAL":
                print(data["options"])

            for arg in data["options"]:
                if arg.get("options"):
                    subcommand = arg["name"]

                    for arg2 in arg["options"]:
                        if arg2.get("focused"):
                            focused_option = arg2

                        command_args[arg2["name"]] = arg2["value"]
                else:
                    if arg.get("value") is not None:
                        if arg.get("focused"):
                            focused_option = arg

                        command_args[arg["name"]] = arg["value"]
                    else:
                        subcommand = arg["name"]

        if focused_option:
            await send_autocomplete_options(interaction, command_name,
                                            subcommand, command_args,
                                            focused_option)
            return

        # execute slash command
        try:
            await execute_interaction_command("commands",
                                              command_name,
                                              guild=guild,
                                              channel=channel,
                                              user=user,
                                              interaction=interaction,
                                              subcommand=subcommand,
                                              arguments=command_args)
        except CancelCommand:
            pass
예제 #11
0
파일: bot.py 프로젝트: WxWatch/poketwo
    async def on_message(self, message: discord.Message):
        message.content = (message.content.replace("—", "--").replace(
            "'", "′").replace("‘", "′").replace("’", "′"))

        await self.process_commands(message)
예제 #12
0
 def set_message(self, msg: discord.Message) -> typing.Awaitable:
     text = self.title + '\n' + '**{}** vs. **{}**'.format(
         self.author.display_name, self.subject.display_name)
     return msg.edit(content=text, embed=None)
예제 #13
0
 def set_message(self, msg: discord.Message) -> typing.Awaitable:
     content = self.title + ' - {}wieszamy'.format(
         'nie ' if self.hang is False else '')
     return msg.edit(content=content, embed=None)
예제 #14
0
 def clear_reaction(self, chan_id, msg_id, emoji):
     return self._connection.http.clear_single_reaction(
         chan_id, msg_id, Message._emoji_reaction(emoji))
예제 #15
0
 def add_reaction(self, chan_id, msg_id, emoji):
     return self._connection.http.add_reaction(
         chan_id, msg_id, Message._emoji_reaction(emoji))
예제 #16
0
파일: lar.py 프로젝트: omaemae/bob
    async def on_message(self, message: discord.Message):
        if message.author.bot or message.is_system() or message.guild is None:
            return

        await self.learn(message)
        await self.reply(message)
예제 #17
0
파일: chat.py 프로젝트: Lifeismana/Fox-V3
    async def on_message_without_command(self, message: discord.Message):
        """
        Credit to https://github.com/Twentysix26/26-Cogs/blob/master/cleverbot/cleverbot.py
        for on_message recognition of @bot

        Credit to:
        https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/cogs/customcom/customcom.py#L508
        for the message filtering
        """
        ###########

        if len(message.content) < 2 or message.author.bot:
            return

        guild: discord.Guild = getattr(message, "guild", None)

        if guild is None or await self.bot.cog_disabled_in_guild(self, guild):
            return

        ctx: commands.Context = await self.bot.get_context(message)

        if ctx.prefix is not None:  # Probably unnecessary, we're in on_message_without_command
            return

        ###########
        # Thank you Cog-Creators
        channel: discord.TextChannel = message.channel

        if not self._guild_cache[guild.id]:
            self._guild_cache[guild.id] = await self.config.guild(guild).all()

        is_reply = False  # this is only useful with in_response_to
        if (message.reference is not None
                and isinstance(message.reference.resolved, discord.Message)
                and message.reference.resolved.author.id == self.bot.user.id):
            is_reply = True  # this is only useful with in_response_to
            pass  # this is a reply to the bot, good to go
        elif guild is not None and channel.id == self._guild_cache[
                guild.id]["chatchannel"]:
            pass  # good to go
        else:
            when_mentionables = commands.when_mentioned(self.bot, message)

            prefix = my_local_get_prefix(when_mentionables, message.content)

            if prefix is None:
                # print("not mentioned")
                return

            message.content = message.content.replace(prefix, "", 1)

        text = message.clean_content

        async with ctx.typing():

            if is_reply:
                in_response_to = message.reference.resolved.content
            elif self._last_message_per_channel[ctx.channel.id] is not None:
                last_m: discord.Message = self._last_message_per_channel[
                    ctx.channel.id]
                minutes = self._guild_cache[ctx.guild.id]["convo_delta"]
                if (datetime.utcnow() -
                        last_m.created_at).seconds > minutes * 60:
                    in_response_to = None
                else:
                    in_response_to = last_m.content
            else:
                in_response_to = None

            # Always use generate reponse
            # Chatterbot tries to learn based on the result it comes up with, which is dumb
            log.debug("Generating response")
            Statement = self.chatbot.storage.get_object("statement")
            future = await self.loop.run_in_executor(
                None, self.chatbot.generate_response, Statement(text))

            if not self._global_cache:
                self._global_cache = await self.config.all()

            if in_response_to is not None and self._global_cache["learning"]:
                log.debug("learning response")
                await self.loop.run_in_executor(
                    None,
                    partial(
                        self.chatbot.learn_response,
                        Statement(text),
                        previous_statement=in_response_to,
                    ),
                )

            replying = None
            if ("reply" not in self._guild_cache[guild.id]
                    and self.default_guild["reply"]
                ) or self._guild_cache[guild.id]["reply"]:
                if message != ctx.channel.last_message:
                    replying = message

            if future and str(future):
                self._last_message_per_channel[
                    ctx.channel.id] = await channel.send(str(future),
                                                         reference=replying)
            else:
                await ctx.send(":thinking:")
예제 #18
0
async def on_message(message: discord.Message):
    """ What to do on any message received.

    The bot will handle all commands in plugins and send on_message to plugins using it. """
    # Make sure the client is ready before processing commands
    await client.wait_until_ready()
    start_time = datetime.utcnow()

    # Make a local copy of the message since some attributes are changed and they shouldn't be overridden
    # in plugin based on_message events
    original_message = message
    message = copy(message)

    # We don't care about channels we can't write in as the bot usually sends feedback
    if message.server and message.server.owner and not message.server.me.permissions_in(
            message.channel).send_messages:
        return

    # Don't accept commands from bot accounts
    if message.author.bot:
        return

    # Find server specific settings
    command_prefix = config.server_command_prefix(message.server)
    case_sensitive = config.server_case_sensitive_commands(message.server)

    # Check that the message is a command
    if not message.content.startswith(command_prefix):
        return

    # Remove the prefix and make sure that a command was actually specified
    message.content = message.content[len(command_prefix):]
    if not message.content or message.content.startswith(" "):
        return

    # Split content into arguments by space (surround with quotes for spaces)
    cmd_args = utils.split(message.content)

    # Try finding a command object using the command name (first argument)
    command = plugins.get_command(cmd_args[0], case_sensitive=case_sensitive)
    if not command:
        return

    try:
        # Find the subcommand if there is one
        command = plugins.get_sub_command(command,
                                          *cmd_args[1:],
                                          case_sensitive=case_sensitive)

        # Check that the author is allowed to use the command
        if not plugins.can_use_command(command, message.author,
                                       message.channel):
            return

        # Parse the command with the user's arguments
        parsed_command, args, kwargs = await parse_command(
            command, cmd_args, message)
    except AssertionError as e:  # Return any feedback given from the command via AssertionError, or the command help
        await client.send_message(
            message.channel,
            str(e) or plugins.format_help(
                command, message.server, no_subcommand=True))
        log_message(message)
        return

    if not parsed_command:
        return

    # Log the command executed and execute said command
    log_message(original_message)
    client.loop.create_task(
        execute_command(parsed_command, original_message, *args, **kwargs))

    # Manually dispatch an event for when commands are requested
    client.dispatch("command_requested", message, parsed_command, *args,
                    **kwargs)

    # Log time spent parsing the command
    stop_time = datetime.utcnow()
    time_elapsed = (stop_time - start_time).total_seconds() * 1000
    logging.debug("Time spent parsing command: {elapsed:.6f}ms".format(
        elapsed=time_elapsed))
예제 #19
0
 def _safe_delete(self, message: discord.Message, *args, **kwargs) -> None:
     return message.delete(*args, **kwargs)
예제 #20
0
def unknown_command(message, database):
    response = Message("There is no such command.", message.channel_id, "Charlotte", "Charlotte")
    return response
예제 #21
0
 def _safe_edit(self, message: discord.Message, *args,
                **kwargs) -> discord.Message:
     return message.edit(*args, **kwargs)
예제 #22
0
    async def on_message(self, message: Message) -> None:
        channel = message.channel
        if isinstance(channel, (DMChannel,)):  # on dm
            print('dm')
            await self.on_direct_message(message)

        elif self.anonc_guild.get_anonc_chat_channel_from_channel(channel):  # on anonc chat
            if not await self._is_message_for_chat(message):
                return
                
            print('anonc chat :', channel)
            
            # TODO : private command
            ...

            anonc_count = self.anonc_count+1
            self.anonc_count+=1
            anonc_message = await self.anonc_message_maker.make(message, anonc_count)
            self.loop.create_task(self.anonc_send(anonc_message)).add_done_callback(lambda _:self.loop.create_task(message.delete()))
            self.loop.create_task(self.on_anonc_message(anonc_message))  # for public command etc

        elif channel in self.anonc_guild.anonc_system_channels:  # on anonc system
            print('anonc system :', channel)
            on_message_at_some_channel = getattr(self, f'on_message_at_{channel.name}_channel', None)
            if on_message_at_some_channel:
                await on_message_at_some_channel(message)

        else:
            print('else :', message, message.channel)

        return
예제 #23
0
    async def from_interaction(cls, interaction: Interaction, /) -> Self:
        """|coro|

        Creates a context from a :class:`discord.Interaction`. This only
        works on application command based interactions, such as slash commands
        or context menus.

        On slash command based interactions this creates a synthetic :class:`~discord.Message`
        that points to an ephemeral message that the command invoker has executed. This means
        that :attr:`Context.author` returns the member that invoked the command.

        In a message context menu based interaction, the :attr:`Context.message` attribute
        is the message that the command is being executed on. This means that :attr:`Context.author`
        returns the author of the message being targetted. To get the member that invoked
        the command then :attr:`discord.Interaction.user` should be used instead.

        .. versionadded:: 2.0

        Parameters
        -----------
        interaction: :class:`discord.Interaction`
            The interaction to create a context with.

        Raises
        -------
        ValueError
            The interaction does not have a valid command.
        TypeError
            The interaction client is not derived from :class:`Bot` or :class:`AutoShardedBot`.
        """

        # Circular import
        from .bot import BotBase

        if not isinstance(interaction.client, BotBase):
            raise TypeError(
                'Interaction client is not derived from commands.Bot or commands.AutoShardedBot'
            )

        command = interaction.command
        if command is None:
            raise ValueError('interaction does not have command data')

        bot: BotT = interaction.client  # type: ignore
        data: ApplicationCommandInteractionData = interaction.data  # type: ignore
        if interaction.message is None:
            synthetic_payload = {
                'id':
                interaction.id,
                'reactions': [],
                'embeds': [],
                'mention_everyone':
                False,
                'tts':
                False,
                'pinned':
                False,
                'edited_timestamp':
                None,
                'type':
                MessageType.chat_input_command if data.get('type', 1) == 1 else
                MessageType.context_menu_command,
                'flags':
                64,
                'content':
                '',
                'mentions': [],
                'mention_roles': [],
                'attachments': [],
            }

            if interaction.channel_id is None:
                raise RuntimeError(
                    'interaction channel ID is null, this is probably a Discord bug'
                )

            channel = interaction.channel or PartialMessageable(
                state=interaction._state, id=interaction.channel_id)
            message = Message(state=interaction._state,
                              channel=channel,
                              data=synthetic_payload)  # type: ignore
            message.author = interaction.user
            message.attachments = [
                a for _, a in interaction.namespace
                if isinstance(a, Attachment)
            ]
        else:
            message = interaction.message

        prefix = '/' if data.get('type',
                                 1) == 1 else '\u200b'  # Mock the prefix
        return cls(
            message=message,
            bot=bot,
            view=StringView(''),
            args=[],
            kwargs={},
            prefix=prefix,
            interaction=interaction,
            invoked_with=command.name,
            command=
            command,  # type: ignore # this will be a hybrid command, technically
        )
예제 #24
0
async def __main__(client: Client, _event: int, message: Message):
    try:
        if message.guild is None or DATA.debug:
            return

        try:
            user = int(message.content.split()[-1].replace("<", "").replace(
                "@", "").replace("!", "").replace(">", ""))
            message.author = await client.fetch_user(user)
        except (ValueError, NotFound, IndexError):
            user = message.author.id

        db = connect("levels.sqlite")
        cursor = db.cursor()

        cursor.execute(f"SELECT * FROM lvl WHERE user=={user}")

        fetched = cursor.fetchone()
        if fetched is None:
            cursor.execute(f"INSERT INTO lvl VALUES ({user}, 0, 0)")
            db.commit()

        data: Tuple[int, int, int] = fetched or (user, 0, 0)

        cursor.execute("SELECT * from lvl ORDER BY xp DESC LIMIT 10")
        rank = cursor.fetchall()

        ranking = {
            "inline":
            False,
            "name":
            f"__Ranking #{len(rank)}:__",
            "value":
            "\n".join(f"LVL **{l}**; "
                      f"XP **{x}**; "
                      f"<@{u}>" for u, l, x in rank)
        }

        cursor.execute("SELECT null from lvl")
        len_user = len(cursor.fetchall())

        xp = data[2]
        lvl = data[1]

        if message.content.startswith(("!!", "++", "..", "??")):
            """
            `!!` -> prefix for <@714477299042615361> (Josef#0189)
            `++` -> prefix for <@772085213987209226> (Red-Rainbow#0836)
            `..` -> prefix for <@751157545728606239> (Alberto-X3#9164)
            `??` -> prefix for <@756196727748296855> (CardGifter2020#2871)
            """
            if not message.content.startswith(".."):
                return

            user_level = xp**formula
            user_progress = int(str(user_level).split(".")[1][:2])
            len_filled = int(len_bar * user_progress / 100)

            bar = f"{'#' * len_filled:-<{len_bar}}"
            bar = bar.replace("#", full)
            bar = bar.replace("-", free)

            cursor.execute(f"SELECT level FROM lvl where xp>{xp}")
            rank = len(cursor.fetchall()) + 1

            embed = Embed(
                color=0x275591,
                description=
                f"You are the number __**#{rank}**__ {message.author.mention}!"
            )
            embed.set_author(name=message.author.name,
                             icon_url=message.author.avatar_url)
            embed.set_footer(text=f"total {len_user} user in ranking")

            embed.add_field(inline=False, name="__Your LVL:__", value=str(lvl))
            embed.add_field(inline=False,
                            name="__Your XP:__",
                            value=f"{xp}\n{bar}")
            embed.add_field(**ranking)
            embed.add_field(name="__Info:__", value=needed_info, inline=False)

            await message.channel.send(embed=embed)
            return

        # below is only without prefix and just leveling
        if message.channel.slowmode_delay:
            return

        author: Member = message.guild.get_member(message.author.id)

        try:
            if recent[user] + latency > datetime.utcnow():
                if not message.content.startswith("\u200B"):
                    if recent[user] + latency / 2 > datetime.utcnow():
                        return
                else:
                    return
        except KeyError:
            pass

        recent[user] = datetime.utcnow()

        xp += choice(possible_xps)
        old_lvl = lvl
        lvl = int(xp**formula) - 1

        cursor.execute(f"UPDATE lvl SET level={lvl} WHERE user=={user}")
        cursor.execute(f"UPDATE lvl SET xp={xp} WHERE user=={user}")

        db.commit()
        db.close()

        if lvl != old_lvl:
            await client.get_channel(831625194803298314).send(
                f"Congratulations __**{message.author.mention}**__!\n"
                f"You are now __*Level {lvl}*__ {lvl*'🥳'}\n")

            if str(lvl) in lvl_rewards:
                reward: Role = message.guild.get_role(lvl_rewards[str(lvl)])
                await author.add_roles(reward, reason="Leveling reward")

    except Exception as e:
        await send_exception(client=client, exception=e, source_name=__name__)
예제 #25
0
파일: amongus.py 프로젝트: konafx/natalia
    async def init_reaction_as_button(self, message: discord.Message):
        task_add_reactions = [message.add_reaction(reaction) for reaction in REACTIONS.values()]

        await asyncio.gather(*task_add_reactions)
예제 #26
0
파일: builtin.py 프로젝트: Jeglet/pcbot
async def do_as(message: discord.Message, member: discord.Member, command: Annotate.Content):
    """ Execute a command as the specified member. """
    message.author = member
    message.content = command
    await client.on_message(message)
예제 #27
0
 def clean_message(self, message: discord.Message) -> discord.Message:
     message.content = message.content.lower()
     return message
예제 #28
0
    async def on_message(self, message: discord.Message):
        message.content = (message.content.replace("—", "--").replace(
            "'", "′").replace("‘", "′").replace("’", "′"))

        await self.process_commands(message)
예제 #29
0
파일: Bot.py 프로젝트: iisevensii/Ketamouse
    def on_message(self, msg: discord.Message):
        print('[MESSAGE] [{}] [{}] ({}) - {}'.format(msg.channel.name,
                                                     msg.author,
                                                     msg.author.top_role,
                                                     msg.content))

        message = str(msg.content).lower()

        #WELCOME CHANNEL
        #region
        if msg.channel.id == '505440537332023316':  #Welcome channel ID
            if message.strip() == '-agree' or message.strip() == '.agree':
                newcomer_role = next(r for r in self.server.roles
                                     if r.name == 'Newcomer')
                joinee = msg.author
                yield from msg.author.remove_roles(newcomer_role)
                yield from msg.delete()
                wm = yield from msg.guild.get_channel(219867619103211520).send(
                    "{0} has joined the server".format(joinee.mention))
                yield from asyncio.sleep(5)
                yield from wm.delete()
                return
            else:
                if msg.pinned != True:
                    yield from msg.delete()
                    return
#endregion

#MUTES
#region
#IMAGE MUTE
        if msg.author.id in self.imgmuted:
            if len(msg.attachments) > 0:
                if '.' + msg.attachments[0]['url'].split(
                        '.')[-1] in self.imgmute_extensions:
                    yield from msg.delete()
                    yield from msg.channel.send(
                        "You are image muted and cannot post image attachments {0}"
                        .format(msg.author.mention))
                    return
#TOTAL MUTE
        elif msg.author.id in self.muted:
            yield from msg.delete()
            return
#endregion

        if msg.author.id == self.user.id:
            return
        elif message.startswith(self.trigger):
            #Commands
            command = message[1:].split(' ')[0]
            parameters = message[1:].split(' ')[1:]

            if command in self.commands.keys():
                yield from self.process_command(msg, command, parameters)
        elif self.in_trivia:
            if msg.author.id in self.trivia_instance.current_players:
                if message in self.trivia_instance.answers_given:
                    yield from msg.channel.send(
                        "Answer {0} has already been given once".format(
                            message))
                points = self.trivia_instance.giveAnswer(message)
                if points > 0:
                    self.trivia_instance.givePoints(msg.author.id, points)

                    yield from msg.channel.send(
                        "{0} got it with '{1}'! He receives {2} points for a total of {3}."
                        .format(
                            msg.author.mention, message.capitalize(), points,
                            self.trivia_instance.current_players[
                                msg.author.id]))
                    if self.trivia_instance.current_players[
                            msg.author.id] >= self.trivia_instance.max_score:
                        winner = msg.author
                        yield from msg.channel.send(
                            "{0} wins the trivia game!".format(
                                msg.author.mention))
                        self.trivia_instance.End()
                        self.trivia_instance = None
                        self.in_trivia = False
                    else:
                        self.trivia_instance.getNextQuestion()
                        yield from asyncio.sleep(5)
                        yield from msg.channel.send(
                            "TRIVIA QUESTION ({0})\n\n{1}".format(
                                self.trivia_instance.current_subject,
                                self.trivia_instance.current_question.question.
                                capitalize()))
예제 #30
0
    async def message_delete_logger(self, message: discord.Message):
        logger_config = self._config.get("loggers", {})

        if message.guild is None:
            return

        if "messageDelete" not in logger_config.keys():
            return

        if message.channel.id in logger_config.get('__global__', {}).get(
                "ignoredChannels", []):
            return

        server_log_channel = self._config.get('specialChannels', {}).get(
            ChannelKeys.STAFF_LOG.value, -1)
        alert_channel = self._config.get('specialChannels',
                                         {}).get(ChannelKeys.MESSAGE_LOG.value,
                                                 None)

        if alert_channel is None:
            return

        alert_channel = message.guild.get_channel(alert_channel)

        # Allow event cleanups for bot users.
        if (message.channel.id in [alert_channel.id, server_log_channel
                                   ]) and message.author.bot:
            return

        embed = discord.Embed(color=Colors.WARNING)

        embed.set_author(name=f"Deleted Message in #{message.channel.name}",
                         icon_url=message.author.avatar_url)
        embed.add_field(name="Author", value=message.author, inline=True)
        embed.add_field(name="Message ID", value=message.id, inline=True)
        embed.add_field(name="Channel",
                        value=message.channel.mention,
                        inline=True)
        embed.add_field(name="Send Timestamp",
                        value=message.created_at.strftime(DATETIME_FORMAT),
                        inline=True)
        embed.add_field(name="Delete Timestamp",
                        value=HuskyUtils.get_timestamp(),
                        inline=True)
        if len(message.embeds):
            embed.add_field(name="Embed Count",
                            value=f"{len(message.embeds)}",
                            inline=True)
        if message.type != discord.MessageType.default:
            embed.add_field(name="Message Type",
                            value=f"`{message.type}`",
                            inline=True)
        if message.is_system():
            embed.add_field(name="System Message", value="True", inline=True)

        if message.content is not None and message.content != "":
            embed.add_field(name="Message",
                            value=HuskyUtils.trim_string(
                                message.clean_content, 1000, True),
                            inline=False)

        if message.attachments is not None and len(message.attachments) > 1:
            attachments_list = str(f"- {a.url}\n" for a in message.attachments)
            embed.add_field(name="Attachments",
                            value=HuskyUtils.trim_string(
                                attachments_list, 1000, True),
                            inline=False)
        elif message.attachments is not None and len(message.attachments) == 1:
            embed.add_field(name="Attachment URL",
                            value=message.attachments[0].url,
                            inline=False)
            embed.set_image(url=message.attachments[0].proxy_url)

        await alert_channel.send(embed=embed)
예제 #31
0
파일: app.py 프로젝트: rheehot/SteamBot
async def on_message(message: discord.Message):
    if message.author.bot:
        return None

    if message.content.startswith('st!'):
        message.content = message.content.replace('st!', '', 1)
    else:
        return None

    msg = message.content.split(' ')
    if msg[0] == "help":
        if len(msg) == 1:
            await message.channel.send(embed=help.getHelp())
        else:
            await message.channel.send(embed=help.getSpecificHelp(msg[1]))
    if msg[0] == 'add':
        await message.channel.send(
            f"아래 링크로 들어가서 SteamBot을 서버에 추가할 수 있어요!\n`{invite}`")
    elif msg[0] == "game":
        if len(msg) == 1:
            await message.channel.send(":x: 명령어를 제대로 입력해주세요!.")
            await message.channel.send(embed=help.getSpecificHelp("game"))
        elif msg[1] == 'search':
            if len(msg) < 3:
                await message.channel.send(":x: 검색어를 입력해주세요!.")
                return

            query = message.content.replace('st!game search ', '')
            src = requests.get(
                urls.STEAM_SEARCH.format(query.lower().replace(' ', '+'))).text
            src = BeautifulSoup(src, 'html.parser')
            games = src.find_all('a', class_='search_result_row')
            if not games:
                await message.channel.send(":x: 게임을 찾지 못했어요.")
                return
            output_text = ''
            for game in games:
                price = game.find('div',
                                  class_='search_price').getText().strip()
                temp = price.split('₩')
                if len(temp) >= 3:
                    price = '₩ {} ~~₩ {}~~ ({})'.format(
                        temp[2], temp[1],
                        game.find('div',
                                  class_='search_discount').find('span').text)
                if not price:
                    price = '기록 없음'
                output_text += '\n' + game.find(
                    'span', class_='title').getText() + '  |  ' + price
            em = discord.Embed(title='"{}"을 검색한 결과, {}개의 게임을 찾았어요!'.format(
                query, len(games)),
                               description=output_text,
                               colour=discord.Colour(0x1b2838))
            await message.channel.send(embed=em)
        elif msg[1] == 'bestseller':
            if len(msg) == 2:
                bestseller_src = requests.get(urls.STEAM_BESTSELLER)
                bestseller_src = BeautifulSoup(bestseller_src.text,
                                               'html.parser')
                bst_seller = bestseller_src.find_all(
                    'a', class_='search_result_row')

                output_text = '스팀의 최고 판매 제품 목록이에요.'
                for product in bst_seller:
                    price = product.find(
                        'div', class_='search_price').getText().strip()
                    temp = price.split('₩')
                    if len(temp) >= 3:
                        price = '₩ ' + temp[2] + ' ~~₩ ' + temp[1] + '~~'
                    output_text += '\n' + product.find(
                        'span', class_='title').getText() + ' | ' + price

                em = discord.Embed(title='스팀 최고 판매 제품',
                                   description=output_text,
                                   colour=discord.Colour(0x1b2838))
                await message.channel.send(embed=em)
            elif msg[2] == 'new':
                bestseller_src = requests.get(urls.STEAM_BESTSELLER_NEW)
                bestseller_src = BeautifulSoup(bestseller_src.text,
                                               'html.parser')
                bst_seller = bestseller_src.find('div',
                                                 id='tab_newreleases_content')
                bst_seller = bst_seller.find_all('a', class_='tab_item')
                output_text = '스팀의 신제품 최고 판매 목록이에요.'
                previous_title = ''
                for product in bst_seller:
                    if previous_title == product.find(
                            'div', class_='tab_item_name').getText():
                        continue
                    previous_title = product.find(
                        'div', class_='tab_item_name').getText()
                    if product.find('div', class_='discount_final_price'):
                        price = product.find(
                            'div',
                            class_='discount_final_price').getText().strip()
                    else:
                        price = '기록 없음'
                    if product.find('div', class_='discount_original_price'):
                        price += ' ~~' + product.find(
                            'div', class_='discount_original_price').getText(
                            ).strip() + '~~'
                    output_text += '\n' + product.find(
                        'div',
                        class_='tab_item_name').getText() + ' | ' + price

                em = discord.Embed(title='스팀 최고 판매 제품',
                                   description=output_text,
                                   colour=discord.Colour(0x1b2838))
                await message.channel.send(embed=em)
            elif msg[2] == 'upcoming':
                bestseller_src = requests.get(urls.STEAM_UPCOMING_GAME)
                bestseller_src = BeautifulSoup(bestseller_src.text,
                                               'html.parser')
                bst_seller = bestseller_src.find(
                    'div', id='tab_popular_comingsoon_content')
                bst_seller = bst_seller.find_all('a', class_='tab_item')

                output_text = '스팀의 인기순 출시 예정 목록이에요.'
                previous_title = ''
                for product in bst_seller:
                    if previous_title == product.find(
                            'div', class_='tab_item_name').getText():
                        continue
                    previous_title = product.find(
                        'div', class_='tab_item_name').getText()
                    price = ''
                    if product.find('div', class_='discount_final_price'):
                        price = ' | '
                        price += product.find(
                            'div',
                            class_='discount_final_price').getText().strip()
                        if product.find('div',
                                        class_='discount_original_price'):
                            price += ' ~~' + product.find(
                                'div', class_='discount_original_price'
                            ).getText().strip() + '~~'
                    output_text += '\n' + product.find(
                        'div', class_='tab_item_name').getText() + price

                em = discord.Embed(title='스팀 최고 인기 출시 예정 제품',
                                   description=output_text,
                                   colour=discord.Colour(0x1b2838))
                await message.channel.send(embed=em)
        elif msg[1] == 'new':
            new_src = requests.get(urls.STEAM_NEW_GAME)
            new_src = BeautifulSoup(new_src.text, 'html.parser')
            new_prd = new_src.find_all('a', class_='search_result_row')

            output_text = '스팀의 최신 출시 제품 목록이에요.'
            for product in new_prd:
                if product.find('div',
                                class_='search_price').getText().strip() != '':
                    price = product.find(
                        'div', class_='search_price').getText().strip()
                    temp = price.split('₩')
                    if len(temp) >= 3:
                        price = '₩ {} ~~₩ {}~~'.format(temp[2], temp[1])
                else:
                    price = "기록 없음"
                output_text += '\n{}  |  {}'.format(
                    product.find('span', class_='title').getText(), price)

            em = discord.Embed(title='스팀 최신 출시 제품',
                               description=output_text,
                               colour=discord.Colour(0x1b2838))
            await message.channel.send(embed=em)
        elif msg[1] == 'specials':
            new_src = requests.get(urls.STEAM_SPECIALS)
            new_src = BeautifulSoup(new_src.text, 'html.parser')
            new_prd = new_src.find_all('a', class_='search_result_row')

            output_text = '스팀의 인기 할인 제품 목록이에요.'
            for product in new_prd:
                if product.find('div',
                                class_='search_price').getText().strip() != '':
                    price = product.find(
                        'div', class_='search_price').getText().strip()
                    temp = price.split('₩')
                    if len(temp) >= 3:
                        price = '₩ ' + temp[2] + ' ~~₩ ' + temp[1] + '~~'
                else:
                    price = "기록 없음"
                output_text += '\n' + product.find(
                    'span', class_='title').getText() + '  |  ' + price

            em = discord.Embed(title='스팀 인기 할인 제품',
                               description=output_text,
                               colour=discord.Colour(0x1b2838))
            await message.channel.send(embed=em)
        elif msg[1] == 'hot':
            if len(msg) > 2:
                try:
                    requested_length = int(msg[3])
                except ValueError:
                    await message.channel.send(":x: 게임 갯수는 정수를 사용해주세요.")
                    return
            else:
                requested_length = 10

            hot_src = requests.get(urls.STEAM_HOT_GAME)
            hot_src = BeautifulSoup(hot_src.text, 'html.parser')
            hot_prd = hot_src.find_all('tr', class_='player_count_row')
            if len(hot_prd) < requested_length:
                requested_length = len(hot_prd)
            if requested_length > 25:
                requested_length = 25
            em = discord.Embed(title='스팀 최다 플레이어',
                               description='스팀의 현재 최다 플레이어 수 목록이에요.',
                               colour=discord.Colour(0x1b2838))
            i = 0
            for product in hot_prd:
                if i == requested_length:
                    break
                name = '{} ({})'.format(
                    product.find('a', class_='gameLink').getText(),
                    product.find('a', class_='gameLink')['href'].replace(
                        'https://store.steampowered.com/app/',
                        '').split('/')[0])
                value = "현재 플레이어: {}명 | 오늘 최고 기록: {}명".format(
                    product.find_all('span',
                                     class_='currentServers')[0].getText(),
                    product.find_all('span',
                                     class_='currentServers')[1].getText())
                em.add_field(name=name, value=value, inline=False)

                i += 1

            await message.channel(embed=em)
        elif msg[1] == 'news':
            if len(msg) > 2:
                requested_length = 10
                halflife3 = ['halflife 3', 'hl3', 'halflife3', 'hl 3']
                if message.content.replace('st!game news ',
                                           '').lower() in halflife3:
                    await message.channel.send(':x: 이미 뒤진 게임이에요.')
                    return
                id = get_game_id(message.content.replace('st!game news ', ''))
                if id == {}:
                    await message.channel.send(':x: 게임을 찾을 수 없어요.')
                    return
                await message.channel.send(":white_check_mark: 로딩 중 입니다.")
                keys = list(id.keys())
                news_src = requests.get(
                    urls.STEAM_GAME_NEWS.format(keys[0], requested_length))
                news_src = news_src.json()

                news_text = news_src['appnews']['newsitems']
                if requested_length > len(news_text):
                    requested_length = len(news_text)
                em = discord.Embed(
                    title=id[keys[0]],
                    description="{}개의 뉴스를 가져왔어요.".format(requested_length))
                i = 0
                for news in news_text:
                    if i > requested_length:
                        break
                    em.add_field(name='{} - {}'.format(news['feedlabel'],
                                                       news['title']),
                                 value=md(news['contents']) +
                                 ' **[자세히 보기]({})**'.format(news['url']))
                    i += 1
                await message.channel.send(embed=em)
            else:
                await message.channel.send(':x: 게임 이름을 입력해주세요.')
        elif msg[1] == 'realtime':
            if len(msg) > 2:
                if msg[2] == 'stop':
                    if message.channel not in realtimeList:
                        await message.channel.send(':x: 등록되지 않은 채널이에요!')
                        return
                    realtimeList.remove(message.channel)
                    await message.channel.send(
                        ':white_check_mark: 스팀 실시간 업데이트 수신을 중지했어요!')
                    return
            if message.channel in realtimeList:
                await message.channel.send(':x: 이미 등록된 채널이에요!')
                return
            realtimeList.append(message.channel)
            await message.channel.send(
                ':white_check_mark: 지금부터 이 채널에서 스팀 실시간 업데이트를 받을 수 있어요!')
    elif msg[0] == "user":
        if len(msg) == 1:
            await message.channel.send(":x: 명령어를 제대로 입력해주세요!.")
            await message.channel.send(embed=help.getSpecificHelp("user"))
        elif msg[1] == 'recent':
            if len(msg) == 2:
                await message.channel.send(":x: 스팀 아이디를 입력해주세요!.")
            elif len(msg) == 3:
                steamid = get_steam_id(msg[2])
                if steamid == 0:
                    await message.channel.send(":x: 유효한 스팀 아이디를 사용해주세요.")
                    return
                recents = requests.get(
                    urls.STEAM_RECENT_PLAYED.format(steam_api_key, steamid))
                recents = recents.json()
                if recents['response']['total_count'] == 0:
                    await message.channel.send(
                        ':frowning: 어떠한 게임도 불러오지 못했어요. 아무런 게임도 플레이하지 않으셨을수도 있고, 스팀 프로필이 비공개일수도 있어요.'
                    )
                    return
                em = discord.Embed(
                    title='{} 님이 최근에 플레이하신 게임 목록이에요.'.format(msg[2]),
                    description='지난 2주간 {}개의 게임을 플레이하셨어요.'.format(
                        recents['response']['total_count']),
                    colour=discord.Colour(0x1b2838))
                total_time = 0
                for text in recents['response']['games']:
                    print(text)
                    total_time += text['playtime_2weeks']
                    em.add_field(
                        name='{} ({})'.format(text['name'], text['appid']),
                        value='지난 2주간 {} 시간동안 플레이 함\n평생 동안 {} 시간동안 플레이 함'.
                        format("%.2f" % (text['playtime_2weeks'] / 60),
                               "%.2f" % (text['playtime_forever'] / 60)),
                        inline=False)
                em.add_field(
                    name='총 플레이 시간',
                    value=msg[2] +
                    '님은 지난 2주간 {} 시간동안 플레이하셨어요!'.format("%.2f" %
                                                        (total_time / 60)))
                await message.channel.send(embed=em)
            else:
                await message.channel.send(":x: ID를 입력해주세요.")
        elif msg[1] == 'library':
            if len(msg) == 1:
                await message.channel.send(":x: 명령어를 제대로 입력해주세요!.")
            else:
                if len(msg) == 2:
                    await message.channel.send(":x: 스팀 아이디를 입력해주세요!.")
                    return
                steamid = get_steam_id(msg[2])
                if steamid == 0:
                    await message.channel.send(":x: 유효한 스팀 아이디를 사용해주세요.")
                    return
                userlib = requests.get(
                    urls.STEAM_LIBRARY.format(steam_api_key, steamid))
                userlib = userlib.json()
                games = userlib['response']['games']
                games = sorted(games,
                               key=lambda game: game['playtime_forever'],
                               reverse=True)
                if len(msg) > 3:
                    try:
                        requested_length = int(msg[3])
                    except ValueError:
                        if msg[3] == 'random':
                            game = random.choice(games)
                            playtime = '평생 {} 시간 플레이 함'.format(
                                '%.2f' % (game['playtime_forever'] / 60))
                            if 'playtime_2weeks' in game:
                                playtime += '\n지난 2주 간 {} 시간 플레이 함'.format(
                                    '%.2f' % (game['playtime_2weeks'] / 60))
                            em = discord.Embed(
                                title='{} ({})'.format(game['name'],
                                                       game['appid']),
                                description='{}\n플레이: steam://run/{}/'.format(
                                    playtime, game['appid']))
                            await message.channel.send(embed=em)
                            return
                        await message.channel.send(":x: 게임 갯수는 정수를 사용해주세요.")
                        return
                else:
                    requested_length = 5
                if len(games) < requested_length:
                    requested_length = len(games)
                if requested_length > 25:
                    requested_length = 25
                i = 0
                em = discord.Embed(title='{} 님의 라이브러리에요.'.format(msg[2]),
                                   description='플레이시간 상위 {}개를 불러왔어요.'.format(
                                       requested_length),
                                   inline=False,
                                   colour=discord.Colour(0x1b2838))
                for game in games:
                    if i == requested_length:
                        break
                    playtime = '평생 {} 시간 플레이 함'.format(
                        '%.2f' % (game['playtime_forever'] / 60))
                    if 'playtime_2weeks' in game:
                        playtime += '\n지난 2주 간 {} 시간 플레이 함'.format(
                            '%.2f' % (game['playtime_2weeks'] / 60))

                    em.add_field(name='{} ({})'.format(game['name'],
                                                       game['appid']),
                                 value='{}\n플레이: steam://run/{}/'.format(
                                     playtime, game['appid']),
                                 inline=False)
                    i += 1
                await message.channel.send(embed=em)
        elif msg[1] == 'wishlist':
            if len(msg) == 1:
                await message.channel.send(":x: 명령어를 제대로 입력해주세요!.")
            else:
                steamid = get_steam_id(msg[2])
                if steamid == 0:
                    await message.channel.send(":x: 유효한 스팀 아이디를 사용해주세요.")
                    return
                wishlist = requests.get(urls.STEAM_WISHLIST.format(steamid))
                wishlist = wishlist.json()
                if len(msg) > 3:
                    try:
                        requested_length = int(msg[3])
                    except ValueError:
                        await message.channel.send(":x: 게임 갯수는 정수를 사용해주세요.")
                        return
                else:
                    requested_length = 20
                if len(wishlist) < requested_length:
                    requested_length = len(wishlist)
                if requested_length > 50:
                    requested_length = 50
                sortedNumbers = sorted(
                    wishlist,
                    key=lambda wish: wishlist[wish]['priority'] if wishlist[
                        wish]['priority'] != 0 else requested_length + 1)
                sortedNumbers += sorted(
                    wishlist,
                    key=lambda wish: wishlist[wish]['priority'] if wishlist[
                        wish]['priority'] == 0 else requested_length + 1)
                i = 0
                output = '찜 목록에 있는 게임 {}개를 불러왔어요.\n'.format(requested_length)
                for num in sortedNumbers:
                    if i == requested_length:
                        break
                    output += '{} ({})'.format(wishlist[num]['name'], num)
                    if wishlist[num].get('subs', False):
                        if wishlist[num]['subs'][0].get('price', False):
                            output += ' - ₩ {:,}'.format(
                                int(wishlist[num]['subs'][0]['price']) // 100)
                    output += '\n'
                    i += 1
                em = discord.Embed(title='{} 님의 찜 목록이에요.'.format(msg[2]),
                                   description=output,
                                   inline=False,
                                   colour=discord.Colour(0x1b2838))

                await message.channel.send(embed=em)
        elif msg[1] == "profile":
            if len(msg) < 3:
                await message.channel.send(":x: 스팀 아이디를 입력해주세요!.")
                return
            xmls = get_steam_id(msg[2], True)
            if xmls == 0:
                await message.channel.send(":x: 유효한 스팀 아이디를 사용해주세요.")
                return
            if xmls.find('onlineState').text == 'in-game':
                statusColor = discord.Colour(0x90ba3c)
            elif xmls.find('onlineState').text == 'online':
                statusColor = discord.Colour(0x57cbde)
            else:
                statusColor = discord.Colour(0x898989)
            em = discord.Embed(
                title=xmls.find('steamID').text,
                description=xmls.find('stateMessage').text.replace(
                    '<br/>', ': '),
                colour=statusColor).set_thumbnail(
                    url=xmls.find('avatarIcon').text)
            em.add_field(name='요약',
                         value=xmls.find('summary').text.replace('<br>', '\n'),
                         inline=False)
            await message.channel.send(embed=em)