コード例 #1
0
    async def sendToChat(self, ctx, userOne: User, userTwo: User = None):
        length = 0
        attempts = 0
        existingDict = False
        phrase = ""
        text_channel = ctx.channel  #chat channel

        markovDict, existingDict = await Markov.load_pickle(
            os.path.join(self._chains_dir,
                         str(userOne) + MarkovCommands._CHAINSEXT))
        if existingDict:
            while ((phrase == "" or length < 5)
                   and attempts < 10):  #Generate new phrase if last one sucked
                try:
                    phrase, length = await Markov.generateChain(
                        markovDict, True)
                except (
                        KeyError
                ):  #On error just make a new phrase (I'll fix this later maybe)
                    continue

            if attempts >= 10:
                await ctx.send("Exceeded number of attempts for " +
                               str(userOne))
            else:
                embed = Embed(
                    title=':speaking_head: Markov :person_shrugging:',
                    color=0x228B22)
                embed.add_field(name=str(userOne), value=phrase.capitalize())
                await ctx.send(embed=embed)
        else:
            await ctx.send("No existing Markov dictionary for " +
                           str(userOne) + ".\nUse \"d!collect <@" +
                           str(userOne.id) + ">\"")
コード例 #2
0
    async def get_message(self):
        messages = await self.channel.history(limit=1,
                                              oldest_first=True).flatten()
        message = None

        # Load the message from the channel, creating if necessary
        if not messages:
            message_content = (
                f"**Select your coding skill level by reacting to this message**\n\n"
                f"Use {self.get_emoji('beginner')} if you're a beginner\n"
                f"Use {self.get_emoji('intermediate')} if you're at an intermediate skill level\n"
                f"Use {self.get_emoji('expert')} if you're an expert (e.g. production work experience)\n"
            )
            embed = Embed(description=message_content,
                          color=0x306998).set_author(
                              name=f"Skill Level Assignment",
                              icon_url=self.server.icon.url)
            embed.set_footer(
                text=
                "We reserve the right to adjust your skill level manually if "
                "we don't feel you've been honest about it.")
            message = await self.channel.send(embed=embed)
            await self.add_reactions()
        else:
            message = messages[0]

        return message
コード例 #3
0
ファイル: embeds.py プロジェクト: wanony/PublicBot
def banned_word_embed(guild, word):
    message = f'Your message was deleted in {guild.name} because it contained the banned word {word}.'
    embed = Embed(title='Message Deleted!',
                  description=message,
                  color=Color.orange())
    embed.set_thumbnail(url=guild.icon_url)
    return embed
コード例 #4
0
    async def profile(self, ctx, member: Optional[Member]):
        member = member or ctx.author

        userinfo = getuserfromdiscord(member.id)
        if userinfo:
            embed = Embed(
                title=member.display_name,
                description=f"Here is the info on {member.mention}",
                colour=member.colour,
                timestamp=nextcord.utils.utcnow(),
            )

            fields = [
                ("UserID", userinfo["_id"], True),
                ("Username", userinfo["username"], True),
                (
                    "Owned Products",
                    "\n".join([product for product in userinfo["purchases"]])
                    or "None",
                    True,
                ),
            ]

            for name, value, inline in fields:
                embed.add_field(name=name, value=value, inline=inline)

            await ctx.send(embed=embed, reference=ctx.message)
        else:
            await ctx.send(
                f"I was unable to find any info on {member.display_name}.",
                reference=ctx.message,
            )
コード例 #5
0
ファイル: embeds.py プロジェクト: wanony/PublicBot
def restricted_embed(guild):
    message = f"""You are currently restricted from using commands in {guild.name}!\n
                  You can continue to use Joy's functions in other servers or in DMs!
                  Speak with a moderator of {guild.name} to get more information!"""
    embed = Embed(title='Restricted User Warning!',
                  description=message,
                  color=Color.orange())
    embed.set_thumbnail(url=guild.icon_url)
    return embed
コード例 #6
0
 async def checktime(self, ctx):
     pet = PetHandler.getcurrentpet()
     embed = Embed(title=':motorized_wheelchair: Name: ' + str(pet['name'] + ' :motorized_wheelchair:'), color=0x228B22)
     embed.add_field(name='Last Checked', value=str(pet['lastchecked']), inline=True)
     embed.add_field(name='Last Fed', value=str(pet['lastfeed']), inline=True)
     embed.add_field(name='Last Watered', value=str(pet['lastwatered']), inline=True)
     embed.add_field(name='Last Cleaned', value=str(pet['lastcleaned']), inline=True)
     embed.add_field(name='Last Pet', value=str(pet['lastpet']), inline=True)
     await ctx.send(embed=embed)
