示例#1
0
from giphy_client.rest import ApiException

load_dotenv()


def get_prefix(client, message):
    with open('json/prefixes.json', 'r') as f:
        prefixes = json.load(f)

    return prefixes[str(message.guild.id)]


client = commands.Bot(command_prefix=get_prefix)
client.remove_command("help")

emb = discord.Embed(color=discord.Color.blue())


@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.idle,
                                 activity=discord.Game('GTA 6 || ssbc.help'))
    print('Bot is ready.')


reddit = praw.Reddit(client_id="3x8bPejF3lTyPQ",
                     client_secret="E7-k6V90lpIM5ZYX5ytrBWLjSc6LxQ",
                     username="******",
                     password="******",
                     user_agent="pythonpraw",
                     check_for_async=False)
示例#2
0
文件: roles.py 项目: ozzhates/AceBot
    async def spawn(self, ctx):
        '''Spawn role selectors.'''

        await ctx.message.delete()

        conf = await self.config.get_entry(ctx.guild.id)

        selectors = await self.db.fetch(
            '''SELECT rs.*
			FROM role_selector as rs
			JOIN unnest($1::INTEGER[]) WITH ORDINALITY t(id, ord) USING (id)
			WHERE id=ANY($1::INTEGER[])
			ORDER BY t.ord
			''', conf.selectors)

        if not selectors:
            raise commands.CommandError(
                'No selectors configured. Do `roles editor` to set one up.')

        if any(not selector.get('roles') for selector in selectors):
            raise commands.CommandError(
                'You have empty selectors. Delete these or add roles to them before spawning.'
            )

        if conf.message_ids:
            channel = ctx.guild.get_channel(conf.channel_id)
            if channel:
                for message_id in conf.message_ids:
                    try:
                        msg = await channel.fetch_message(message_id)
                        if msg:
                            await msg.delete()
                    except discord.HTTPException:
                        pass

        msgs = list()

        async def delete_all():
            for m in msgs:
                try:
                    await m.delete()
                except discord.HTTPException:
                    pass

        for selector in selectors:

            # https://stackoverflow.com/questions/866465/order-by-the-in-value-list
            roles = await self.db.fetch(
                '''
				SELECT re.* 
				FROM role_entry as re 
				JOIN unnest($1::INTEGER[]) WITH ORDINALITY t(id, ord) USING (id) 
				WHERE id=ANY($1::INTEGER[])
				ORDER BY t.ord
				''', selector.get('roles'))

            if not roles:
                continue

            e = discord.Embed(
                description=selector.get('description')
                or 'Click the reactions to give or remove roles.')

            icon = selector.get('icon')

            e.set_author(name=selector.get('title') or 'Role Selector',
                         icon_url=icon if icon else ctx.guild.icon_url)

            for role in roles:
                e.add_field(name='{} {}'.format(role.get('emoji'),
                                                role.get('name')),
                            value=role.get('description'),
                            inline=selector.get('inline'))

            msg = await ctx.send(embed=e)

            msgs.append(msg)

            try:
                for role in roles:
                    emoj = role.get('emoji')
                    await msg.add_reaction(emoj)
            except discord.HTTPException:
                await delete_all()
                raise commands.CommandError(
                    'Failed adding the emoji {}.\nIf the emoji has been deleted, change it in the editor.'
                    .format(emoj))

        await conf.update(channel_id=ctx.channel.id,
                          message_ids=list(msg.id for msg in msgs))
示例#3
0
    async def propose(self, ctx, partner: MemberWithCharacter):
        _("""Propose for a marriage.""")
        if partner == ctx.author:
            return await ctx.send(
                _("You should have a better friend than only yourself."))
        if ctx.character_data["marriage"] != 0 or ctx.user_data[
                "marriage"] != 0:
            return await ctx.send(_("One of you is married."))
        msg = await ctx.send(embed=discord.Embed(
            title=_("{author} has proposed for a marriage!").format(
                author=ctx.author.mention),
            description=
            _("{author} wants to marry you, {partner}! React with :heart: to marry them!"
              ).format(author=ctx.author.mention, partner=partner.mention),
            colour=0xFF0000,
        ).set_image(url=ctx.author.avatar_url).set_thumbnail(
            url="http://www.maasbach.com/wp-content/uploads/The-heart.png"))
        await msg.add_reaction("\U00002764")

        def reactioncheck(reaction, user):
            return (str(reaction.emoji) == "\U00002764"
                    and reaction.message.id == msg.id
                    and user.id == partner.id)

        try:
            reaction, user = await self.bot.wait_for("reaction_add",
                                                     timeout=120.0,
                                                     check=reactioncheck)
        except asyncio.TimeoutError:
            return await ctx.send(_("They didn't want to marry."))
        # check if someone married in the meantime
        async with self.bot.pool.acquire() as conn:
            check1 = await conn.fetchrow(
                'SELECT * FROM profile WHERE "user"=$1 AND "marriage"=$2;',
                ctx.author.id,
                0,
            )
            check2 = await conn.fetchrow(
                'SELECT * FROM profile WHERE "user"=$1 AND "marriage"=$2;',
                partner.id,
                0,
            )
            if check1 and check2:
                await conn.execute(
                    'UPDATE profile SET "marriage"=$1 WHERE "user"=$2;',
                    partner.id,
                    ctx.author.id,
                )
                await conn.execute(
                    'UPDATE profile SET "marriage"=$1 WHERE "user"=$2;',
                    ctx.author.id,
                    partner.id,
                )
                await ctx.send(
                    _("Owwwwwww! :heart: {author} and {partner} are now married!"
                      ).format(author=ctx.author.mention,
                               partner=partner.mention))
            else:
                await ctx.send(
                    _("Either you or your lovee married in the meantime... :broken_heart:"
                      ))
示例#4
0
 async def delete(self, ctx, reactid=None):
     perms = ctx.message.author.permissions_in(ctx.channel)
     if not perms.manage_messages:
         em = discord.Embed(
             title=":x: Error!",
             description="You have insufficient permissions!",
             colour=discord.Colour.red())
         msg = await ctx.send(embed=em)
         await asyncio.sleep(3)
         await msg.delete()
     else:
         if reactid == None:
             em = discord.Embed(
                 title=":x: Error",
                 description="Enter a reaction ID to delete.".format(
                     bot.command_prefix),
                 colour=discord.Colour.red())
             msg = await ctx.send(embed=em)
             await asyncio.sleep(3)
             await msg.delete()
         else:
             conn = psycopg2.connect(
                 database="da5rfaqi7o9cg7",
                 user="******",
                 password=
                 "******",
                 host="ec2-79-125-110-209.eu-west-1.compute.amazonaws.com",
                 port="5432")
             cur = conn.cursor()
             cur.execute(
                 """SELECT serverid, message, reaction FROM customreacts WHERE id = %s;""",
                 ([reactid]))
             deleted = cur.fetchone()
             if deleted[0] != ctx.guild.id:
                 em = discord.Embed(title=":x: Error!",
                                    description="That isn't a valid ID!",
                                    colour=discord.Colour.red())
                 msg = await ctx.send(embed=em)
                 await asyncio.sleep(3)
                 await msg.delete()
             else:
                 cur.execute("""DELETE FROM customreacts WHERE id = %s;""",
                             ([reactid]))
                 rowdel = cur.rowcount
                 conn.commit()
                 cur.close()
                 conn.close()
                 if int(rowdel) == 1:
                     em = discord.Embed(title="Deleted:",
                                        colour=discord.Colour.green())
                     em.add_field(name="Id",
                                  value=str(reactid),
                                  inline=True)
                     em.add_field(name="Message",
                                  value=str(deleted[1]),
                                  inline=True)
                     em.add_field(name="Reaction",
                                  value=str(deleted[2]),
                                  inline=True)
                     await ctx.send(embed=em)
                 else:
                     em = discord.Embed(
                         title=":x:Error",
                         description=
                         "No reaction with that ID could be found.",
                         colour=discord.Colour.red())
                     await ctx.send(embed=em)
示例#5
0
文件: roles.py 项目: ozzhates/AceBot
 def new_embed(question):
     e = discord.Embed(description=question)
     e.set_footer(text=EDIT_FOOTER)
     return e