コード例 #7
0
 async def modules(self, ctx: commands.Context):
     """Syntax: !modules <>
     Part of admin cog
     :return a list of numbers"""
     if ctx.message.author.guild_permissions.administrator:
         embed = Embed(title="Gavin: Here are the modules")
         for m_name, c_object in self.bot.cogs.items():
             embed.add_field(name=f"Module: {m_name}", value=f"Reload: cogs.{m_name.lower()}cog", inline=False)
         await ctx.channel.send(embed=embed)
コード例 #8
0
 async def update_select(self, _, interaction: Interaction):
     product = str(interaction.data["values"])[2:-2]
     embed = Embed(
         title=f"Update {product}",
         description=f"What would you like to change?",
         colour=Colour.blue(),
         timestamp=nextcord.utils.utcnow(),
     )
     embed.set_footer(text="Redon Tech RPH • By: parker02311")
     await interaction.message.edit(
         "", embed=embed, view=WhatUpdateView(self.context, product, self.bot)
     )
コード例 #9
0
ファイル: message_events.py プロジェクト: vzdc/ZDC.Discord
 async def on_message_edit(self, before: Message, after: Message) -> None:
     logging_channel = before.guild.get_channel(int(os.environ["LOGGING_CHANNEL"]))
     embed = Embed(
         title="Message Edited",
         description=f"{before.author.mention}'s message in {before.channel.mention} was edited",
         color=Color.red(),
     )
     embed.add_field(name="Before", value=before.content, inline=False)
     embed.add_field(name="After", value=after.content, inline=False)
     embed.set_thumbnail(url=before.author.avatar.url)
     embed.timestamp = datetime.now()
     await logging_channel.send(embed=embed)
コード例 #10
0
async def give_product():
    info = await request.get_json()
    try:
        giveproduct(info["userid"], info["productname"])
        userinfo = getuser(info["userid"])
        member = nextcord.utils.get(sbot.users, id=userinfo["discordid"])
        if member != None:  # Try to prevent it from returning an error
            product = getproduct(info["productname"])
            productname = info["productname"]
            if product != None:
                embed = Embed(
                    title="Thanks for your purchase!",
                    description=f"Thank you for your purchase of **{productname}** please get it by using the links below.",
                    colour=Colour.from_rgb(255, 255, 255),
                    timestamp=nextcord.utils.utcnow(),
                )

                await member.send(embed=embed)

                if product["attachments"] != None or product["attachments"] != []:
                    for attachment in product["attachments"]:
                        await member.send(attachment)

        return dumps(userinfo)
    except:
        return {"errors": [{"message": "Unable to give product"}]}
コード例 #11
0
 async def log_action(
     self,
     action: str,
     user: Member,
     mod: Member,
     reason: str,
     message: Message,
     **kwargs,
 ):
     additional_fields = "\n".join(
         [f"{key}: {value}" for key, value in kwargs.items()]
     )
     await self.get_channel(
         self.settings.get("MOD_ACTION_LOG_CHANNEL", "mod-action-log")
     ).send(
         embed=Embed(
             description=f"Moderator: {mod.mention}\n"
             + (f"User: {user.mention}\n" if user else "")
             + f"Reason: {reason}"
             + ("\n" if additional_fields else "")
             + f"{additional_fields}\n\n"
             f"[Jump To Action]({message.jump_url})",
             color=0xCC2222,
         ).set_author(
             name=f"{action} @{user.display_name if user else mod.display_name}",
             icon_url=self.server.icon.url,
         )
     )
コード例 #12
0
ファイル: embeds.py プロジェクト: wanony/PublicBot
def perma_embed():
    message = f"""You are currently restricted from adding to Joy!\n
                  You can continue to use Joy's functions, but adding to Joy has been disabled.
                  Speak with a moderator of Joy to get more information."""
    embed = Embed(title='Restricted User Warning!',
                  description=message,
                  color=Color.orange())
    return embed
コード例 #13
0
    async def giveproduct(self, ctx, members: Greedy[Member], *, product: str):
        if not len(members):
            await ctx.send(
                f"You left out a vital argument, use {self.bot.PREFIX}help to see all the required arguments.",
                refrence=ctx.message,
            )

        elif not getproduct(product):
            await ctx.send(f"You inputted a incorrect product.",
                           refrence=ctx.message)

        else:
            for member in members:
                data = getuserfromdiscord(member.id)
                if data:
                    try:
                        giveproduct(data["_id"], product)

                        try:
                            embed = Embed(
                                title="Thanks for your purchase!",
                                description=
                                f"Thank you for your purchase of {product} please get it by using the links below.",
                                colour=Colour.from_rgb(255, 255, 255),
                                timestamp=nextcord.utils.utcnow(),
                            )
                            if not member.dm_channel:
                                await member.create_dm()

                            await member.dm_channel.send(embed=embed)

                            for attachment in getproduct(
                                    product)["attachments"]:
                                await member.dm_channel.send(attachment)
                        except:
                            await ctx.send(
                                f"I was unable to DM {member.mention} there product.",
                                reference=ctx.message,
                            )
                    except:
                        await ctx.send(
                            f"I was unable to give {member.mention} {product}.",
                            reference=ctx.message,
                        )
                        members.remove(member)
                else:
                    await ctx.send(
                        f"I was unable to give {member.mention} {product}.",
                        reference=ctx.message,
                    )
                    members.remove(member)

            if members:
                await ctx.send(
                    "Gave " + "".join([member.mention for member in members]) +
                    f" {product}.",
                    reference=ctx.message,
                )
コード例 #14
0
async def sources(intr: Interaction):
    """List all the sources supported"""
    if not await assert_check(intr, is_direct_only):
        return

    await intr.response.defer()

    embed = Embed(
        title="Supported sources",
        description=
        "This embed shows the list of all the sources currently supported",
        url=
        "https://novelsave-sources.readthedocs.io/en/latest/content/support.html#supported-novel-sources",
    )

    for gateway in sorted(source_service.get_novel_sources(),
                          key=lambda g: g.base_url):
        value = f"search: {'✅' if gateway.is_search_capable else '❌'}"
        embed.add_field(name=f"<{gateway.base_url}>", value=value)

    embed.set_footer(text=f"Version {source_service.current_version}")

    request_embed = Embed(
        title="Looking for something else?",
        description=
        "You can request a new source by creating an issue at github",
        url="https://github.com/mensch272/novelsave/issues/new/choose",
    )

    await intr.send(embeds=[embed, request_embed])
コード例 #15
0
    async def racerinfo(self, ctx):
        embed = Embed(color=0x228B22)
        package_dir = os.path.dirname(os.path.abspath(__file__))
        thefile = os.path.join(package_dir, 'emojiracers.txt')
        with open(thefile) as json_file:
            json_object = json.load(json_file)
            json_file.close()

        emojilist = json_object['emojilist']

        for emoji in emojilist:
            embed.add_field(
                name=emoji['emoji'],
                value='Won: ' + str(emoji['wins']) + '\nLoss: ' + str(
                    (emoji['totalraces'] - emoji['wins'])) + '\nWin%: ' +
                str(math.ceil((emoji['wins'] / emoji['totalraces']) * 100)),
                inline=True)
        await ctx.send(embed=embed)
コード例 #16
0
 async def stats(self, ctx):
     num_bots = self.get_bots()
     await ctx.send(embed=Embed(
         title=f"Server Stats",
         description=
         (f"Of the {self.server.member_count - num_bots:,} members there are currently {self.get_online():,} "
          f"online!!!\n\n{self.get_pending():,} have not accepted the rules. Found {num_bots:,} bots."
          ),
         color=0x00A35A,
     ))
コード例 #17
0
    async def list_tips(self, channel, tips, label=None):
        formatted = [f"- {tip.label}" for tip in tips]
        message = "Here are all tips that are available"
        title = "Available Tips"

        if label:
            message = f"Here are the tips that are similar to *{label}*"
            title = "Possible Matches"

        if not len(formatted):
            message = "*No Tips Found*"

        embed = Embed(description=message, color=0x306998, title=title)
        while formatted:
            index = min(len(formatted), 5)
            embed.add_field(name="- - - -", value="\n".join(formatted[:index]))
            formatted = formatted[index:]

        await channel.send(embed=embed)
コード例 #18
0
 async def transfer(self, ctx, member: Member):
     await ctx.send(
         embed=Embed(
             title="Transfer Product",
             description="Please select the product you want to transfer.",
             colour=Colour.from_rgb(255, 255, 255),
             timestamp=nextcord.utils.utcnow(),
         ),
         view=TransferView(ctx, member),
         reference=ctx.message,
     )
コード例 #19
0
 async def on_member_join(self, member: Member):
     history = list(
         ModAction.select().limit(1).where(ModAction.user_id == member.id))
     if history:
         mod_action_log = self.get_channel(
             self.settings.get("MOD_ACTION_LOG_CHANNEL", "mod-action-log"))
         await mod_action_log.send(embed=Embed(
             description=
             f"{member.mention} has rejoined. They have a past history of mod actions.",
             color=0xFFE873,
         ).set_author(name="Member Rejoined"))