示例#6
0
async def remindme(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        time_req = pld.args[0]
        try:
            in_seconds = convert_to_seconds(time_req)
            upper_limit = 7776000
            if in_seconds <= upper_limit:
                rem_count = await cmd.db[cmd.db.db_nam
                                         ].Reminders.count_documents(
                                             {'user_id': pld.msg.author.id})
                rem_limit = 15
                if rem_count < rem_limit:
                    is_dm = False
                    if len(pld.args) > 1:
                        if pld.args[-1].lower() == '--direct':
                            is_dm = True
                            text_message = ' '.join(pld.args[1:-1])
                            text_message = 'No reminder message set.' if not text_message else text_message
                        else:
                            text_message = ' '.join(pld.args[1:])
                    else:
                        text_message = 'No reminder message set.'
                    execution_stamp = arrow.utcnow().int_timestamp + in_seconds
                    timestamp = arrow.get(execution_stamp).datetime
                    if in_seconds < 60:
                        time_diff = f'In {in_seconds} seconds'
                    else:
                        time_diff = arrow.get(execution_stamp + 5).humanize(
                            arrow.utcnow())
                    reminder_id = secrets.token_hex(2)
                    reminder_data = {
                        'reminder_id': reminder_id,
                        'user_id': pld.msg.author.id,
                        'creation_stamp': arrow.utcnow().int_timestamp,
                        'execution_stamp': execution_stamp,
                        'channel_id': pld.msg.channel.id,
                        'server_id': pld.msg.guild.id,
                        'text_message': text_message,
                        'direct_message': is_dm
                    }
                    await cmd.db[cmd.db.db_nam
                                 ].Reminders.insert_one(reminder_data)
                    response = discord.Embed(color=0x66CC66,
                                             timestamp=timestamp)
                    response.description = text_message
                    response.set_author(name=f'Reminder {reminder_id} Created',
                                        icon_url=user_avatar(pld.msg.author))
                    response.set_footer(text=f'Executes: {time_diff.title()}')
                else:
                    response = GenericResponse(
                        'You already have 15 reminders pending.').error()
            else:
                response = GenericResponse(
                    'Reminders have a limit of 90 days.').error()
        except (LookupError, ValueError):
            response = GenericResponse(
                'Please use the format HH:MM:SS.').error()
    else:
        response = GenericResponse('Nothing inputted.').error()
    await pld.msg.channel.send(embed=response)
示例#7
0
 async def cogs(self, ctx):
     embed = discord.Embed(title='Current Cogs ({})'.format(len(cogsx)),
                           colour=discord.Colour.red())
     for x in cogsy:
         embed.add_field(name=x, value=description[x], inline=False)
     await ctx.send(embed=embed)
示例#8
0
    async def trade(self, ctx, user, item1, item2):
        if len(ctx.message.mentions) == 0:
            try:
                user = self.bot.get_user(int(user))
                if user is None:
                    return await ctx.send(
                        "I couldn't find that user.\n**Tip:** Mention them or use their id."
                    )
            except ValueError:
                return await ctx.send(
                    "I couldn't find that user.\n**Tip:** Mention them or use their id."
                )
        else:
            user = ctx.message.mentions[0]

        mydata = await self.bot.inventories.find(ctx.author.id)
        if mydata is None:
            return await ctx.send("You haven't initialized your inventory yet."
                                  )
        myinventory = mydata["inventory"]

        items = await self.bot.items.find("items")
        items = items["items"]

        yourdata = await self.bot.inventories.find(user.id)
        if yourdata is None:
            return await ctx.send(
                "This user hasn't initialized their inventory yet.")
        yourinventory = yourdata["inventory"]

        if user.id == ctx.author.id or item1 == item2:
            return await ctx.send("That's pointless.")

        if item1.lower() not in items:
            return await ctx.send("That item does not exist.")
        if item2.lower() not in items:
            return await ctx.send("That item does not exist.")

        item1 = items[item1.lower()]
        name1, emoji1 = item1["name"], item1["emoji"]
        item2 = items[item2.lower()]
        name2, emoji2 = item2["name"], item2["emoji"]
        myinventory = mydata["inventory"]
        yourinventory = yourdata["inventory"]

        found = False
        for i in myinventory:
            if i["name"] == name1:
                if i["locked"]:
                    return await ctx.send(
                        f"**{emoji1} {name1}** is locked in your inventory.")
                found = True
        if not found:
            return await ctx.send(
                f"You don't have a **{emoji1} {name1}** in your inventory.")

        found = False
        for i in yourinventory:
            if i["name"] == name2:
                if i["locked"]:
                    return await ctx.send(
                        f"**{emoji2} {name2}** is locked in {user.name}'s inventory."
                    )
                found = True
        if not found:
            return await ctx.send(
                f"{user.name} doesn't have a **{emoji2} {name2}** in their inventory."
            )

        created = False
        while not created:
            tradeid = random.randint(100, 999)
            trade = await self.bot.trades.find(tradeid)
            if trade is None:
                created = True

        dict = {}
        offered = item1["name"].replace(" ", "").lower()
        desired = item2["name"].replace(" ", "").lower()
        dict["offerer"], dict["offereditem"], dict["desireditem"], dict[
            "receiver"], dict[
                "completed"] = ctx.author.id, offered, desired, user.id, False
        await self.bot.trades.upsert({"_id": tradeid, "trade": dict})

        embed = discord.Embed(
            title=
            f"Trade Request for **{user.name}** from **{ctx.author.name}**",
            description=
            f"TradeID: `{tradeid}`\n\n**Offering: {emoji1} {name1}**\n**For: {emoji2} {name2}**\n\nTo accept: `{self.bot.prefix}taccept {tradeid}`\nExpires in 30 minutes",
            color=discord.Color.gold())
        await ctx.send(embed=embed)
        try:
            await user.send(
                f"You have a trade request! Do `{self.bot.prefix}taccept {tradeid}` in dms or in any channel I have acces to."
            )
            await user.send(embed=embed)
        except Forbidden:
            await ctx.send("Messaging user failed.")
        await asyncio.sleep(60 * 30)
        dict["completed"] = True
        await self.bot.trades.upsert({"_id": int(tradeid), "trade": dict})
示例#9
0
async def help_me(ctx):
        """Отправляет сведения о некоторых коммандах (может в личку)"""
        emb = discord.Embed(title= "Info about commands", colour=0x39d0d6)
        emb.add_field(name= "{}help".format(prefix), value= "Show this embed")
        emb.add_field(name= "{}hello".format(prefix), value= "Answer me")
        await ctx.send(embed=emb)               # вывод на канал
示例#10
0
    async def albuminfo(self, ctx, *, arg=None):
        async with ctx.typing():
            
            username = db.get_user(ctx.author.id)

            if username is None:
                embed = discord.Embed(description = f"You need to first set your Last.fm username with the command\n`>set [your username]`", colour = 0x4a5fc3)
                return await ctx.send(embed=embed)

            lastfm_username = username [0][1];
            if not lastfm_username:
                embed = discord.Embed(description = f"You need to first set your Last.fm username with the command\n`>set [your username]`", colour = 0x4a5fc3)
                return await ctx.send(embed=embed)

            if arg is None:
                recent_tracks_params = {
                    "limit": "1",
                    "user": lastfm_username,
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "user.getRecentTracks"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/", params=recent_tracks_params)
                rtdata = r.json()
                await asyncio.sleep(0.25)
                rtinfo = rtdata["recenttracks"]["track"][0]
                album_cover = rtinfo["image"][-1]["#text"]
                actual_artist = rtinfo["artist"]["#text"]
                actual_album = rtinfo["album"]["#text"]

                album_info_params = {
                    "artist": actual_artist,
                    "album": actual_album,
                    "autocorrect": "1",
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "album.getInfo"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/", params=album_info_params)
                abidata = r.json()
            else:
                artist, album = arg.split("|")
                params = {
                    "artist": artist.strip(),
                    "album": album.strip(),
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "album.getInfo"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/", params=params)
                abidata = r.json()
                await asyncio.sleep(0.25)

            try:
                actual_artist = abidata["album"]["artist"]
            except KeyError:
                return await ctx.send(embed = discord.Embed(description = f"This artist's album doesn't exist.", colour = 0x4a5fc3))
            try:
                album_info = abidata["album"]["wiki"]["content"]
            except KeyError:
                album_info = ""


            actual_album = abidata["album"]["name"]
            album_url = abidata["album"]["url"]
            album_cover = abidata["album"]["image"][-1]["#text"]
            try:
                album_tags = [tag["name"] for tag in abidata["album"]["tags"]["tag"]]
            except TypeError:
                album_tags = ""
            album_tags_string = " ∙ ".join(album_tags)

            album_info = album_info.strip()
            sep = "<a"
            album_info = album_info.split(sep, 1)[0]
            if len(album_info)>800:
                album_info = album_info[:800] + "..."

            embed = discord.Embed(
            colour = 0x4a5fc3
            )

            embed.set_author(name=f"Album info for {lastfm_username} about {actual_artist} - {actual_album}")
            if album_cover is not None:
                embed.set_thumbnail(url=f"{album_cover}")
            if album_info != "":
                embed.add_field(name=f"Summary", value=f"{album_info}", inline=False)
            if album_info == "":
                embed.add_field(name=f"Summary", value=f"*No summary exists for this album.*", inline=False)
            if album_url is not None:
                embed.add_field(name="\u200b", value=f"[Link to the site]({album_url})")
            if album_tags is not None:
                embed.set_footer(text=f"{album_tags_string.lower()}")

        await ctx.send(embed=embed)
示例#11
0
    async def taccept(self, ctx, tradeid):
        trade = await self.bot.trades.find(int(tradeid))

        if trade is None:
            return await ctx.send("That is not a valid TradeID.")

        trade = trade["trade"]
        if trade["completed"]:
            return await ctx.send(
                "Trade has already been completed, it was cancelled by the offerer or it has expired."
            )

        items = await self.bot.items.find("items")
        items = items["items"]

        if ctx.author.id != trade["receiver"]:
            return await ctx.send("This trade isn't meant for you.")

        offererid = trade["offerer"]
        try:
            offerer = self.bot.get_user(offererid)
        except Exception:
            trade["completed"] = True
            await self.bot.trades.upsert({"_id": int(tradeid), "trade": trade})
            return await ctx.send(
                "Something went wrong when trying to find offerer, cancelling trade..."
            )

        rdata = await self.bot.inventories.find(ctx.author.id)
        if rdata is None:
            trade["completed"] = True
            await self.bot.trades.upsert({"_id": int(tradeid), "trade": trade})
            return await ctx.send("Database error")
        rinventory = rdata["inventory"]

        odata = await self.bot.inventories.find(offererid)
        if odata is None:
            trade["completed"] = True
            await self.bot.trades.upsert({"_id": int(tradeid), "trade": trade})
            return await ctx.send("Database error")
        oinventory = odata["inventory"]

        oitem = items[trade["offereditem"]]
        oname, oemoji = oitem["name"], oitem["emoji"]
        ditem = items[trade["desireditem"]]
        dname, demoji = ditem["name"], ditem["emoji"]

        found = False
        for i in oinventory:
            if i["name"] == oname:
                if i["locked"]:
                    trade["completed"] = True
                    await self.bot.trades.upsert({
                        "_id": int(tradeid),
                        "trade": trade
                    })
                    return await ctx.send(
                        f"**{oemoji} {oname}** has been locked in their inventory."
                    )
                elif i["quantity"] != 1:
                    i["quantity"] -= 1
                else:
                    oinventory.remove(i)
                found = True
        if not found:
            trade["completed"] = True
            await self.bot.trades.upsert({"_id": int(tradeid), "trade": trade})
            return await ctx.send(
                f"Trader doesn't have **{oemoji} {oname}** anymore.")

        found = False
        for i in rinventory:
            if i["name"] == dname:
                if i["locked"]:
                    trade["completed"] = True
                    await self.bot.trades.upsert({
                        "_id": int(tradeid),
                        "trade": trade
                    })
                    return await ctx.send(
                        f"**{demoji} {dname}** has been locked in your inventory."
                    )
                elif i["quantity"] != 1:
                    i["quantity"] -= 1
                else:
                    rinventory.remove(i)
                found = True
        if not found:
            trade["completed"] = True
            await self.bot.trades.upsert({"_id": int(tradeid), "trade": trade})
            return await ctx.send(
                f"You don't have a **{demoji} {dname}** anymore.")

        # Give ditem to oinventory
        item = items[dname.replace(" ", "").lower()]
        given = False
        for i in oinventory:
            if i["name"] == dname:
                i["quantity"] += 1
                given = True

        if not given:
            del item["emoji"], item["value"]
            item["locked"] = False
            item["quantity"] = 1
            oinventory.append(item)

        # Give oitem to rinventory
        item = items[oname.replace(" ", "").lower()]
        given = False
        for i in rinventory:
            if i["name"] == oitem:
                i["quantity"] += 1
                given = True

        if not given:
            del item["emoji"], item["value"]
            item["locked"] = False
            item["quantity"] = 1
            rinventory.append(item)

        await self.bot.inventories.upsert({
            "_id": offererid,
            "inventory": oinventory
        })
        await self.bot.inventories.upsert({
            "_id": ctx.author.id,
            "inventory": rinventory
        })
        trade["completed"] = True
        await self.bot.trades.upsert({"_id": int(tradeid), "trade": trade})
        embed = discord.Embed(
            title=f"Trade {tradeid} Accepted",
            description=
            f"**{ctx.author.name}** gained **{oemoji} {oname}** from **{offerer.name}**\n**{offerer.name}** gained **{demoji} {dname}** from **{ctx.author.name}**",
            color=discord.Color.gold())
        await ctx.send(embed=embed)
        try:
            await offerer.send(embed=embed)
        except Forbidden:
            pass
示例#12
0
 async def crypto_embed(
     self,
     ctx: commands.Context,
     coin: str,
     ammount: float = 1.0,
     currency: str = "USD",
     full: bool = True,
 ) -> Optional[Union[str, discord.Embed]]:
     """Creates the embed for the crypto currency"""
     coin_data = await self.checkcoins(coin)
     if coin_data is None:
         await ctx.send("{} is not in my list of currencies!".format(coin))
         return None
     coin_colour = {
         "Bitcoin": discord.Colour.gold(),
         "Bitcoin Cash": discord.Colour.orange(),
         "Ethereum": discord.Colour.dark_grey(),
         "Litecoin": discord.Colour.dark_grey(),
         "Monero": discord.Colour.orange(),
     }
     price = float(coin_data["quotes"]["USD"]["price"]) * ammount
     market_cap = float(coin_data["quotes"]["USD"]["market_cap"])
     volume_24h = float(coin_data["quotes"]["USD"]["volume_24h"])
     coin_image = "https://s2.coinmarketcap.com/static/img/coins/128x128/{}.png".format(
         coin_data["id"])
     coin_url = "https://coinmarketcap.com/currencies/{}".format(
         coin_data["id"])
     if currency.upper() != "USD":
         conversionrate = await self.conversionrate("USD", currency.upper())
         if conversionrate:
             price = conversionrate * price
             market_cap = conversionrate * market_cap
             volume_24h = conversionrate * volume_24h
     msg = "{0} {3} is **{1:,.2f} {2}**".format(ammount, price,
                                                currency.upper(),
                                                coin_data["symbol"])
     embed = discord.Embed(description=msg,
                           colour=discord.Colour.dark_grey())
     if coin_data["name"] in coin_colour:
         embed.colour = coin_colour[coin_data["name"]]
     embed.set_footer(text="As of")
     embed.set_author(name=coin_data["name"],
                      url=coin_url,
                      icon_url=coin_image)
     embed.timestamp = datetime.datetime.utcfromtimestamp(
         int(coin_data["last_updated"]))
     if full:
         hour_1 = coin_data["quotes"]["USD"]["percent_change_1h"]
         hour_24 = coin_data["quotes"]["USD"]["percent_change_24h"]
         days_7 = coin_data["quotes"]["USD"]["percent_change_7d"]
         hour_1_emoji = "🔼" if hour_1 >= 0 else "🔽"
         hour_24_emoji = "🔼" if hour_24 >= 0 else "🔽"
         days_7_emoji = "🔼" if days_7 >= 0 else "🔽"
         available_supply = "{0:,.2f}".format(
             coin_data["circulating_supply"])
         try:
             max_supply = "{0:,.2f}".format(coin_data["max_supply"])
         except KeyError:
             max_supply = "\N{INFINITY}"
         total_supply = "{0:,.2f}".format(coin_data["total_supply"])
         embed.set_thumbnail(url=coin_image)
         embed.add_field(name="Market Cap",
                         value="{0:,.2f} {1}".format(
                             market_cap, currency.upper()))
         embed.add_field(name="24 Hour Volume",
                         value="{0:,.2f} {1}".format(
                             volume_24h, currency.upper()))
         embed.add_field(name="Available Supply", value=available_supply)
         if max_supply is not None:
             embed.add_field(name="Max Supply", value=max_supply)
         embed.add_field(name="Total Supply ", value=total_supply)
         embed.add_field(name="Change 1 hour " + hour_1_emoji,
                         value="{}%".format(hour_1))
         embed.add_field(name="Change 24 hours " + hour_24_emoji,
                         value="{}%".format(hour_24))
         embed.add_field(name="Change 7 days " + days_7_emoji,
                         value="{}%".format(days_7))
     if not ctx.channel.permissions_for(ctx.me).embed_links:
         if full:
             return (
                 f"{msg}\nMarket Cap: **{market_cap}**\n"
                 f"24 Hour Volume: **{volume_24h}**\nAvailable Supply: **{available_supply}**\n"
                 f"Max Supply: **{max_supply}**\nTotal Supply: **{total_supply}**\n"
                 f"Change 1 hour{hour_1_emoji}: **{hour_1}%**\n"
                 f"Change 24 hours{hour_24_emoji}: **{hour_24}%**\n"
                 f"Change 7 days{days_7_emoji}: **{days_7}%**\n")
         else:
             return msg
     else:
         return embed
示例#13
0
    async def invoke_controller(self, track: wavelink.Track = None):
        """Invoke our controller message, and spawn a reaction controller if one isn't alive."""
        if not track:
            track = self.current

        if track.title == 'Unknown title':
            return

        self.updating = True

        embed = discord.Embed(
            title='Music Controller',
            description=
            f'<a:eq:557312295340998687> Now Playing:```ini\n{track.title}\n\n'
            f'[EQ]: {self.eq}\n'
            f'[Presets]: Flat/Boost/Piano/Metal```',
            colour=0xffb347)
        embed.set_thumbnail(url=track.thumb)

        if track.is_stream:
            embed.add_field(name='Duration', value='🔴`Streaming`')
        else:
            embed.add_field(
                name='Duration',
                value=str(datetime.timedelta(milliseconds=int(track.length))))
        embed.add_field(name='Author', value=f'{track.author}')
        embed.add_field(name='Requested By', value=track.requester.mention)
        embed.add_field(name='Current DJ', value=self.dj.mention)
        embed.add_field(name='Queue Length', value=str(len(self.entries)))
        embed.add_field(name='Volume', value=f'**`{self.volume}%`**')

        if len(self.entries) > 0:
            data = '\n'.join(
                f'**-** `{t.title[0:45]}{"..." if len(t.title) > 45 else ""}`\n{"-"*10}'
                for t in itertools.islice(
                    [e for e in self.entries if not e.is_dead], 0, 3, None))
            embed.add_field(name='Coming Up:', value=data, inline=False)

        if not await self.is_current_fresh(track.channel
                                           ) and self.controller_message:
            try:
                await self.controller_message.delete()
            except discord.HTTPException:
                pass

            self.controller_message = await track.channel.send(embed=embed)
        elif not self.controller_message:
            self.controller_message = await track.channel.send(embed=embed)
        else:
            self.updating = False
            await self.controller_message.edit(embed=embed, content=None)

        try:
            await self.controller_message.pin()
        except discord.HTTPException:
            pass

        if not self.updating:
            return

        try:
            self.reaction_task.cancel()
        except Exception:
            pass

        self.reaction_task = self.bot.loop.create_task(
            self.reaction_controller())
        self.updating = False
示例#14
0
async def leaderboard(ctx, mixed=1, page_alt=1, **details):
    """
    [CMD_KEY]leaderboard (page)
    or for global ranks
    [CMD_KEY]leaderboard global (page)
    [CMD_KEY]globalranks (page)
    
    The global leaderboard of DueUtil!
    
    The leaderboard updated every hour, but it may be longer.
    
    **Now with local**.
    [PERM]
    """

    page_size = 10

    # Handle weird page args
    if type(mixed) is int:
        page = mixed - 1
        local = True
        ranks = "local"
    else:
        local = mixed.lower() != "global"
        ranks = "local" if local else "global"
        page = page_alt - 1

    # Local/Global
    if local:
        title = "DueUtil Leaderboard on %s" % details["server_name_clean"]
        # Cached.
        local_leaderboard = leaderboards.get_local_leaderboard(ctx.server, "levels")
        leaderboard_data = local_leaderboard.data
        last_updated = local_leaderboard.updated
    else:
        title = "DueUtil Global Leaderboard"
        leaderboard_data = leaderboards.get_leaderboard("levels")
        last_updated = leaderboards.last_leaderboard_update

    if leaderboard_data is None or len(leaderboard_data) == 0:
        await util.say(ctx.channel, "The %s leaderboard has yet to be calculated!\n" % ranks
                       + "Check again soon!")
        return

    leaderboard_embed = discord.Embed(title="%s %s" % (emojis.QUESTER, title),
                                      type="rich", color=gconf.DUE_COLOUR)

    if page > 0:
        leaderboard_embed.title += ": Page %d" % (page + 1)
    if page * page_size >= len(leaderboard_data):
        raise util.DueUtilException(ctx.channel, "Page not found")

    index = 0
    for index in range(page_size * page, page_size * page + page_size):
        if index >= len(leaderboard_data):
            break
        bonus = ""
        if index == 0:
            bonus = "     :first_place:"
        elif index == 1:
            bonus = "     :second_place:"
        elif index == 2:
            bonus = "     :third_place:"
        player = players.find_player(leaderboard_data[index])
        user_info = ctx.server.get_member(player.id)
        if user_info is None:
            user_info = player.id
        leaderboard_embed \
            .add_field(name="#%s" % (index + 1) + bonus,
                       value="[%s **``Level %s``**](https://dueutil.org/player/id/%s) (%s) | **Total EXP** %d"
                             % (player.name_clean, player.level, player.id,
                                util.ultra_escape_string(str(user_info)), player.total_exp), inline=False)

    if index < len(leaderboard_data) - 1:
        remaining_players = len(leaderboard_data) - page_size * (page + 1)
        leaderboard_embed.add_field(name="+%d more!" % remaining_players,
                                    value="Do ``%sleaderboard%s %d`` for the next page!"
                                          % (details["cmd_key"], "" if local else " global", page + 2), inline=False)
    leaderboard_embed.set_footer(text="Leaderboard calculated "
                                      + repoze.timeago.get_elapsed(datetime.utcfromtimestamp(last_updated)))
    await util.say(ctx.channel, embed=leaderboard_embed)
示例#15
0
    async def albumcover(self, ctx, *, arg=None):
        async with ctx.typing():

            username = db.get_user(ctx.author.id)

            if username is None:
                embed = discord.Embed(
                    description=
                    f"You need to first set your Last.fm username with the command\n`>set [your username]`",
                    colour=0x4a5fc3)
                return await ctx.send(embed=embed)

            lastfm_username = username[0][1]
            if not lastfm_username:
                embed = discord.Embed(
                    description=
                    f"You need to first set your Last.fm username with the command\n`>set [your username]`",
                    colour=0x4a5fc3)
                return await ctx.send(embed=embed)

            if arg is None:
                recent_tracks_params = {
                    "limit": "1",
                    "user": lastfm_username,
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "user.getRecentTracks"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/",
                                 params=recent_tracks_params)
                rtdata = r.json()
                rtinfo = rtdata["recenttracks"]["track"][0]
                artist = rtinfo["artist"]["#text"]
                album = rtinfo["album"]["#text"]

                album_info_params = {
                    "artist": artist,
                    "album": album,
                    "autocorrect": "1",
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "album.getInfo"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/",
                                 params=album_info_params)
                abidata = r.json()
            else:
                try:
                    artist, album = arg.split("|")
                except:
                    return await ctx.send(embed=discord.Embed(
                        description="Use the format `artist | album`.",
                        colour=0x4a5fc3))
                album_info_params = {
                    "artist": artist.strip(),
                    "album": album.strip(),
                    "autocorrect": "1",
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "album.getInfo"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/",
                                 params=album_info_params)
                abidata = r.json()

            actual_artist = abidata["album"]["artist"]
            actual_album = abidata["album"]["name"]
            api_album_cover = abidata["album"]["image"][-1]["#text"]
            no_file_type_album_cover = api_album_cover.rsplit(".", 1)[0]
            higher_res_album_cover = no_file_type_album_cover.replace(
                "300x300", "700x0", 1)

            try:
                album_url = abidata["album"]["url"]
            except KeyError:
                album_url = ""

            try:
                album_cover = abidata["album"]["image"][-1]["#text"]
            except KeyError:
                embed = discord.Embed(
                    description=
                    f"**{actual_artist} - [{actual_album}]({album_url})**\n\n*No cover exists for this album.*",
                    timestamp=datetime.now() - timedelta(hours=2),
                    colour=0x4a5fc3)
                embed.set_footer(
                    text=
                    f"Requested by {ctx.author.name}#{ctx.author.discriminator}"
                )

            if album_cover == "":
                embed = discord.Embed(
                    description=
                    f"**{actual_artist} - [{actual_album}]({album_url})**\n\n*No cover exists for this album.*",
                    timestamp=datetime.now() - timedelta(hours=2),
                    colour=0x4a5fc3)
                embed.set_footer(
                    text=
                    f"Requested by {ctx.author.name}#{ctx.author.discriminator}"
                )
            else:
                embed = discord.Embed(
                    description=
                    f"**{actual_artist} - [{actual_album}]({album_url})**",
                    timestamp=datetime.now() - timedelta(hours=2),
                    colour=0x4a5fc3)
                embed.set_image(url=f"{higher_res_album_cover}")
            embed.set_footer(
                text=
                f"Requested by {ctx.author.name}#{ctx.author.discriminator}")

        await ctx.send(embed=embed)
示例#16
0
文件: Tina.py 项目: AiAe/Tina
def make_message(api):
    osu_api = osu.bid(api["beatmap_id"])

    if osu_api == None:
        print("Blame peppy got api error...")
        return

    formatter = {
        "performance_new": "{}".format(api["new_player"]["performance"]),
        "personal_top": api["personal_top"],
        "mode": ConvertMods.convertMode(api["mode"]),
        "global_rank": api["new_player"]["rank"],
        "country": api["country"],
        "country_rank": api["new_player"]["country_rank"],
        "performance": "{:.2f}".format(api["new_score"]["performance"]),
        "combo": api["new_score"]["max_combo"],
        "max_combo": osu_api[0]["max_combo"],
        "rank": api["new_score"]["rank"],
        "stars": "{:.2f}".format(float(osu_api[0]["difficultyrating"])),
        "score": "{:,d}".format(api["new_score"]["score"]),
        "accuracy": "{:.2f}".format(api["new_score"]["accuracy"]),
        "mods": ConvertMods.ModsRev(api["new_score"]["mods"]),
        "artist": osu_api[0]["artist"],
        "title": osu_api[0]["title"],
        "version": osu_api[0]["version"],
        "sid": osu_api[0]["beatmapset_id"],
        "userid": api["user_id"],
        "username": api["username"],
        "bid": api["beatmap_id"],
        "length": strftime("%M:%S", gmtime(int(osu_api[0]["total_length"]))),
        "bpm": osu_api[0]["bpm"]
    } # in bpm, length, stars: consider accounting for DT and HT

    if api["old_player"]:
        gain = api["new_player"]["performance"] - api["old_player"]["performance"]
        grankgain = api["new_player"]["rank"] - api["old_player"]["rank"]
        crankgain = api["new_player"]["country_rank"] - api["old_player"]["country_rank"]

        formatter["ppgain"] = "%+d"%gain
        formatter["grankgain"] = "%+d"%grankgain
        formatter["crankgain"] = "%+d"%crankgain
    else:
        formatter["ppgain"] = "+0"
        formatter["grankgain"] = "+0"
        formatter["crankgain"] = "+0"

    if api["new_score"]["performance"]:
        new_score = "__New score! **{performance}pp** • #{personal_top} personal best__\n"
    else:
        new_score = "__New score! **User has a better score on this map"
        if api["old_score"] and api["old_score"]["score"] > formatter["score"]:
            old_stuff = {
                "old_combo": api["old_score"]["max_combo"],
                "old_rank": api["old_score"]["rank"],
                "old_score": "{:,d}".format(api["old_score"]["score"]),
                "old_accuracy": "{:.2f}".format(api["old_score"]["accuracy"]),
                "old_mods": ConvertMods.ModsRev(api["old_score"]["mods"]),
                "max_combo": osu_api[0]["max_combo"]
            }
            new_score += ":**__\n**▸ Combo {old_combo} / {max_combo} • Rank {old_rank} • Score {old_score} • Accuracy {old_accuracy}% • Mods {old_mods}**\n".format(**old_stuff)
        else:
            new_score += "**__\n"
    new_score += "▸ Mode {mode} • Global #{global_rank} ({grankgain})• {country} #{country_rank} ({crankgain}) • PP {performance_new} ({ppgain})\n"
    new_score += "▸ Combo {combo} / {max_combo} • Rank {rank} • Score {score} • Accuracy {accuracy}% • Mods {mods}\n"
    new_score += "[{artist} - {title} [{version}]](https://osu.ppy.sh/b/{bid})\n▸ {length} • {bpm}BPM • **{stars}★**\n"

    new_score = new_score.format(**formatter)

    if formatter["personal_top"] == 1:
      e = discord.Embed(title="",
                        url="https://ripple.moe/u/{}".format(
                            api["user_id"]),
                        colour=0xf1c40f,
                        description="{}".format(new_score))
    elif formatter["personal_top"] == 2:
      e = discord.Embed(title="",
                        url="https://ripple.moe/u/{}".format(
                            api["user_id"]),
                        colour=0xcccccc,
                        description="{}".format(new_score))
    elif formatter["personal_top"] == 3:
      e = discord.Embed(title="",
                        url="https://ripple.moe/u/{}".format(
                            api["user_id"]),
                        colour=0xcd7f32,
                        description="{}".format(new_score))
    else:
      e = discord.Embed(title="",
                        url="https://ripple.moe/u/{}".format(
                            api["user_id"]),
                        colour=0x4F545C,
                        description="{}".format(new_score))

    e.set_thumbnail(
      url="https://b.ppy.sh/thumb/{sid}.jpg".format(**formatter))

    e.set_author(name='{username}'.format(**formatter),
               icon_url="https://a.ripple.moe/{userid}".format(**formatter))

    e.set_footer(text="{}".format(strftime("%d.%m.%Y at %H:%M", gmtime())))

    return e
示例#17
0
 async def pixiv(self, ctx, *args):
     '''
     P站图片,支持关键词
     格式是[数量][*|R18|ALL][关键词]
     其他方式是[数量]|[*|R18|ALL]|[关键词]
     或者是[数量]|[*|R18|ALL] [关键词]
     不加参数默认输出1份全年龄随机图片
     有时候全年龄会出有R18标签的作品
     '''
     num = 1
     r18 = ''
     keyword = ''
     if len(args) == 0:
         pass
     elif len(args) == 1:
         if args[0] in ['r18', 'R18', 'ALL', 'all']:
             r18 = args[0]
         else:
             try:
                 type(eval(args[0]))
                 num = eval(args[0])
             except:
                 keyword = args[0]
     elif len(args) == 2:
         try:
             num = eval(args[0])
         except:
             r18 = args[0]
         keyword = args[1]
     else:
         try:
             type(eval(args[0]))
             num = eval(args[0])
             r18 = args[1]
             keyword = args[2]
         except:
             r18 = args[1]
             keyword = args[2]
     if num > 5:
         num = 5
     elif num < 1:
         num = 1
     if r18 == 'r18' or r18 == 'R18':
         r18 = 1
     elif r18 == 'all' or r18 == 'ALL':
         r18 = 2
     else:
         r18 = 0
     try:
         apikey = os.environ["loliconAPI_key"]
     except:
         apikey = ''
     params = {
         "apikey": apikey,
         "r18": r18,
         "size1200": False,
         "num": num,
         "keyword": keyword
     }
     web = requests.get('https://api.lolicon.app/setu/',
                        params=params).json()
     if web['code'] != 0:
         await ctx.send(web['msg'])
     else:
         for i in range(0, num):
             url = web['data'][i]['url']
             embed_box = discord.Embed(
                 title=
                 f"{web['data'][i]['title']}-{web['data'][i]['author']}",
                 description=OutputTags(web['data'][i]['tags']),
                 url=
                 f"https://www.pixiv.net/artworks/{str(web['data'][i]['pid'])}"
             )
             embed_box.set_image(url=url)
             await ctx.send(embed=embed_box)
     return
示例#18
0
文件: code.py 项目: TheEle720/-
async def on_message(message):
    if message.author.bot:
        return None

    if message.content.startswith('엘봇아 도움'):
         embed=discord.Embed(title="DM을 확인해주세요.", color=0xff0000)
         embed.add_field(name="DM으로메세지가 전송됩니다.", value="만약 전송이 안되신다면 개인정보 및 보안을 낮음으로 설정해주세요.", inline=True)
         await message.channel.send(embed=embed)
         author = message.guild.get_member(int(message.author.id))
         embed=discord.Embed(title="엘봇명령어 목록", description=None, color=0x00a9f7)
         embed.add_field(name="깜찍한엘봇 명령어", value="`,경고목록` `,신고목록", inline=False)
         embed.add_field(name="관리자", value="미공개", inline=False)
         embed.add_field(name="대화", value="`안녕 엘봇`, '잘가 엘봇', '엘봇 바보'" , inline=False)
         embed.add_field(name="정보", value="`,정보` `,서버정보` `,현재시간`", inline=False)
         embed.add_field(name="놀이", value="`가위바위보 `,  `,숫자게임`", inline=False)
         embed.add_field(name="봇", value="`-봇제작자`", inline=False)
         await author.send(embed=embed)

    if message.content.startswith('엘봇아 안녕'):
        await message.channel.send("반가워")

    if message.content.startswith('엘봇아 잘가'):
        await message.channel.send("또 보자!!")

    if message.content.startswith('엘봇이 바보'):
        await message.channel.send("흥칫뿡 너랑 안 놀아!")

    if message.content.startswith('엘봇아 업로드해줘'):
        pic = message.content.split(" ")[1]
        await message.channel.send(file=discord.File(pic))

    if message.content.startswith('엘봇아 메세지보내줘'):
        channel = message.content[7:25]
        msg = message.content[26:]
        await client.get_channel(int(channel)).send(msg)

    if message.content.lower().startswith("엘봇아 내정보"):
        date = datetime.datetime.utcfromtimestamp(((int(message.author.id) >> 22) + 1420070400000) / 1000)
        emb = discord.Embed(title='정보[info]', color=0x00ff00)
        emb.add_field(name="이름", value=message.author.name, inline=True)
        emb.add_field(name="서버정보", value=message.author.display_name, inline=True)
        emb.add_field(name="가입일", value=str(date.year) + "년" + str(date.month) + "월" + str(date.day) + "일", inline=True)
        emb.add_field(name="아이디", value=message.author.id, inline=True)
        emb.set_thumbnail(url=message.author.avatar_url)
        await message.channel.send(content=None, embed=emb)

    if message.content.lower().startswith('엘봇아 갓챠'):
        if message.channel.id == 603392454036684802:
            Image_captca = ImageCaptcha()
            a = ""
            for i in range(6):
                a += str(random.randint(0, 9))
            name = str(message.author.id) + ".png"
            Image_captca.write(a, name)

            await message.channel.send(file=discord.File(name))
            def check(msg):
                return msg.author == message.author and msg.channel == message.channel

            try:
                msg = await client.wait_for("message", timeout=10, check=check)
            except:
                emb = discord.Embed(title='시간이 초과되었습니다. 다시 `인증`을 입력해주세요.', color=0x1d6bda)
                await message.channel.send(content=None, embed=emb)
                return

            if msg.content == a:
                emb = discord.Embed(title='인증이 완료되었습니다.', color=0x1d6bda)
                await message.channel.send(content=None, embed=emb)
            else:
                emb = discord.Embed(title='오답입니다. 다시 `인증`을 입력해주세요.', color=0x1d6bda)
                await message.channel.send(content=None, embed=emb)
        else:
            emb = discord.Embed(title='이 채널에서는 사용할수없는 명령어입니다.', color=0x1d6bda)
            await message.channel.send(content=None, embed=emb)

    if message.content.lower().startswith("엘봇아 현재시간"):
        a = datetime.datetime.today().year
        b = datetime.datetime.today().month
        c = datetime.datetime.today().day
        d = datetime.datetime.today().hour
        e = datetime.datetime.today().minute
        f = datetime.datetime.today().second
        emb = discord.Embed(title='현재시간[Time]', color=0xffbf00)
        emb.add_field(name=str(a) + "년 " +  str(b) + "월 " + str(c) + "일 " + str(d) + "시 " + str(e) + "분 " + str(f) + "초 입니다.", value='[Korea]', inline=False)
        await message.channel.send(content=None, embed=emb)

    if message.content.lower().startswith(",서버정보"):
        date = datetime.datetime.utcfromtimestamp(((int(message.guild.id) >> 22) + 1420070400000) / 1000)
        emb = discord.Embed(title='서버정보[Severinfo]', color=0x00ff00)
        emb.add_field(name="이름", value=message.guild.name, inline=True)
        emb.add_field(name="생성일", value=str(date.year) + "년" + str(date.month) + "월" + str(date.day) + "일", inline=True)
        emb.add_field(name="아이디", value=message.guild.id, inline=True)
        emb.add_field(name="자기정보", value=message.author.display_name, inline=True)
        emb.set_thumbnail(url=message.guild.icon_url)
        await message.channel.send(content=None, embed=emb)


    if message.content.startswith("엘봇아 가위바위보 가위"):
        rsp = "123"
        rsp1 = random.choice(rsp)
        if rsp1 == "1":
            emb = discord.Embed(title='가위바위보', color=0xfff000)
            emb.add_field(name='결과', value='봇 :v: 당신 :v: 무승부!')
            await message.channel.send(content=None, embed=emb)
        if rsp1 == "2":
            emb = discord.Embed(title='가위바위보', color=0xff0000)
            emb.add_field(name='결과', value='봇 :fist: 당신 :v: 봇 승리!')
            await message.channel.send(content=None, embed=emb)
        if rsp1 == "3":
            emb = discord.Embed(title='가위바위보', color=0x0dff00)
            emb.add_field(name='결과', value='봇 :raised_hand: 당신 :v: 당신 승리!')
            await message.channel.send(content=None, embed=emb)
    if message.content.startswith("엘봇아 가위바위보 바위"):
        rsp = "123"
        rsp1 = random.choice(rsp)
        if rsp1 == "1":
            emb = discord.Embed(title='가위바위보', color=0x0dff00)
            emb.add_field(name='결과', value='봇 :v: 당신 :fist: 당신 승리!')
            await message.channel.send(content=None, embed=emb)
        if rsp1 == "2":
            emb = discord.Embed(title='가위바위보', color=0xfff000)
            emb.add_field(name='결과', value='봇 :fist: 당신 :fist: 무승부!')
            await message.channel.send(content=None, embed=emb)
        if rsp1 == "3":
            emb = discord.Embed(title='가위바위보', color=0xff0000)
            emb.add_field(name='결과', value='봇 :raised_hand: 당신 :fist: 봇 승리!')
            await message.channel.send(content=None, embed=emb)

    if message.content.startswith("엘봇아 가위바위보 보"):
        rsp = "123"
        rsp1 = random.choice(rsp)
        if rsp1 == "1":
            emb = discord.Embed(title='가위바위보', color=0xff0000)
            emb.add_field(name='결과', value='봇 :v: 당신 :raised_hand: 봇 승리!')
            await message.channel.send(content=None, embed=emb)
        if rsp1 == "2":
            emb = discord.Embed(title='가위바위보', color=0x0dff00)
            emb.add_field(name='결과', value='봇 :fist: 당신 :raised_hand: 당신 승리!')
            await message.channel.send(content=None, embed=emb)
        if rsp1 == "3":
            emb = discord.Embed(title='가위바위보', color=0xfff000)
            emb.add_field(name='결과', value='봇 :raised_hand: 당신 :v: 무승부!')
            await message.channel.send(content=None, embed=emb)

    if message.content.startswith(',숫자게임'):
        number = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
        botnumber = random.sample(number, 3)
        mynumber = random.sample(number, 3)
        emb = discord.Embed(title='숫자게임', color=0x0016ff)
        emb.add_field(name='결과', value='봇의 숫자' + str(botnumber) + '당신의 숫자' + str(mynumber), inline=False)
        await message.channel.send(content=None, embed=emb)
        if botnumber == mynumber:
            emb = discord.Embed(title='숫자게임', color=0xfff000)
            emb.add_field(name='승자',value='봇의 숫자' + str(botnumber, 3) + '당신의 숫자' + str(mynumber, 3) + '이므로 무승부!',inline=False)
            await message.channel.send(content=None, embed=emb)
        if botnumber > mynumber:
            emb = discord.Embed(title='숫자게임', color=0xff0000)
            emb.add_field(name='승자',value='봇의 숫자' + str(botnumber) + '당신의 숫자' + str(mynumber) + '이므로 봇의 승리!',inline=False)
            await message.channel.send(content=None, embed=emb)
        else:
            emb = discord.Embed(title='숫자게임', color=0x0dff00)
            emb.add_field(name='승자', value='봇의 숫자' + str(botnumber) + '당신의 숫자' + str(mynumber) + '이므로 당신의 승리!', inline=False)
            await message.channel.send(content=None, embed=emb)
示例#19
0
文件: worker.py 项目: sizumita/Sigma
 async def command(self, message: discord.Message, command: str, args: list, point: int):
     def pred(m):
         return m.author == message.author and m.channel == message.channel
     client = self.client
     if args[0] == "pp":
         await message.channel.send("市や県の名前や地名を入力してください。")
         try:
             ll = await client.wait_for('message', check=pred, timeout=30)
         except asyncio.TimeoutError:
             return False
         api = Yahoo_API()
         data = api.get_geocoder(ll.content, "json")
         ll_data = data.split(" ")
         weather = api.get_precipitation(ll_data[0], "json")["Feature"][0]["Property"]["WeatherList"]["Weather"]
         embed = discord.Embed(title="{}のこれからの降水確率".format(ll.content), description="これから60分の降水量(予測)を表示します")
         for x in range(7):
             embed.add_field(name="{}0分後".format(x), value=str(weather[x]["Rainfall"]) + "mm/h")
         await message.channel.send(embed=embed)
         return True
     if args[0] == "weather_yahoo":
         await message.channel.send("市や県の名前や地名を入力してください。")
         try:
             ll = await client.wait_for('message', check=pred, timeout=30)
         except asyncio.TimeoutError:
             return False
         api = Yahoo_API()
         data = api.get_geocoder(ll.content, "json")
         ll_data = data.split(" ")[0]
         base_ll_data = ll_data.split(",")
         weather_data = get_weather_forecast(base_ll_data[1], base_ll_data[0])
         embed = discord.Embed(title="{.content}のこれからの天気".format(ll), description="3時間ごとの天気を表示します")
         num = 0
         time = 0
         for sort_key in weather_data[1]:
             value = weather_data[0][sort_key]
             embed.add_field(name="{}時間後の天気".format(time), value=value, inline=False)
             num += 1
             time += 3
             if num == 10:
                 break
         await message.channel.send(embed=embed)
         return True
     if args[0] == "weather":
         await message.channel.send("市や県の名前を入力してください。")
         try:
             ll = await client.wait_for('message', check=pred, timeout=30)
         except asyncio.TimeoutError:
             return False
         data = get_weather(ll.content)
         if data['cod'] == '404':
             await message.channel.send("都市名が不明です。県や市などの言葉を削除し、地名も削除してください。\n"
                                        "また、ローマ字の地名にすることをお勧めします。例: 大阪 -> Osaka")
             return True
         weather = data['weather'][0]
         temp = data['main']
         wind = data['wind']
         embed = discord.Embed(title=f'{ll.content}の天気', description="------")
         embed.add_field(name="天気", value=weather['main'])
         embed.add_field(name="気温", value=str(temp['temp']) + "℃")
         embed.add_field(name="最低気温", value=str(temp['temp_min']) + "℃")
         embed.add_field(name="最高気温", value=str(temp['temp_max']) + "℃")
         embed.add_field(name="風速", value=str(wind['speed']) + "m/s")
         await message.channel.send(embed=embed)
         # await message.channel.send(data)
     if args[0] == "mscale":
         req = requests.get("http://weathernews.jp/mscale/mscale_json.cgi")
         await message.channel.send("今のMスケールは{}です。".format(req.json()['mscale'][1]))
         return True
     if args[0] == "taifu":
         req = requests.get("http://weathernews.jp/s/typhoon/cgi/typhoon_json.fcgi")
         data = req.json()
         if not data:
             await message.channel.send("台風情報はありません。")
             return True
         json_data = data[0]
         name = json_data["name"]  # 台風の名称
         comment_title = json_data["comment_title"]  # 台風chのトピック
         comment_body = json_data["comment_body"]  # 本文
         analized_date = json_data["analized_date"]  # 更新時刻
         date = json_data["details"][0]["date"]  # 現在情報
         location = json_data["details"][0]["location"]  # 現在位置
         latitude = json_data["details"][0]["latitude"]  # 現在位置 緯度
         longitude = json_data["details"][0]["longitude"]  # 現在位置 経度
         size = json_data["details"][0]["size"]  # 台風の大きさ
         strength = json_data["details"][0]["strength"]  # 台風の勢力
         direction = json_data["details"][0]["direction"]  # 台風の方向・速さ
         pressure = json_data["details"][0]["pressure"]  # 台風の中心気圧
         maxwind = json_data["details"][0]["maxwind"]  # 最大風速
         windgust = json_data["details"][0]["windgust"]  # 最大瞬間風速
         embed = discord.Embed(title="台風情報", color=0xeee657)
         embed.add_field(name="台風の名称", value=name, inline=False)
         embed.add_field(name="現在位置", value=location, inline=False)
         embed.add_field(name="座標", value=latitude + longitude)
         embed.add_field(name="大きさ", value=size)
         embed.add_field(name="勢力", value=strength)
         embed.add_field(name="方向・速さ", value=direction, inline=False)
         embed.add_field(name="中心気圧", value=pressure, inline=False)
         embed.add_field(name="最大風速", value=maxwind, inline=False)
         embed.add_field(name="最大瞬間風速", value=windgust, inline=False)
         embed.add_field(name=comment_title, value=comment_body)
         embed.add_field(name="更新", value=analized_date)
         embed.set_image(url="http://weathernews.jp" + json_data['img'])
         await message.channel.send(embed=embed)
         return True
     if args[0] == "rrd":
         api = Yahoo_API()
         url = api.get_rrd()
         embed = discord.Embed(title="雨雲レーダー", description="現在の雨雲の様子です")
         embed.set_image(url=url)
         await message.channel.send(embed=embed)
         return True
示例#20
0
    async def delete_game(self, member=None, custom_msg=""):
        """Called automatically when a user decides to leave a game.\n
        Should only be used when there has been a player forfiet.\n
        Use self.end_game() if the game just needs to be ended.
        """
        await self.clear_game()
        if not self.solo:
            if self.game_started:
                if member is None:
                    if self.turn_based:
                        winner = self.off_turn
                        loser = self.current_turn
                        custom_msg = f"{winner} won by default!"
                    else:
                        winner = None
                        loser = None
                        custom_msg = f"Game Timed Out"
                else:
                    temp = [self.playerOne, self.playerTwo]
                    temp.remove(member)
                    winner = temp[0]
                    loser = member
                    custom_msg = f"{winner} won by default!"

                await self.update_leaderboards(winner, loser)

            else:
                if self.wager > 0:
                    await self.Hamood.Currency.update_wallet(
                        self.guild_id, self.playerOne.id, self.wager
                    )
                custom_msg = "No Winner"

        else:
            if self.game_started:
                await self.update_leaderboards(loser=self.playerOne)
                custom_msg = f"{self.playerOne} forfeited!"
            else:
                if self.wager > 0:
                    await self.Hamood.Currency.update_wallet(
                        self.guild_id, self.playerOne.id, self.wager
                    )
                custom_msg = f"Game Cancelled"

        embed = discord.Embed(
            title=self.game_name.title(),
            description=f"\n**Wager:** {self.cash(self.wager)}"
            if self.wager > 0
            else "",
        )
        embed.set_author(name=custom_msg)
        embed.set_footer(text="Game was ended.")

        try:
            await self.message.edit(embed=embed, content=" ")
        except discord.errors.NotFound:
            pass

        self.message = None

        await self.kill_timer()
示例#21
0
文件: married.py 项目: euYosu/Ashley
    async def marry(self, ctx, member: discord.Member = None):
        """Comando usado pra pedir alguem em casamento
        Use ash marry <@pessoa desejada>"""
        query = {"_id": 0, "user_id": 1, "user": 1, "ship": 1}
        data_user = await (await self.bot.db.cd("users")).find_one({"user_id": ctx.author.id}, query)

        if data_user['user']['married']:
            return await ctx.send('<:alert:739251822920728708>│`VOCE JÁ ESTA CASADO(A)!`')

        if ctx.author.id in self.bot.casando:
            return await ctx.send('<:alert:739251822920728708>│`VOCÊ JÁ ESTÁ EM PROCESSO DE CASAMENTO!`')

        if member is None:
            return await ctx.send('<:alert:739251822920728708>│`VOCÊ PRECISA MENCIONAR ALGUEM.`')

        if member.id == ctx.author.id:
            return await ctx.send('<:alert:739251822920728708>│`VOCE NÃO PODE CASAR CONSIGO MESMO!`')

        query = {"_id": 0, "user_id": 1, "user": 1, "ship": 1}
        data_member = await (await self.bot.db.cd("users")).find_one({"user_id": member.id}, query)

        if data_member is None:
            return await ctx.send('<:alert:739251822920728708>│**ATENÇÃO**: `esse usuário não está cadastrado!` '
                                  '**Você so pode se casar com membros cadastrados!**', delete_after=5.0)

        if data_member['user']['married'] is True:
            return await ctx.send('<:alert:739251822920728708>│`ELE(A) JÁ ESTA CASADO(A)!`')

        if member.id in self.bot.casando:
            return await ctx.send(f'<:alert:739251822920728708>│{member.mention} `JÁ ESTÁ EM PROCESSO DE CASAMENTO!`')

        if str(member.id) not in data_user['ship'].keys():
            t1 = "Você"
            t2 = "use"
            return await ctx.send(f"<:alert:739251822920728708>│`{t1} ainda nao interagiu com essa pessoa, então não"
                                  f" tem` **ship** `com ela ainda, para ter ship {t2} os seguintes comandos:`\n```\n"
                                  f"ash dance\nash hug\nash kick\nash kiss\nash lick\nash punch\nash push\nash slap```")

        if str(ctx.author.id) not in data_member['ship'].keys():
            t1 = "Esse membro"
            t2 = "Ele deve usar"
            return await ctx.send(f"<:alert:739251822920728708>│`{t1} ainda nao interagiu com essa pessoa, então não"
                                  f" tem` **ship** `com ela ainda, para ter ship {t2} os seguintes comandos:`\n```\n"
                                  f"ash dance\nash hug\nash kick\nash kiss\nash lick\nash punch\nash push\nash slap```")

        if data_user['ship'][str(member.id)] <= 600:
            return await ctx.send(f'<:alert:739251822920728708>│{ctx.author.mention} `Voce precisa ter todos os '
                                  f'corações no comando:` **ash ship** `para casar com` {member.mention}')

        if data_member['ship'][str(ctx.author.id)] <= 600:
            return await ctx.send(f'<:alert:739251822920728708>│{member.mention} `Voce precisa ter todos os '
                                  f'corações no comando:` **ash ship** `para casar com` {ctx.author.mention}')

        self.bot.casando.append(ctx.author.id)
        self.bot.casando.append(member.id)

        await ctx.send(f'<a:vergonha:525105074398167061>│{member.mention}, `VOCÊ RECEBEU UM PEDIDO DE '
                       f'CASAMENTO DE` {ctx.author.mention} `DIGITE` **SIM** `OU` **NÃO**')

        def check(m):
            return m.author.id == member.id and m.content.upper() in ['SIM', 'NÃO', 'S', 'N', 'NAO', 'CLARO']

        try:
            answer = await self.bot.wait_for('message', check=check, timeout=30.0)

        except TimeoutError:
            self.bot.casando.remove(ctx.author.id)
            self.bot.casando.remove(member.id)
            return await ctx.send('<:negate:721581573396496464>│`Desculpe, ele(a) demorou muito pra responder:` '
                                  '**COMANDO CANCELADO**')

        if answer.content.upper() not in ['SIM', 'S', 'CLARO']:
            self.bot.casando.remove(ctx.author.id)
            self.bot.casando.remove(member.id)
            return await ctx.send(f'<:negate:721581573396496464>│{ctx.author.mention} `VOCE FOI REJEITADO...`')

        data_user['user']['married'] = True
        data_user['user']['married_at'] = member.id
        data_user['user']['married_in'] = datetime.today()

        data_member['user']['married'] = True
        data_member['user']['married_at'] = ctx.author.id
        data_member['user']['married_in'] = datetime.today()

        cl = await self.bot.db.cd("users")
        query = {"$set": {"user": data_user['user']}}
        await cl.update_one({"user_id": data_user["user_id"]}, query, upsert=False)

        cl = await self.bot.db.cd("users")
        query = {"$set": {"user": data_member['user']}}
        await cl.update_one({"user_id": data_member["user_id"]}, query, upsert=False)

        self.bot.casando.remove(ctx.author.id)
        self.bot.casando.remove(member.id)

        embed = discord.Embed(color=self.color)
        embed.set_image(url=choice(git))
        await ctx.send(embed=embed)
        await ctx.send(f"🎊 **PARABENS** 🎉 {ctx.author.mention} **e** {member.mention} **vocês estão casados!**")
示例#22
0
 async def help(self, ctx):
     embed = discord.Embed(title="Commands & Useage", color=0x9988FF)
     embed.set_thumbnail(url="https://aq3d.com/media/1507/aq3d-full-logo760.png")
     embed.add_field(name="Commands: ", value=help_msg, inline=False)
     await ctx.send(embed=embed)
示例#23
0
文件: roles.py 项目: ozzhates/AceBot
    async def editor(self, ctx):
        '''Editor for selectors and roles.'''

        # ignore command input from user while editor is open
        self.set_editing(ctx)

        conf = await self.config.get_entry(ctx.guild.id)

        slcs = await self.db.fetch(
            '''
			SELECT rs.*
			FROM role_selector as rs
			JOIN unnest($1::INTEGER[]) WITH ORDINALITY t(id, ord) USING (id)
			WHERE id=ANY($1::INTEGER[])
			ORDER BY t.ord
			''', conf.selectors)

        selectors = list()

        for slc in slcs:
            roles = await self.db.fetch(
                '''
				SELECT re.* 
				FROM role_entry as re 
				JOIN unnest($1::INTEGER[]) WITH ORDINALITY t(id, ord) USING (id) 
				WHERE id=ANY($1::INTEGER[])
				ORDER BY t.ord
				''', slc.get('roles'))

            selector = Selector.from_record(
                slc, list(Role.from_record(role) for role in roles))
            selectors.append(selector)

        head = RoleHead(conf, selectors)

        # so converters can access the head for data integrity tests...
        ctx.head = head

        msg = await ctx.send(embed=discord.Embed(
            description='Please wait while reactions are being added...'))

        self.messages[ctx.guild.id] = msg

        for emoji in EMBED_EMOJIS:
            await msg.add_reaction(emoji)

        def pred(reaction, user):
            return reaction.message.id == msg.id and user.id == ctx.author.id

        async def close():
            self.unset_editing(ctx)
            try:
                await msg.delete()
                self.messages.pop(ctx.guild.id)
            except discord.HTTPException:
                pass

        while True:
            await msg.edit(embed=head.embed())

            try:
                reaction, user = await self.bot.wait_for('reaction_add',
                                                         check=pred,
                                                         timeout=300.0)
            except asyncio.TimeoutError:
                await close()
                raise commands.CommandError(
                    'Role editor closed after 5 minutes of inactivity.')
            else:
                await msg.remove_reaction(reaction.emoji, user)

                reac = str(reaction)

                if reac == ADD_SEL_EMOJI:
                    if len(head.selectors) > 7:
                        await ctx.send(embed=discord.Embed(
                            description='No more than 8 selectors, sorry!'),
                                       delete_after=6)
                        continue

                    selector_data = await self._multiprompt(
                        ctx, msg, NEW_SEL_PREDS)
                    if selector_data is None:
                        continue

                    selector = Selector(selector_data[0], None, list())
                    selector.set_dirty()

                    new_pos = 0 if not head.selectors else head.selector_pos + 1
                    head.add_selector(new_pos, selector)

                    head.selector_pos = new_pos
                    head.role_pos = None

                if reac == ABORT_EMOJI:
                    await close()
                    raise commands.CommandError(
                        'Editing aborted, no changes saved.')

                if reac == SAVE_EMOJI:
                    await head.store(ctx)
                    await close()
                    await ctx.send(
                        'New role selectors saved. Do `roles spawn` to see!')
                    break

                # rest of the actions assume at least one item (selector) is present
                if not head.selectors:
                    continue

                if reac == ADD_ROLE_EMOJI:
                    if len(head.selector.roles) > 24:
                        await ctx.send(embed=discord.Embed(
                            description=
                            'No more than 25 roles in one selector, sorry!'),
                                       delete_after=6)
                        continue

                    role_data = await self._multiprompt(
                        ctx, msg, NEW_ROLE_PREDS)
                    if role_data is None:
                        continue

                    role = Role(*role_data)

                    new_pos = 0 if head.role_pos is None else head.role_pos + 1
                    head.selector.add_role(new_pos, role)

                    head.role_pos = new_pos

                if reac == DOWN_EMOJI:
                    head.down()
                if reac == UP_EMOJI:
                    head.up()

                if reac in (MOVEUP_EMOJI, MOVEDOWN_EMOJI):
                    direction = -1 if reac == MOVEUP_EMOJI else 1

                    if head.role_pos is None:
                        head.move_selector(direction)
                    else:
                        head.move_role(direction)

                if reac == DEL_EMOJI:
                    if head.role_pos is None:

                        if len(head.selector.roles):
                            p = ctx.prompt(
                                'Delete selector?',
                                'The selector you\'re trying to delete has {} roles inside it.'
                                .format(len(head.selector.roles)))

                            if not await p:
                                continue

                        head.selectors.pop(head.selector_pos)
                        if head.selector_pos > head.selector_max:
                            head.selector_pos = head.selector_max
                        head.role_pos = None

                    else:
                        head.selector.roles.pop(head.role_pos)
                        if len(head.selector.roles) == 0:
                            head.role_pos = None
                        elif head.role_pos > head.role_max:
                            head.role_pos = head.role_max

                if reac == EDIT_EMOJI:
                    await self._edit_item(
                        ctx, msg, head.selector if head.role_pos is None else
                        head.selector.roles[head.role_pos])
示例#24
0
 async def time(self, ctx):
     tz = timezone('EST')
     embed = discord.Embed(title="Server Time", description=f'Server Time: `{datetime.now(tz).ctime()}`\nTime to Reset: `{midnight_time(tz)}`', color=0x9900FF)
     embed.set_thumbnail(url="https://aq3d.com/media/1507/aq3d-full-logo760.png")
     await ctx.send(embed=embed)
示例#25
0
文件: roles.py 项目: ozzhates/AceBot
    async def _edit_item(self, ctx, msg, item):
        if isinstance(item, Selector):
            questions = dict(
                title=selector_title_converter,
                description=selector_desc_converter,
                inline=SelectorInlineConverter(),
            )
        elif isinstance(item, Role):
            questions = dict(
                name=role_title_converter,
                description=role_desc_converter,
                emoji=SelectorEmojiConverter(),
            )
        else:
            raise TypeError('Unknown item type: ' + str(type(item)))

        opts = {emoji: q for emoji, q in zip(EMBED_EMOJIS, questions.keys())}

        opt_string = '\n'.join('{} {}'.format(key, value)
                               for key, value in opts.items())

        e = discord.Embed(description='What would you like to edit?\n\n' +
                          opt_string)

        e.set_footer(text=ABORT_EMOJI + ' to abort.')

        await msg.edit(embed=e)

        def reac_pred(reaction, user):
            return reaction.message.id == msg.id and user.id == ctx.author.id

        while True:
            try:
                reaction, user = await self.bot.wait_for('reaction_add',
                                                         check=reac_pred,
                                                         timeout=300.0)
            except asyncio.TimeoutError:
                return
            else:
                await msg.remove_reaction(reaction.emoji, user)

                reac = str(reaction)

                if reac == ABORT_EMOJI:
                    return

                elif reac in opts.keys():
                    attr = opts[reac]
                    conv = questions[attr]
                    break

                else:
                    continue

        e.description = 'Please input a new value for \'{}\'.'.format(attr)
        e.set_footer(text='Send \'exit\' to abort.')
        await msg.edit(embed=e)

        def msg_pred(message):
            return message.channel.id == msg.channel.id and message.author.id == ctx.author.id

        while True:
            try:
                message = await self.bot.wait_for('message',
                                                  check=msg_pred,
                                                  timeout=60.0)
            except asyncio.TimeoutError:
                return

            await message.delete()

            if message.content.lower() == 'exit':
                return

            try:
                value = await conv.convert(ctx, message.content)
            except commands.CommandError as exc:
                if not msg.embeds:
                    try:
                        await msg.delete()
                    except discord.HTTPException:
                        pass
                    raise commands.CommandError(
                        'Embed seems to have been removed, aborting.')

                e = msg.embeds[0]
                e.set_footer(text='NOTE: ' + str(exc) + ' ' + RETRY_MSG)
                await msg.edit(embed=e)
                continue

            setattr(item, attr, value)
            item.set_dirty()
            return
示例#26
0
 async def fish(self, ctx, option="None", *, fish="None"):
     option_list = ["rods", "levels", "fish"]
     if option == "None":
         options = "`rods`, `levels`, `fish`"
         embed = discord.Embed(title="Lookup Categories", description='`!fish <category>` or `!fish fish <Fish Name>`', color=0x00ff00)
         embed.set_thumbnail(url="https://aq3d.com/media/1507/aq3d-full-logo760.png")
         embed.add_field(name="Fish Categories:", value=options, inline=False)
         await ctx.send(embed=embed)
         return
     elif option in option_list:
         if option == "rods":
             with open(f'./data/fish/rods.txt', "r") as f:
                 output = f.read()
             embed = discord.Embed(title="Fishing Rods", description=f'```{output}```', color=0x00ff00)
             embed.set_thumbnail(url="https://aq3d.com/media/1507/aq3d-full-logo760.png")
             await ctx.send(embed=embed)
             return
         elif option == "levels":
             with open(f'../data/fish/10_exp.txt', "r") as f:
                 output1 = f.read()
             with open(f'../data/fish/20_exp.txt', "r") as f:
                 output2 = f.read()
             with open(f'../data/fish/30_exp.txt', "r") as f:
                 output3 = f.read()
             with open(f'../data/fish/40_exp.txt', "r") as f:
                 output4 = f.read()
             with open(f'../data/fish/50_exp.txt', "r") as f:
                 output5 = f.read()
             embed = discord.Embed(title="Fishing Exp", color=0x00ff00)
             embed.set_thumbnail(url="https://aq3d.com/media/1507/aq3d-full-logo760.png")
             embed.add_field(name="__**Levels 1-10:**__", value=f'```{output1}```', inline=False)
             embed.add_field(name="__**Levels 11-20:**__", value=f'```{output2}```', inline=False)
             embed.add_field(name="__**Levels 21-30:**__", value=f'```{output3}```', inline=False)
             embed.add_field(name="__**Levels 31-40:**__", value=f'```{output4}```', inline=False)
             embed.add_field(name="__**Levels 41-50:**__", value=f'```{output5}```', inline=False)
             await ctx.send(embed=embed)
             return
         else:
             format_fish = []
             with open(f'./data/fish/fish.txt', "r") as f:
                 fish_list = f.readlines()
             if fish == "None":
                 output = ""
                 for fish in fish_list:
                     format_fish.append(fish.capitalize())
                 for i in format_fish:
                     output += f'`{i[:-1]}`\n'
                 embed = discord.Embed(title="Fishes", description=output, color=0x00ff00)
                 embed.set_thumbnail(url="https://aq3d.com/media/1507/aq3d-full-logo760.png")
                 await ctx.send(embed=embed)
                 return
             else:
                 for fishes in fish_list:
                     format_fish.append(fishes.lower()[:-1])
                 fish = fish.lower()
                 if fish in format_fish:
                     row = format_fish.index(fish)
                     data = getItem(row)
                     embed = createFishEmbed(data)
                     await ctx.send(embed=embed)
                     return
                 else:
                     await ctx.send("Unable to find fish.")
     else:
         await ctx.send("Unknown Category, See `!fish` for Categories.")
示例#27
0
文件: roles.py 项目: ozzhates/AceBot
    async def on_raw_reaction_add(self, payload):
        guild_id = payload.guild_id
        if guild_id is None:
            return

        channel_id = payload.channel_id
        message_id = payload.message_id
        user_id = payload.user_id
        emoji = payload.emoji

        conf = await self.config.get_entry(guild_id, construct=False)
        if conf is None:
            return

        if channel_id != conf.channel_id or message_id not in conf.message_ids:
            return

        guild = self.bot.get_guild(guild_id)
        if guild is None:
            return

        channel = guild.get_channel(channel_id)
        if channel is None:
            return

        message = await channel.fetch_message(message_id)
        if message is None:
            return

        member = guild.get_member(user_id)
        if member is None:
            return

        if member.bot:
            return

        try:
            await message.remove_reaction(emoji, member)
        except discord.HTTPException:
            pass

        selector_id = conf.selectors[conf.message_ids.index(message_id)]

        selector = await self.db.fetchrow(
            'SELECT * FROM role_selector WHERE id=$1', selector_id)
        if selector is None:
            return

        role_row = await self.db.fetchrow(
            'SELECT * FROM role_entry WHERE emoji=$1 AND id=ANY($2::INTEGER[])',
            str(emoji), selector.get('roles'))

        if role_row is None:
            return

        role = guild.get_role(role_row.get('role_id'))
        if role is None:
            await channel.send(embed=discord.Embed(
                description=
                'Could not find role with ID {}. Has it been deleted?'.format(
                    role_row.get('role_id'))),
                               delete_after=30)
            return

        e = discord.Embed()
        e.set_author(name=member.display_name, icon_url=member.avatar_url)

        do_add = role not in member.roles

        try:
            if do_add:
                await member.add_roles(role,
                                       reason='Added through role selector')
                e.description = 'Added role {}'.format(role.mention)
            else:
                await member.remove_roles(
                    role, reason='Removed through role selector')
                e.description = 'Removed role {}'.format(role.mention)
        except discord.HTTPException:
            e.description = 'Unable to add role {}. Does the bot have the necessary permissions?'.format(
                role.mention)

            try:
                await channel.send(embed=e, delete_after=30)
            except discord.HTTPException:
                pass

        if conf.notify:
            await channel.send(embed=e, delete_after=5)

        log.info('%s %s %s %s in %s', 'Added' if do_add else 'Removed',
                 po(role), 'to' if do_add else 'from', po(member), po(guild))
示例#28
0
    async def albumcoverspotify(self, ctx, *, arg=None):
        async with ctx.typing():

            username = db.get_user(ctx.author.id)

            if username is None:
                return await ctx.send(
                    f"`You need to first set your Last.fm username with the command`\n```>set [your username]```"
                )

            lastfm_username = username[0][1]
            if not lastfm_username:
                return await ctx.send(
                    f"`You need to first set your Last.fm username with the command`\n```>set [your username]```"
                )

            if arg is None:
                recent_tracks_params = {
                    "limit": "1",
                    "user": lastfm_username,
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "user.getRecentTracks"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/",
                                 params=recent_tracks_params)
                rtdata = r.json()
                rtinfo = rtdata["recenttracks"]["track"][0]
                artist = rtinfo["artist"]["#text"]
                album = rtinfo["album"]["#text"]

                album_info_params = {
                    "artist": artist.strip(),
                    "album": album.strip(),
                    "autocorrect": "1",
                    "api_key": os.getenv("LASTFM_API_KEY"),
                    "format": "json",
                    "method": "album.getInfo"
                }

                r = requests.get("http://ws.audioscrobbler.com/2.0/",
                                 params=album_info_params)
                abidata = r.json()
            else:
                try:
                    artist, album = arg.split("|")
                except:
                    return await ctx.send(embed=discord.Embed(
                        description="Use the format `artist | album`.",
                        colour=0x4a5fc3))

            album_info_params = {
                "artist": artist.strip(),
                "album": album.strip(),
                "autocorrect": "1",
                "api_key": os.getenv("LASTFM_API_KEY"),
                "format": "json",
                "method": "album.getInfo"
            }

            r = requests.get("http://ws.audioscrobbler.com/2.0/",
                             params=album_info_params)
            abidata = r.json()
            actual_artist = abidata["album"]["artist"]
            actual_album = abidata["album"]["name"]

            try:
                album_url = abidata["album"]["url"]
            except KeyError:
                album_url = ""

            sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
            sp_album_image = ""
            results = sp.search(f"{actual_artist} {actual_album}",
                                type="track",
                                limit=20)
            items = results["tracks"]["items"]
            lfm_artist_name_lowercase = f"{actual_artist.lower()}"
            lfm_album_name_lowercase = f"{actual_album.lower()}"

            for sp_track in items:
                sp_artist_correct = sp_track["artists"][0]
                sp_album_correct = sp_track["album"]
                sp_artist_name_lowercase = sp_artist_correct["name"].lower()
                sp_album_name_lowercase = sp_album_correct["name"].lower()
                if lfm_artist_name_lowercase == sp_artist_name_lowercase and lfm_album_name_lowercase == sp_album_name_lowercase:
                    try:
                        sp_album_image = sp_track["album"]["images"][0]["url"]
                    except IndexError:
                        sp_album_image = None
                    break

            if sp_album_image is None:
                embed = discord.Embed(
                    description=
                    f"**{actual_artist} - [{actual_album}]({album_url})**\n*No cover exists for this album.*",
                    timestamp=datetime.now() - timedelta(hours=2),
                    colour=0x4a5fc3)
                embed.set_footer(
                    text=
                    f"Requested by {ctx.author.name}#{ctx.author.discriminator}"
                )
            else:
                embed = discord.Embed(
                    description=
                    f"**{actual_artist} - [{actual_album}]({album_url})**",
                    timestamp=datetime.now() - timedelta(hours=2),
                    colour=0x4a5fc3)
                embed.set_image(url=f"{sp_album_image}")
            embed.set_footer(
                text=
                f"Requested by {ctx.author.name}#{ctx.author.discriminator}")

        await ctx.send(embed=embed)
示例#29
0
    async def apply(self, ctx: commands.Context):
        """Apply to be a staff member."""
        role_add = get(ctx.guild.roles, name="Staff Applicant")
        channel = get(ctx.guild.text_channels, name="applications")
        if ctx.guild not in self.antispam:
            self.antispam[ctx.guild] = {}
        if ctx.author not in self.antispam[ctx.guild]:
            self.antispam[ctx.guild][ctx.author] = AntiSpam([(timedelta(days=2), 1)])
        if self.antispam[ctx.guild][ctx.author].spammy:
            return await ctx.send("Uh oh, you're doing this way too frequently.")
        if role_add is None:
            return await ctx.send(
                "Uh oh. Looks like your Admins haven't added the required role."
            )
        if channel is None:
            return await ctx.send(
                "Uh oh. Looks like your Admins haven't added the required channel."
            )
        try:
            await ctx.author.send(
                "Let's start right away! You have maximum of 2 minutes for each question.\nWhat position are you applying for?"
            )
        except discord.Forbidden:
            return await ctx.send(
                "I don't seem to be able to DM you. Do you have closed DMs?"
            )
        await ctx.send(f"Okay, {ctx.author.mention}, I've sent you a DM.")

        def check(m):
            return m.author == ctx.author and m.channel == ctx.author.dm_channel

        try:
            position = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        await ctx.author.send("What is your name?")
        try:
            name = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        await ctx.author.send("How old are you?")
        try:
            age = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        await ctx.author.send("What timezone are you in? (Google is your friend.)")
        try:
            timezone = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        await ctx.author.send("How many days per week can you be active?")
        try:
            days = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        await ctx.author.send("How many hours per day can you be active?")
        try:
            hours = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        await ctx.author.send(
            "Do you have any previous experience? If so, please describe."
        )
        try:
            experience = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        await ctx.author.send("Why do you want to be a member of our staff?")
        try:
            reason = await self.bot.wait_for("message", timeout=120, check=check)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        embed = discord.Embed(color=await ctx.embed_colour(), timestamp=datetime.now())
        embed.set_author(name="New application!", icon_url=ctx.author.avatar_url)
        embed.set_footer(
            text=f"{ctx.author.name}#{ctx.author.discriminator} ({ctx.author.id})"
        )
        embed.title = (
            f"User: {ctx.author.name}#{ctx.author.discriminator} ({ctx.author.id})"
        )
        embed.add_field(name="Name:", value=name.content, inline=True)
        embed.add_field(name="Age:", value=age.content, inline=True)
        embed.add_field(name="Timezone:", value=timezone.content, inline=True)
        embed.add_field(name="Desired position:", value=position.content, inline=True)
        embed.add_field(name="Active days/week:", value=days.content, inline=True)
        embed.add_field(name="Active hours/day:", value=hours.content, inline=True)
        embed.add_field(
            name="Previous experience:", value=experience.content, inline=False
        )
        embed.add_field(name="Reason:", value=reason.content, inline=False)

        await channel.send(embed=embed)

        await ctx.author.add_roles(role_add)

        await ctx.author.send(
            "Your application has been sent to the Admins, thank you!"
        )
        self.antispam[ctx.guild][ctx.author].stamp()
示例#30
0
    async def _help(self, ctx: Context, command: CommandConverter = None):
        """
        Shows help for a command or a list of all commands.

        Usage:
            {prefix}help
            {prefix}help <command>

        Example:
            {prefix}help config
        """
        if command is None:
            other_commands = {}
            pages = []
            for cog in self.bot.cogs.values():
                if not getattr(cog, "hidden", False):
                    command_list = get_cog_commands(cog)
                    if cog.qualified_name != "Other":
                        if len(command_list) > 1:
                            self.add_page(cog.qualified_name, pages,
                                          command_list)
                        else:
                            other_commands.update(command_list)
                    else:
                        other_commands.update(command_list)
            no_cog = {
                comm.name: comm
                for comm in self.bot.commands
                if comm.cog is None and not comm.hidden
            }
            other_commands.update(no_cog)
            if other_commands:
                self.add_page("Other", pages, other_commands)

            embed = discord.Embed(title="Help Menu", color=constants.Bot.color)
            await HelpPaginator.paginate(ctx,
                                         embed,
                                         pages=pages,
                                         restrict_to_users=(ctx.author, ))
        else:
            help_format = """**```asciidoc
{comm}
{dashes}

{help}```**"""
            embed = discord.Embed(title="Help Menu", color=constants.Bot.color)
            comms = (dict({command.name: command}, **
                          get_group_commands(command)) if isinstance(
                              command, Group) else {
                                  command.name: command
                              })
            pages = [
                help_format.format(comm=name,
                                   dashes='-' * len(name),
                                   help=comm.help.format(prefix=ctx.prefix))
                for name, comm in comms.items()
            ]
            await HelpPaginator.paginate(ctx,
                                         embed,
                                         pages=pages,
                                         restrict_to_users=(ctx.author, ))