コード例 #20
0
 def build_mod_action_embed(
     self, ctx, user: Member, reason: str, title: str
 ) -> Embed:
     embed = Embed(description=reason, color=0xCC2222)
     embed.set_author(name=title, icon_url=self.server.icon.url)
     embed.set_footer(text=ctx.author.display_name, icon_url=ctx.author.avatar.url)
     return embed
コード例 #21
0
    async def getproducts(self, ctx):
        dbresponse = getproducts()
        embed = Embed(
            title="Products",
            description=f"Here is all the products I was able to get for this server!",
            colour=ctx.author.colour,
            timestamp=nextcord.utils.utcnow(),
        )

        fields = []

        for product in dbresponse:
            fields.append(
                (
                    product["name"],
                    "Product Description: "
                    + str(product["description"])
                    + "\nProduct Price: "
                    + str(product["price"]),
                    False,
                )
            )

        for name, value, inline in fields:
            embed.add_field(name=name, value=value, inline=inline)

        embed.set_footer(text="Redon Tech RPH • By: parker02311")

        await ctx.send(embed=embed, reference=ctx.message)
コード例 #22
0
    async def send(self, ctx, channel, *, message):
        if not ctx.author.guild_permissions.manage_guild:
            return

        title = (message[:message.find("\n")]
                 if message.find("\n") > 0 else "beginner.py")
        content = message[message.find("\n") + 1:]

        embed = Embed(title=title, description=content,
                      color=0x306998).set_footer(
                          text=ctx.author.display_name,
                          icon_url=ctx.author.avatar.url)
        await self.server.get_channel(int(channel[2:-1])).send(embed=embed)
コード例 #23
0
ファイル: message_events.py プロジェクト: vzdc/ZDC.Discord
 async def on_message_delete(self, message: Message) -> None:
     logging_channel = message.guild.get_channel(int(os.environ["LOGGING_CHANNEL"]))
     embed = Embed(
         title="Message Deleted",
         description=f"{message.author.mention}'s message in {message.channel.mention} was deleted",
         color=Color.red(),
     )
     embed.add_field(name="Message", value=message.content)
     embed.set_thumbnail(url=message.author.avatar.url)
     embed.timestamp = datetime.now()
     await logging_channel.send(embed=embed)
コード例 #24
0
    async def history(self, ctx, member: Member):
        history = list(
            ModAction.select()
            .limit(50)
            .order_by(ModAction.datetime.desc())
            .where(ModAction.user_id == member.id)
        )
        message = f"{member.mention} has no mod action history."
        title = f"Mod History for {member}"
        if (
            ctx.invoked_with.casefold() == "whois"
            or not ctx.author.guild_permissions.manage_messages
        ):
            message = f"Here are some details about {member.mention}"
            title = f"Who is {member}"
        elif len(history):
            action_items = []
            for action in history:
                details = pickle.loads(action.details.encode())
                msg = details.get("message", "*No message*")
                link_url = details.get("link", None)
                link = f"\n[Jump To Action]({link_url})" if link_url else ""
                action_items.append(
                    f"**{action.action_type:6} {action.datetime:%d/%m/%Y}**\n{msg}{link}"
                )
            message = "\n".join(action_items)

        how_long_ago = pytz.utc.localize(datetime.utcnow()) - member.joined_at
        how_long_ago_msg = "Just now"
        if how_long_ago > timedelta(days=1):
            how_long_ago_msg = f"{how_long_ago // timedelta(days=1)} days ago"
        elif how_long_ago > timedelta(hours=1):
            how_long_ago_msg = f"{how_long_ago // timedelta(hours=1)} hours ago"
        elif how_long_ago > timedelta(minutes=5):
            how_long_ago_msg = f"{how_long_ago // timedelta(minutes=1)} minutes ago"

        await ctx.send(
            embed=Embed(
                title=title,
                description=message,
                color=0xFFE873,
            )
            .add_field(name="Joined", value=how_long_ago_msg)
            .add_field(name="User ID", value=str(member.id))
            .add_field(
                name="Are They Sus?",
                value="🚨 Yes 🚨"
                if utils.get(ctx.guild.roles, name="🚨sus🚨") in member.roles
                else "No, they cool 😎",
            )
        )
コード例 #25
0
 async def _send_error_to_webhook(self, error: Exception, ctx: commands.Context):
     async with ClientSession() as session:
         wh = Webhook.partial(
             882811369353793576,
             self.settings.get("_ERROR_WEBHOOK_URL"),
             session=session,
         )
         await wh.send(
             embed=Embed(
                 title="🛑Error Encountered",
                 description=f"{error}\n\nCommand: {ctx.command and ctx.command.qualified_name or ctx!r}",
                 color=0xFF8800,
             )
         )
コード例 #26
0
 async def cmd_help(self, ctx, command):
     embed = Embed(
         title=f"Help with `{command}`",
         description=syntax(command),
         colour=ctx.author.colour,
     )
     embed.add_field(name="Command Description", value=command.brief)
     embed.set_footer(text="Pembroke Bot • By: parker02311")
     await ctx.send(embed=embed, reference=ctx.message)
コード例 #27
0
ファイル: xkcd.py プロジェクト: elihschiff/Rubber-Duck-Python
    def get_comic(self, number):
        if number == None:
            comic = xkcd.getRandomComic()
        else:
            comic = xkcd.getComic(number)

        embed = Embed(description=comic.getAltText())
        embed.set_author(name=comic.getTitle())
        embed.set_image(url=comic.getImageLink())
        return embed
コード例 #28
0
    async def send_dm(
        self,
        member: Member,
        embed: Embed,
        message: Message = None,
        description: str = "",
    ):
        embed.description = f"{description}\n\n" f"Reason: {embed.description}\n\n"
        if message:
            embed.description += f"[Jump To Conversation]({message.jump_url})"

        try:
            await member.send(embed=embed)
            return True
        except nextcord.errors.Forbidden:
            return False
コード例 #29
0
 async def _help_embed(self,
                       title: str,
                       description: Optional[str] = None,
                       mapping: Optional[str] = None,
                       command_set: Optional[Set[commands.Command]] = None,
                       set_author: bool = False) -> Embed:
     embed = Embed(title=title)
     if description:
         embed.description = description
     if set_author:
         avatar = self.context.bot.user.avatar or self.context.bot.user.default_avatar
         embed.set_author(name=self.context.bot.user.name,
                          icon_url=avatar.url)
     if command_set:
         # show help about all commands in the set
         filtered = await self.filter_commands(command_set, sort=True)
         for command in filtered:
             embed.add_field(name=self.get_command_signature(command),
                             value=command.short_doc or "...",
                             inline=False)
     elif mapping:
         # add a short description of commands in each cog
         for cog, command_set in mapping.items():
             filtered = await self.filter_commands(command_set, sort=True)
             if not filtered:
                 continue
             name = cog.qualified_name if cog else "No category"
             emoji = getattr(cog, "COG_EMOJI", None)
             cog_label = f"{emoji} {name}" if emoji else name
             # \u2002 is an en-space
             cmd_list = "\u2002".join(
                 f"`{self.context.clean_prefix}{cmd.name}`"
                 for cmd in filtered)
             value = (f"{cog.description}\n{cmd_list}"
                      if cog and cog.description else cmd_list)
             embed.add_field(name=cog_label, value=value)
     return embed
コード例 #30
0
 async def disabled(self, ctx):
     """Display Disabled Commands"""
     results = tool.returnDisabled(ctx.message.guild.id, self.c)
     modules = {}
     for m_name, c_object in self.bot.cogs.items():
         modules[f"cogs.{m_name.lower()}cog"] = {}
     for collection in results:
         module = collection[0]
         command = collection[1]
         channelID = "<#" + str(collection[2]) + ">"
         try:
             modules[module][channelID] = command
         except KeyError as e:
             self.logger.error(f"Error: {e}")
     embeds = []
     embedsTitle = []
     for i, collection in enumerate(results):
         moduleName = collection[0]
         title = f"Disabled for: {moduleName}"
         if i == 0:
             embed = Embed(title=title)
             embedsTitle.append(title)
             embeds.append(embed)
             if modules[moduleName]:
                 for key, value in modules[moduleName].items():
                     embed.add_field(name=f"Command: {str(value)}", value=f"Channel: !{str(key)}")
         else:
             if title in embedsTitle:
                 e = embedsTitle.index(title)
                 c_embed = embeds[e]
                 if modules[moduleName]:
                     for key, value in modules[moduleName].items():
                         c_embed.add_field(name=f"Command: {str(value)}", value=f"Channel: !{str(key)}")
             else:
                 embed = Embed(title=title)
                 embedsTitle.append(title)
                 embeds.append(embed)
                 if modules[moduleName]:
                     for key, value in modules[moduleName].items():
                         embed.add_field(name=f"Command: {str(value)}", value=f"Channel: !{str(key)}")
     for embed in embeds:
         await ctx.send(embed=embed)