コード例 #1
0
ファイル: skyutils.py プロジェクト: skylarr1227/sky-cogs
    async def onixian(self, *, ctx):
        confirmation = BotConfirmation(ctx, 0x012345)
        await confirmation.confirm(
            "Would you like to know more about Onixian? Well, react accordingly."
        )

        if confirmation.confirmed:
            await confirmation.update(
                "Onixian, a Pokemon bot from a developer many already know: Foreboding.",
                color=0x55ff55)
            member = ctx.author
            embed = discord.Embed(
                color=discord.Color.blue(),
                description=
                "[Click here to join the official Onixian server](https://discord.gg/67Bx3sV)\nNew features and updates added daily!\
                                          \nCommunity suggestions are heard, discussed, and implemented fast!\
                                          \nFamiliar look and commands your used to, with an epic new spin!\
                                          \nSKY is somehow involved, that's good right??? (Right...??)\
                                          \nOh and also don't forget to [vote if you want it to grow!](https://top.gg/bot/654427498565599243)\
                                          \n\n``its also in`` [sky's server](https://discord.gg/eBwrbNh) ``if you got beef with Mr. Bodeing just sayin!``"
            )
            embed.set_author(name="Have fun!")
            embed.set_image(
                url=
                "https://images.discordapp.net/avatars/654427498565599243/07fe64e8cd90e789001f1c3da4bde6c0.png"
            )
            await ctx.send(embed=embed)
            #channel = self.bot.get_channel("599660712985624576")
            #await ctx.send_message(channel, "butts")
        else:
            await confirmation.update(
                "Well, good job.. now Sky owns your soul. She will be by to collect within 24 hours. Please be ready.",
                hide_author=True,
                color=0xff5555)
コード例 #2
0
 async def delevent(self, ctx: commands.Context):
     """
     Deletes an event
     #STAFF
     """
     gen = [
         event.name
         for event in self.events
     ]
     multiple_choice = BotMultipleChoice(
         ctx, gen, "Choose which event to delete", colour=0x94F29B)
     await multiple_choice.run()
     await multiple_choice.quit()
     if multiple_choice.choice:
         confirmation = BotConfirmation(ctx, 0x012345)
         await confirmation.confirm(f"Are you sure you want to delete {multiple_choice.choice}?")
         if confirmation.confirmed:
             await confirmation.update("Confirmed", color=0x55ff55)
             async with self.lock:
                 for n, event in enumerate(self.events):
                     if event.name == multiple_choice.choice:
                         self.events[n] = None
                         async with aiosqlite.connect("calendar.db") as db:
                             await db.execute(
                                 """DELETE FROM events WHERE date_start=? AND date_end=? AND name=?""",
                                 (event.date_start, event.date_end, event.name))
                             await db.commit()
                 self.events = [event for event in self.events if event is not None]
         else:
             await confirmation.update("Not confirmed", hide_author=True, color=0xFF0000)
コード例 #3
0
ファイル: coordinates.py プロジェクト: tigersharkpr13/Inari
 async def shopset(self, ctx: commands.Context, name: str, *items: str):
     """
     Sets a shop
     **e.g**: $shopset <name> <items it sells>
     __Wrap <name> in " "  if it uses spaces__
     """
     await ctx.message.delete()
     slash_sep_items = '/'.join(items)
     confirmation = BotConfirmation(ctx, 0xFFAE00)
     await confirmation.confirm(
         f"Are you sure you want to set your shop as:\n"
         f"Name: {name} / Sells: {slash_sep_items}")
     if confirmation.confirmed:
         shop = Shop(user_id=ctx.author.id,
                     name=name,
                     items=slash_sep_items,
                     guild_id=ctx.guild.id)
         self.shops.append(shop)
         async with aiosqlite.connect("coorddata.db") as db:
             await db.execute(
                 """INSERT INTO shops (user_id, name, items, guild_id) VALUES(?,?,?,?)""",
                 (ctx.author.id, name, slash_sep_items, ctx.guild.id))
             await db.commit()
         await confirmation.update(
             f'Shop for {ctx.author.display_name} set as:'
             f'Name: {name} / Sells: {slash_sep_items}'[:100],
             color=0xFFAE00)
     else:
         await confirmation.update("Not confirmed",
                                   hide_author=True,
                                   color=0xFF0000)
コード例 #4
0
ファイル: kaede.py プロジェクト: united-minecrafters/kaede
    async def delstatus(self, ctx, n: int):
        """
        Deletes a status
        #OWNER
        """
        if len(config()["statuses"]) == 1:
            await ctx.send("Can't delete only status, do `!resetstatus`")
            return
        if n < 0 or n >= len(config()["statuses"]):
            await ctx.send("Invalid index, do `!liststatus`")
            return
        conf = BotConfirmation(ctx, 0x5555ff)
        await conf.confirm(f'Delete `{config()["statuses"][n]}`?')

        if conf.confirmed:
            try:
                s = config()["statuses"][n]
                del config()["statuses"][n]
                save_config()
                self.status = cycle(config()["statuses"])
                self.status_rotate.restart()
            except Exception as e:  # noqa e722
                await conf.update("An error occurred", color=0xffff00)
            else:
                await conf.update("Deleted!", color=0x55ff55)
                await self.modlog.log_message("Status Modification", f"```diff\n - {s}```", ctx.author)
        else:
            await conf.update("Canceled", color=0xff5555)
コード例 #5
0
ファイル: filters.py プロジェクト: united-minecrafters/kaede
    async def delfilteredtoken(self, ctx: commands.Context, n: int):
        """
        Delete a filtered token
        #STAFF
        """
        if n < 0 or n >= len(config()["filters"]["token_blacklist"]):
            await ctx.send("Invalid number - do `!lfw` to view")
        conf = BotConfirmation(ctx, 0x5555ff)
        await conf.confirm(
            f'Delete `{config()["filters"]["token_blacklist"][n]}`?')

        if conf.confirmed:
            try:
                s = config()["filters"]["token_blacklist"][n]
                del config()["filters"]["token_blacklist"][n]
                save_config()
            except Exception as e:  # noqa e722
                await conf.update("An error occurred", color=0xffff00)
            else:
                await conf.update("Deleted!", color=0x55ff55)
                await self.modlog.log_message("Filter Token Modification",
                                              f"```diff\n - {s}```",
                                              ctx.author)
        else:
            await conf.update("Canceled", color=0xff5555)
コード例 #6
0
 async def delete_availabilities(self, ctx: commands.Context):
     if not self.availabilities:
         await ctx.send(embed=discord.Embed(title='No availabilities have been set!', colour=0xFF0000))
         return
     gen = [
         stamp_to_str(avail.date_start) + " - " + stamp_to_str(avail.date_end)
         for avail in self.availabilities if avail.userid == ctx.author.id
     ]
     multiple_choice = BotMultipleChoice(
         ctx, gen, 'Choose which of your avails to delete',
         colour=0x94F29B)
     await multiple_choice.run()
     await multiple_choice.quit()
     if multiple_choice.choice:
         confirmation = BotConfirmation(ctx, 0x012345)
         await confirmation.confirm(f"Are you sure you want to delete {multiple_choice.choice}?")
         if confirmation.confirmed:
             await confirmation.update("Confirmed", color=0x55ff55)
             async with self.lock:
                 for n, avail in enumerate(self.availabilities):
                     if (stamp_to_str(avail.date_start) + " - " + stamp_to_str(avail.date_end) ==
                             multiple_choice.choice and avail.userid == ctx.author.id):
                         self.availabilities[n] = None
                         async with aiosqlite.connect("calendar.db") as db:
                             await db.execute(
                                 """DELETE FROM availabilities WHERE userid=? AND date_start=? AND date_end=?""",
                                 (ctx.author.id, avail.date_start, avail.date_end))
                             await db.commit()
                 self.availabilities = [avail for avail in self.availabilities if avail is not None]
         else:
             await confirmation.update("Not confirmed", hide_author=True, color=0xFF0000)
コード例 #7
0
ファイル: admin.py プロジェクト: eggnoginsquad/Polyphony
    async def disable(self, ctx: commands.context,
                      system_member: discord.Member):
        """
        Disables a system member permanently by deleting it from the database and kicking it from the server. Bot token cannot be reused.

        :param ctx: Discord Context
        :param system_member: System Member
        """
        # TODO: Provide more verbose feedback from command
        instance = get_member_by_discord_id(system_member.id)
        if instance:
            log.debug(f"Disabling {system_member}")
            confirmation = BotConfirmation(ctx, discord.Color.red())
            await confirmation.confirm(
                f"Disable member {system_member} permanently?")
            if confirmation.confirmed:
                await confirmation.message.delete()
                with conn:
                    c.execute(
                        "DELETE FROM members WHERE token = ?",
                        [instance["token"]],
                    )
                await self.suspend(ctx, system_member)
                await ctx.send(
                    f"{system_member.mention} disabled permanently by {ctx.message.author}"
                )
                log.info(
                    f"{system_member} has been disabled permanently by {ctx.message.author}"
                )
                log.debug(f"Disabled {system_member}")
            else:
                await confirmation.message.delete()
                await ctx.send(f"{system_member.mention} was __not__ disabled")
                log.debug(f"Canceled disable of {system_member}")
コード例 #8
0
    async def confirm(self, ctx):
        confirmation = BotConfirmation(ctx, 0x012345)
        await confirmation.confirm("Are you sure?")

        if confirmation.confirmed:
            await confirmation.update("Confirmed", color=0x55ff55)
        else:
            await confirmation.update("Not confirmed", hide_author=True, color=0xff5555)
コード例 #9
0
ファイル: skyutils.py プロジェクト: skylarr1227/sky
    async def testconfirm(self, ctx):
        confirmation = BotConfirmation(ctx, 0x012345)
        await confirmation.confirm(
            "Do you have any event ideas that you would like to contribute?")

        if confirmation.confirmed:
            await confirmation.update("Yes", color=0x55ff55)
        else:
            await confirmation.update("No", hide_author=True, color=0xff5555)
コード例 #10
0
    async def disable(self, ctx: commands.context,
                      system_member: discord.Member):
        """
        Disables a system member permanently by deleting it from the database and kicking it from the server. Bot token cannot be reused.

        :param ctx: Discord Context
        :param system_member: System Member
        """
        await ctx.message.delete()
        member = conn.execute(
            "SELECT * FROM members WHERE id = ?",
            [system_member.id],
        ).fetchone()
        if member is not None:
            log.debug(f"Disabling {system_member}")
            confirmation = BotConfirmation(ctx, discord.Color.red())
            await confirmation.confirm(
                f"Disable member __{system_member}__ **permanently?**")
            if confirmation.confirmed:
                await confirmation.message.delete()
                conn.execute(
                    "DELETE FROM members WHERE id = ?",
                    [system_member.id],
                )
                conn.commit()
                await ctx.send(embed=discord.Embed(
                    description=
                    f":ballot_box_with_check: {system_member.mention} **permanently disabled** by {ctx.author.mention}",
                    color=discord.Color.dark_green(),
                ))
                log.info(
                    f"{system_member} has been permanently by {ctx.message.author}"
                )
            else:
                await confirmation.message.delete()
                await ctx.send(
                    embed=discord.Embed(
                        description=
                        f":information_source: {system_member.mention} was __not__ disabled",
                        color=discord.Color.blue(),
                    ),
                    delete_after=10,
                )
                log.info(f"{system_member} not disabled")
        else:
            await ctx.send(
                embed=discord.Embed(
                    description=
                    f":x: {system_member.mention} not found in database",
                    color=discord.Color.red(),
                ),
                delete_after=10,
            )
コード例 #11
0
    async def schedule(self, ctx: commands.Context, name: str, date: str, start: str, end: str,
                       channel: discord.TextChannel, role: discord.Role = None):
        """
        Schedule an event
        Set date as: day/month/year
        Set time in 24 hour format
        !schedule <name event> <date> <start> <end> <channel> [role_to_ping]
        [] = optional
        #STAFF
        """
        if ctx.author.id in self.timezones:
            user_tz = self.timezones[ctx.author.id]
        else:
            async with aiohttp.ClientSession() as sess:
                async with sess.get(f"https://www.ansura.xyz/api/{ctx.author.id}") as resp:
                    if resp.status != 200:
                        await ctx.send(embed=discord.Embed(title="You don't have a timezone set with Ansura",
                                                           description="Do `%help` to see Ansura's commands",
                                                           colour=0xFF0000))
                        return
                    else:
                        js = await resp.json()
            user_tz = js["timezone"]
            self.timezones[ctx.author.id] = user_tz

        if parse(start) > parse(end):
            await ctx.send(embed=discord.Embed(title='The start time must be before the end time',
                                               colour=0xFF0000))
            return
        date_start = str_to_stamp(date, start)
        date_end = str_to_stamp(date, end)
        confirmation = BotConfirmation(ctx, 0x94F29B)
        await confirmation.confirm(f'Are you sure you want to schedule an event for:'
                                   f"{stamp_to_str(date_start)}"
                                   f" - {stamp_to_str(date_end)}")
        if confirmation.confirmed:
            await confirmation.update("Confirmed", color=0x55ff55)
            event = Event(userid=ctx.author.id, date_start=date_start,
                          date_end=date_end, timezone=user_tz,
                          name=name, channel_id=channel.id,
                          role_id=role.id if role else None, sent=0)
            async with self.lock:
                self.events.append(event)
            async with aiosqlite.connect("calendar.db") as db:
                await db.execute(
                    """INSERT INTO events
                       (userid, date_start, date_end, timezone, name, channel_id, role_id, sent)
                       VALUES (?,?,?,?,?,?,?,?)""",
                    (ctx.author.id, date_start, date_end, user_tz, name,
                     channel.id, role.id if role else None, 0))
                await db.commit()
        else:
            await confirmation.update("Not confirmed", hide_author=True, color=0xFF0000)
コード例 #12
0
    async def rps(self, ctx):
        PlayerScore = 0
        BotScore = 0
        while True:
            player = BotMultipleChoice(ctx, ['剪刀', '石頭', '布'], "請出拳")
            await player.run()
            await player.quit()
            bot = random.choice(['剪刀', '石頭', '布'])
            if player.choice == '剪刀':
                if bot == '剪刀':
                    status = '平手'
                if bot == '石頭':
                    status = '失敗'
                if bot == '布':
                    status = '勝利'
            elif player.choice == '石頭':
                if bot == '剪刀':
                    status = '勝利'
                if bot == '石頭':
                    status = '平手'
                if bot == '布':
                    status = '失敗'
            elif player.choice == '布':
                if bot == '剪刀':
                    status = '失敗'
                if bot == '石頭':
                    status = '勝利'
                if bot == '布':
                    status = '平手'
            else:
                embed = discord.Embed(title="已取消", color=discord.Colour.red())
                await ctx.send(embed=embed)
                break

            if status == '失敗':
                BotScore += 1
                color = discord.Colour.red()
            if status == '勝利':
                PlayerScore += 1
                color = discord.Colour.green()
            if status == '平手':
                color = discord.Colour.orange()

            confirm = BotConfirmation(ctx, color)
            await confirm.confirm(
                f"__**{status}**__\n{player.choice} vs {bot}\n{PlayerScore} | {BotScore}\n繼續?"
            )

            if confirm.confirmed:
                await confirm.quit()
                continue
            else:
                break
コード例 #13
0
 async def del_confirm(t: int):
     conf = BotConfirmation(ctx, 0x0000aa)
     await conf.confirm(
         f"Delete {t} (**{self.reactions[t - 1][0]}**: {self.reactions[t - 1][1]})?"
     )
     if conf.confirmed:
         await conf.update(
             f"{t} (**{self.reactions[t - 1][0]}**: {self.reactions[t - 1][1]}) deleted",
             color=0x00aa00)
         del self.reactions[t - 1]
         self._save_cr()
     else:
         await conf.update("Cancelled", color=0xaa0000)
コード例 #14
0
ファイル: coordinates.py プロジェクト: tigersharkpr13/Inari
    async def coordset(self,
                       ctx: commands.Context,
                       x: int,
                       z: int,
                       y=62,
                       name=''):
        """
        Sets the coord of the user using format and a name(base, spawner, etc)
        **e.g**: `$coordset <x> <z> <y> <name>`
        """
        await ctx.message.delete()
        ints = [x, z, y]
        confirmation = BotConfirmation(ctx, 0xFFAE00)
        if y > 256 or y < 0:
            await ctx.send(embed=discord.Embed(
                title='Y level can\'t be higher than 256 blocks \n'
                'Or lower than 0',
                colour=0xFF0000))
            return
        await confirmation.confirm(
            f"Are you sure you want to set your coords as:\n"
            f" x: {x}/ z: {z}/ y: {y}/ name: {name}?")
        if confirmation.confirmed:
            str_of_coords = "/".join([str(i) for i in ints])
            async with aiosqlite.connect("coorddata.db") as db:
                await db.execute(
                    """INSERT INTO
                    coords(user_id, name, base_coords, guild_id)
                    VALUES (?,?,?,?)""", (
                        ctx.author.id,
                        name,
                        str_of_coords,
                        ctx.guild.id,
                    ))
                await db.commit()

            ucoord = UserCoords(user_id=ctx.author.id,
                                name=name,
                                base_coords=str_of_coords,
                                guild_id=ctx.guild.id)
            self.usercoords.append(ucoord)
            await confirmation.update(
                f"Coords set for {ctx.author.display_name}(Name: {name})"
                f"as {str_of_coords}"[:100],
                color=0xFFAE00)
        else:
            await confirmation.update("Not confirmed",
                                      hide_author=True,
                                      color=0xFF0000)
コード例 #15
0
ファイル: settings.py プロジェクト: xNathanTWx/NDiscordbot
 async def close(self, ctx):
     data = ticket_db.find_one({"guild": ctx.guild.id})
     if data == None:
         await ctx.send(":x: 此伺服器還沒有設置Ticket")
         return ''
     if ctx.channel.category.id == data['category']:
         confirm = BotConfirmation(ctx, discord.Colour.green())
         await confirm.confirm(f"關閉此Ticket?")
         if confirm.confirmed:
             await confirm.quit()
             await ctx.channel.delete()
             return ''
         else:
             await confirm.quit("已取消")
             return ''
コード例 #16
0
ファイル: coordinates.py プロジェクト: tigersharkpr13/Inari
 async def setadmincoords(self,
                          ctx: commands.Context,
                          name: str,
                          x: int,
                          z: int,
                          y=62):
     """
     **ADMIN ONLY**
     Sets a server coordinate(end portal, spawn, etc) by an admin
     If the name uses spaces wrap it in " "
     **e.g**: '$setadmincrds <name> <x> <z> <y>`
     __<y> defaults to 62 if not stated__
     """
     await ctx.message.delete()
     if y > 256 or y < 0:
         await ctx.send(embed=discord.Embed(
             title="Y level can't be higher than 256 blocks \n"
             "Or lower than 0",
             colour=0xFF0000))
         return
     ints = [x, z, y]
     str_of_coords = "/".join([str(i) for i in ints])
     confirmation = BotConfirmation(ctx, 0xFFAE00)
     await confirmation.confirm(
         f"Are you sure you want to set the admin coords as:\n"
         f" {name} x: {x}/ z: {z}/ y:{y}?")
     if confirmation.confirmed:
         await confirmation.update(
             f'Admin coords for {name} set as\n'
             f'{str_of_coords} by {ctx.author.display_name}',
             color=0xFFAE00)
         async with aiosqlite.connect("coorddata.db") as db:
             await db.execute(
                 """INSERT INTO admincoords(name, coordinates, creator, guild_id) VALUES(?,?,?,?)""",
                 (name, str_of_coords, ctx.author.id, ctx.guild.id))
             await db.commit()
         adm_coords = AdminCoords(name=name,
                                  coords=str_of_coords,
                                  creator_id=ctx.author.id,
                                  guild_id=ctx.guild.id)
         self.admincoords.append(adm_coords)
     else:
         await confirmation.update("Not confirmed",
                                   hide_author=True,
                                   color=0xFF0000)
コード例 #17
0
 async def purge(self, ctx, limit):
     if GG.checkPermission(ctx, "mm"):
         try:
             if isinstance(int(limit), int):
                 await ctx.message.delete()
                 confirmation = BotConfirmation(ctx, 0x012345)
                 await confirmation.confirm(
                     f"Are you sure you want to remove {limit} messages?")
                 if confirmation.confirmed:
                     await confirmation.update(
                         f"Confirmed, **:put_litter_in_its_place:** deleting {limit} messages...",
                         color=0x55ff55)
                     try:
                         limit = int(limit)
                     except IndexError:
                         limit = 1
                     deleted = 0
                     while limit >= 1:
                         cap = min(limit, 100)
                         deleted += len(await ctx.channel.purge(
                             limit=cap, before=ctx.message))
                         limit -= cap
                     await asyncio.sleep(8)
                     await confirmation.delete()
                 else:
                     await confirmation.delete()
             else:
                 msg = await ctx.send(
                     "I need a number for how many messages I need to purge..."
                 )
                 await asyncio.sleep(4)
                 await msg.delete()
         except ValueError:
             msg = await ctx.send(
                 "I need a number for how many messages I need to purge...")
             await asyncio.sleep(4)
             await msg.delete()
     else:
         await ctx.send(
             "I don't have the Manage_Messages permission. It's a mandatory permission, I have noted my owner about this. Please give me this permission, I will end up leaving the server if it happens again."
         )
     await GG.upCommand("purge")
コード例 #18
0
ファイル: manager.py プロジェクト: ankushKun/The-Voidkeeper
    async def delete(self, ctx, u: discord.User):
        if ctx.author.id in GODS:

            confirmation = BotConfirmation(ctx, 0x00FFFF)
            await confirmation.confirm("Are you sure?")

            if confirmation.confirmed:
                await confirmation.update("Confirmed", color=0x00FFFF)
                db.child("TOTAL-POINTS").child(u.id).remove()
                db.child("OLD-POINTS").child(u.id).remove()
            else:
                await confirmation.update("Not confirmed",
                                          hide_author=True,
                                          color=0x00FFFF)

            emb = discord.Embed(
                title="",
                description=f"{u.mention}s data has been deleted",
                color=0x00FFFF)
            await ctx.send(embed=emb)
コード例 #19
0
ファイル: CoinCog.py プロジェクト: sguo1123/SMMOBot-Teddybear
async def confirm(ctx, game, challenger, user, bet):
    confirmation = BotConfirmation(ctx, 0x012345)
    if bet == None:
        await confirmation.confirm(
            f'Would you like to accept this challenge?\nGame: `{game}`\nChallenger: `{challenger.display_name}`',
            user)
    else:
        await confirmation.confirm(
            f'Would you like to accept this challenge?\nGame: `{game}`\nChallenger: `{challenger.display_name}`\nBet: `{bet}`',
            user)
    if confirmation.confirmed:
        if bet != None:
            await confirmation.update(
                f"Confirmed\nGame: `{game}`\nChallenger: `{challenger.display_name}`\nBet: `{bet}`",
                color=0x55ff55)
        else:
            await confirmation.update("Confirmed", color=0x55ff55)
        return True
    else:
        await confirmation.update("Not confirmed", color=0xff5555)
        return False
コード例 #20
0
ファイル: kaede.py プロジェクト: united-minecrafters/kaede
    async def resetstatus(self, ctx: commands.Context):
        """
        Clear status list
        #OWNER
        """
        conf = BotConfirmation(ctx, 0x5555ff)
        await conf.confirm('Reset status list?')

        if conf.confirmed:
            try:
                config()["statuses"] = ["Hi"]
                save_config()
                self.status = cycle(config()["statuses"])
                self.status_rotate.restart()
            except Exception as e:  # noqa e722
                await conf.update("An error occurred", color=0xffff00)
            else:
                await conf.update("Reset!", color=0x55ff55)
                await self.modlog.log_message("Status Modification", "```# Reset #```", ctx.author)
        else:
            await conf.update("Canceled", color=0xff5555)
コード例 #21
0
ファイル: filters.py プロジェクト: united-minecrafters/kaede
    async def addfilteredword(self, ctx: commands.Context, *, w: str):
        """
        Add a filtered word
        #STAFF
        """
        w = w.strip("` ")
        conf = BotConfirmation(ctx, 0x5555ff)
        await conf.confirm(f'Add `{w}`?')

        if conf.confirmed:
            try:
                config()["filters"]["word_blacklist"].append(w)
                save_config()
            except Exception as e:  # noqa e722
                await conf.update("An error occurred", color=0xffff00)
            else:
                await conf.update("Added!", color=0x55ff55)
                await self.modlog.log_message("Filter Word Modification",
                                              f"```diff\n + {w}```",
                                              ctx.author)
        else:
            await conf.update("Canceled", color=0xff5555)
コード例 #22
0
ファイル: kaede.py プロジェクト: united-minecrafters/kaede
    async def addstatus(self, ctx: commands.Context, *, w: str):
        """
        Adds a status
        #OWNER
        """
        w = w.strip("` ")
        conf = BotConfirmation(ctx, 0x5555ff)
        await conf.confirm(f'Add `{w}`?')

        if conf.confirmed:
            try:
                config()["statuses"].append(w)
                save_config()
                self.status = cycle(config()["statuses"])
                self.status_rotate.restart()
            except Exception as e:  # noqa e722
                await conf.update("An error occurred", color=0xffff00)
            else:
                await conf.update("Added!", color=0x55ff55)
                await self.modlog.log_message("Status Modification", f"```diff\n + {w}```", ctx.author)
        else:
            await conf.update("Canceled", color=0xff5555)
コード例 #23
0
ファイル: coordinates.py プロジェクト: tigersharkpr13/Inari
 async def deleteadmincoords(self, ctx: commands.Context):
     """
     **ADMIN ONLY**
     Deletes the admin coords selected from the multiple choice
     """
     await ctx.message.delete()
     deladmin_gen = [(adm.name, ) for adm in self.admincoords
                     if adm.guild_id == ctx.guild.id]
     async with aiosqlite.connect("coorddata.db") as db:
         multiple_choice = BotMultipleChoice(
             ctx, [tup[0] for tup in deladmin_gen],
             "Select the coords you wish to delete",
             colour=0xFFAE00)
         await multiple_choice.run()
         await multiple_choice.quit()
         confirmation = BotConfirmation(ctx, 0xFFAE00)
         if multiple_choice.choice:
             await confirmation.confirm("Are you sure?")
             if confirmation.confirmed:
                 for adm in self.admincoords:
                     if adm.name == multiple_choice.choice and adm.guild_id == ctx.guild.id:
                         self.admincoords.remove(adm)
                 await db.execute(
                     """DELETE FROM admincoords WHERE name=? AND guild_id=?""",
                     (
                         multiple_choice.choice,
                         ctx.guild.id,
                     ))
                 await db.commit()
                 embed_del = discord.Embed(
                     title=
                     f'Admin coords for {multiple_choice.choice} deleted',
                     description=f'Deleted by {ctx.author.display_name}',
                     colour=0xFF0000)
                 await ctx.send(embed=embed_del)
             else:
                 await confirmation.update("Not confirmed",
                                           hide_author=True,
                                           color=0xff5555)
コード例 #24
0
 async def disconnect(self, ctx, user: discord.Member):
     data = pets_db.find_one({
         "user": str(user.id),
         "pet": str(ctx.author.id)
     })
     if data == None:
         await ctx.send(":x: 你並不是他的寵物!")
         return ''
     confirm = BotConfirmation(ctx, discord.Colour.green())
     await confirm.confirm(f"你要確定欸")
     if confirm.confirmed:
         await confirm.quit()
     else:
         await ctx.message.delete()
         await confirm.quit()
         return ''
     pets_db.delete_one({"user": str(user.id), "pet": str(ctx.author.id)})
     embed = discord.Embed(
         title="寵物",
         description=f"現在{user.mention}不再是{ctx.author.mention}的主人了!",
         color=discord.Colour.red())
     await ctx.send(embed=embed)
コード例 #25
0
ファイル: settings.py プロジェクト: xNathanTWx/NDiscordbot
 async def bot(self, ctx):
     if ctx.author.top_role > ctx.guild.get_member(
             ctx.bot.user.id
     ).top_role or ctx.guild.owner.id == ctx.author.id:
         pass
     else:
         await ctx.send(":x: 你沒有足夠的權限!")
         return ''
     confirm = BotConfirmation(ctx=ctx, color=discord.Colour.green())
     await confirm.confirm("確定?")
     await confirm.quit()
     if confirm.confirmed:
         data = abot_db.find_one({"id": ctx.guild.id})
         if data == None:
             abot_db.insert({"id": ctx.guild.id, "enabled": True})
             await ctx.send(embed=discord.Embed(
                 title="Anti Bot✅", color=discord.Colour.green()))
             return ''
         else:
             if data['enabled']:
                 abot_db.update({"id": ctx.guild.id},
                                {"$set": {
                                    "enabled": False
                                }})
                 await ctx.send(embed=discord.Embed(
                     title="Anti Bot❌", color=discord.Colour.red()))
                 return ''
             else:
                 abot_db.update({"id": ctx.guild.id},
                                {"$set": {
                                    "enabled": False
                                }})
                 await ctx.send(embed=discord.Embed(
                     title="Anti Bot✅", color=discord.Colour.green()))
                 return ''
     else:
         await ctx.send(
             embed=discord.Embed(title="已取消", color=discord.Colour.red()))
コード例 #26
0
ファイル: raffle.py プロジェクト: TheTercept/DiscordCrawler
    async def raffle_cancel(self, ctx, id: int = 0):
        """$raffle cancel <id> - STAFF - Stops the <id> raffle, without pulling a winner, will refund all tickets."""
        if id == 0:
            await ctx.message.delete()
            return
        else:
            raffle = await self.bot.mdb['raffle'].find_one({'id': int(id)})
            if raffle is not None:
                await ctx.message.delete()
                if raffle['ended'] == 0:
                    confirmation = BotConfirmation(ctx, 0x012345)
                    await confirmation.confirm(f"Are you sure you want to cancel the raffle with id: ({raffle['id']})?")
                    if confirmation.confirmed:
                        ch = ctx.guild.get_channel(int(raffle['channelId']))
                        await ctx.send(f"Raffle with id {raffle['id']} was canceled. Refunding all tickets to their buyers...")

                        # Refund Tickets to buyers
                        entries = await self.bot.mdb['raffleEntries'].find({"raffleId": id, "serverId": ctx.guild.id}).to_list(length=None)
                        if entries is not None:
                            for entry in entries:
                                user = await GG.MDB.points.find_one({"user": entry['userId'], "server": ctx.guild.id})
                                await GG.MDB.points.update_one({"user": entry['userId'], "server": ctx.guild.id}, {"$set": {"points": (user['points'] + entry['ticketCost'])}}, upsert=True)
                            await self.bot.mdb['raffleEntries'].delete_many({"raffleId": id, "serverId": ctx.guild.id})

                        message = await ch.fetch_message(int(raffle['msgId']))
                        await message.delete()
                        raffle['ended'] = 1
                        await self.bot.mdb['raffle'].replace_one({"id": raffle['id']}, raffle)
                        await asyncio.sleep(8)
                        await confirmation.delete()
                    else:
                        await confirmation.delete()
                else:
                    await ctx.send("This raffle was already canceled or is already ended.")
            else:
                await ctx.send(f"Raffle with Id `{id}` not found.")
                await ctx.message.delete()
コード例 #27
0
ファイル: coordinates.py プロジェクト: tigersharkpr13/Inari
    async def delshop(self,
                      ctx: commands.Context,
                      user: discord.Member = None):
        """
        Deletes the shops that the user chooses from the multiple choice embed
        **ADMIN ONLY**:
        Do `$delshop <@user>` to delete shops for that user
        """
        await ctx.message.delete()
        if user:
            if ('administrator', True) not in ctx.author.guild_permissions:
                await ctx.send(embed=discord.Embed(
                    title="You don't have the administrator permission!"))
                return
            delshops_gen = [
                shop.name for shop in self.usercoords
                if shop.user_id == user.id and shop.guild_id == ctx.guild.id
            ]
            if not delshops_gen:
                await ctx.send(embed=discord.Embed(
                    title="This user doesn't have any registered shops",
                    colour=0xFF0000))
                return
            confirmation = BotConfirmation(ctx, 0xFFAE00)
            multiple_choice = BotMultipleChoice(
                ctx,
                delshops_gen + ['Delete all shops'],
                "Select the coordinates you wish to delete",
                colour=0xFFAE00)
            await multiple_choice.run()
            await multiple_choice.quit()
            async with aiosqlite.connect("coorddata.db") as db:
                if multiple_choice.choice == 'Delete all shops':
                    await confirmation.confirm(
                        "Are you sure you want to delete all shops for this user?"
                    )
                    if confirmation.confirmed:
                        await confirmation.update("Confirmed", color=0xFFAE00)
                        await db.execute(
                            "DELETE FROM shops WHERE guild_id=? AND user_id=?",
                            (ctx.guild.id, user.id))
                        await db.commit()
                        for shop in self.shops:
                            if shop.user_id == user.id and shop.guild_id == ctx.guild.id:
                                self.usercoords.remove(shop)
                        embed_delete = discord.Embed(
                            title=f"All of {user.display_name}'s shops deleted",
                            colour=0xFFAE00)
                        await ctx.send(embed=embed_delete)
                    else:
                        await confirmation.update("Not confirmed",
                                                  hide_author=True,
                                                  color=0xFF0000)

                elif multiple_choice.choice:
                    await confirmation.confirm(
                        f"Are you sure you want to delete {multiple_choice.choice}?"
                    )
                    if confirmation.confirmed:
                        await confirmation.update(
                            f"{user.display_name}'s ({multiple_choice.choice}) shop deleted",
                            color=0xFFAE00)
                        await db.execute(
                            "DELETE FROM shops WHERE guild_id=? AND user_id=? AND name=?",
                            (ctx.guild.id, user.id, multiple_choice.choice))
                        await db.commit()
                        for shop in self.shops:
                            if (shop.name == multiple_choice.choice
                                    and shop.user_id == user.id
                                    and shop.guild_id == ctx.guild.id):
                                self.usercoords.remove(shop)
                    else:
                        await confirmation.update("Not confirmed",
                                                  hide_author=True,
                                                  color=0xFF0000)
        else:
            author_shops = [
                shop.name for shop in self.shops if
                shop.user_id == ctx.author.id and shop.guild_id == ctx.guild.id
            ]
            if not author_shops:
                await ctx.send(embed=discord.Embed(
                    title='You have no shops set!', colour=0xFF0000))
                return
            multiple_choice = BotMultipleChoice(
                ctx,
                author_shops,
                "Select the shop you wish to delete",
                colour=0xFFAE00)
            await multiple_choice.run()
            await multiple_choice.quit()
            if multiple_choice.choice:
                confirmation = BotConfirmation(ctx, 0xFFAE00)
                await confirmation.confirm(
                    f"Are you sure you want to delete {multiple_choice.choice}?"
                )
                if confirmation.confirmed:
                    for shop in self.shops:
                        if (shop.name == multiple_choice.choice
                                and shop.guild_id == ctx.guild.id
                                and shop.user_id == ctx.author.id):
                            self.shops.remove(shop)
                    async with aiosqlite.connect("coorddata.db") as db:
                        await db.execute(
                            """DELETE FROM shops WHERE user_id=? AND name=? AND guild_id=?""",
                            (ctx.author.id, multiple_choice.choice,
                             ctx.guild.id))
                        await db.commit()
                        await confirmation.update(
                            f"Your shop: ({multiple_choice.choice}) has been deleted",
                            color=0xFFAE00)
                else:
                    await confirmation.update("Not confirmed",
                                              hide_author=True,
                                              color=0xFF0000)
コード例 #28
0
    async def register(
        self,
        ctx: commands.context,
        pluralkit_member_id: str,
        account: discord.Member,
    ):
        """
        Creates a new Polyphony member instance

        :param ctx: Discord Context
        :param pluralkit_member_id: PluralKit system or member id
        :param account: Main Account to be extended from
        """

        log.debug("Registering new member...")

        logger = LogMessage(ctx, title="Registering...")
        await logger.init()

        async with ctx.channel.typing():
            # Error: Account is not a user
            if account.bot is True:
                await logger.set(
                    title="Error Registering: Bad Account Pairing",
                    color=discord.Color.red(),
                )
                await logger.log(f"{account.mention} is a bot user")
                return

            # Get available tokens
            token = conn.execute(
                "SELECT * FROM tokens WHERE used == 0").fetchone()

            # Error: No Slots Available
            if not token:
                await logger.set(
                    title=":x: Error Registering: No Slots Available",
                    color=discord.Color.red(),
                )
                await logger.log(
                    f":x: No tokens in queue. Run `{self.bot.command_prefix}tokens` for information on how to add more."
                )
                return

            # Error: Duplicate Registration
            check_duplicate = conn.execute(
                "SELECT * FROM members WHERE pk_member_id == ?",
                [pluralkit_member_id],
            ).fetchone()
            if check_duplicate:
                await logger.set(
                    title=":x: Error Registering: Member Already Registered",
                    color=discord.Color.red(),
                )
                await logger.log(
                    f":x: Member ID `{pluralkit_member_id}` is already registered with instance {self.bot.get_user(check_duplicate['id'])}"
                )
                return

            # Fetch member from PluralKit
            await logger.log(":hourglass: Fetching member from PluralKit...")
            member = await pk_get_member(pluralkit_member_id)

            # Error: Member not found
            if member is None:
                await logger.set(
                    title=":x: Error Registering: Member ID invalid",
                    color=discord.Color.red(),
                )
                await logger.log(
                    f":x: Member ID `{pluralkit_member_id}` was not found")
                return

            # Error: Missing PluralKit Data
            if (member["name"] is None or member["avatar_url"] is None
                    or member["proxy_tags"] is None):
                await logger.set(
                    title=":x: Error Registering: Missing PluralKit Data",
                    color=discord.Color.red(),
                )
                if member["name"] is None:
                    await logger.log(":warning: Member is missing a name")
                if member["avatar_url"] is None:
                    await logger.log(":warning: Member is missing an avatar")
                if member["proxy_tags"] is None:
                    await logger.log(":warning: Member is missing proxy tags")
                await logger.log(
                    "\n:x: *Please check the privacy settings on PluralKit*")
                return

            system_name = f"__**{member['name']}**__ (`{member['id']}`)"
            await logger.edit(
                -1,
                f":white_check_mark: Fetched member __**{member['name']}**__ (`{member['id']}`)",
            )

            # Confirm add
            confirmation = BotConfirmation(ctx, discord.Color.blue())
            await confirmation.confirm(
                f":grey_question: Create member for {account} with member {system_name}?"
            )
            if confirmation.confirmed:
                await confirmation.message.delete()
            else:
                await confirmation.message.delete()
                await logger.set(title=":x: Registration Cancelled",
                                 color=discord.Color.red())
                await logger.log(":x: Registration cancelled by user")
                return

            # Check if user is new to Polyphony
            if (conn.execute("SELECT * FROM users WHERE id = ?",
                             [account.id]).fetchone() is None):
                await logger.log(
                    f":tada: {account.mention} is a new user! Registering them with Polyphony"
                )
                conn.execute("INSERT INTO users VALUES (?, NULL, NULL)",
                             [account.id])
                conn.commit()

            # Insert member into database
            await logger.log(":hourglass: Adding to database...")
            try:
                insert_member(
                    token["token"],
                    member["id"],
                    account.id,
                    decode_token(token["token"]),
                    member["name"],
                    member["display_name"],
                    member["avatar_url"],
                    member["proxy_tags"],
                    member["keep_proxy"],
                    member_enabled=True,
                )
                await logger.edit(-1, ":white_check_mark: Added to database")

            # Error: Database Error
            except sqlite3.Error as e:
                log.error(e)
                await logger.set(
                    title=":x: Error Registering: Database Error",
                    color=discord.Color.red(),
                )
                await logger.edit(-1, ":x: An unknown database error occurred")
                return

            # Mark token as used
            conn.execute(
                "UPDATE tokens SET used = 1 WHERE token = ?",
                [token["token"]],
            )
            conn.commit()

            # Create Instance
            await logger.log(":hourglass: Syncing Instance...")
            instance = PolyphonyInstance(pluralkit_member_id)
            asyncio.run_coroutine_threadsafe(instance.start(token["token"]),
                                             self.bot.loop)
            await instance.wait_until_ready()

            sync_error_text = ""

            # Update Username
            await logger.edit(-1, f":hourglass: Syncing Username...")
            out = await instance.update_username(member["name"])
            if out != 0:
                sync_error_text += f"> {out}\n"

            # Update Avatar URL
            await logger.edit(-1, f":hourglass: Syncing Avatar...")
            out = await instance.update_avatar(member["avatar_url"])
            if out != 0:
                sync_error_text += f"> {out}\n"

            # Update Nickname
            await logger.edit(-1, f":hourglass: Syncing Nickname...")
            out = await instance.update_nickname(member["display_name"])
            if out < 0:
                sync_error_text += f"> PluralKit display name must be 32 or fewer in length if you want to use it as a nickname"
            elif out > 0:
                sync_error_text += f"> Nick didn't update on {out} guild(s)\n"

            # Update Roles
            await logger.edit(-1, f":hourglass: Updating Roles...")
            out = await instance.update_default_roles()
            if out:
                sync_error_text += f"> {out}\n"

            if sync_error_text == "":
                await logger.edit(-1, ":white_check_mark: Synced instance")
            else:
                await logger.edit(-1, ":warning: Synced instance with errors:")
                await logger.log(sync_error_text)

        # Success State
        logger.content = []
        await logger.set(
            title=f":white_check_mark: Registered __{member['name']}__",
            color=discord.Color.green(),
        )

        slots = conn.execute("SELECT * FROM tokens WHERE used = 0").fetchall()
        await logger.log(f":arrow_forward: **User is {instance.user.mention}**"
                         )
        if sync_error_text != "":
            await logger.log(":warning: Synced instance with errors:")
            await logger.log(sync_error_text)
        await logger.log(f"*There are now {len(slots)} slots available*")
        log.info(
            f"{instance.user} ({instance.pk_member_id}): New member instance registered ({len(slots)} slots left)"
        )
        await instance.close()
コード例 #29
0
ファイル: admin.py プロジェクト: eggnoginsquad/Polyphony
    async def register(
        self,
        ctx: commands.context,
        pluralkit_member_id: str,
        account: discord.Member,
    ):
        """
        Creates a new Polyphony member instance

        :param ctx: Discord Context
        :param pluralkit_member_id: PluralKit system or member id
        :param account: Main Account to be extended from
        """

        log.debug("Registering new member...")

        logger = LogMessage(ctx, title="Registering...")
        await logger.init()

        instance = None

        async with ctx.channel.typing():
            await logger.log("Fetching member from PluralKit...")
            member = await pk_get_member(pluralkit_member_id)

            # Member exists
            if member is not None:
                system_names = [f"{member['name']} (`{member['id']}`)"]
                await logger.log(
                    f"Fetched member -> {member['name']} (`{member['id']}`)")
                tokens = get_unused_tokens()

                # Fail: No Slots Available
                if len(tokens) == 0:
                    logger.title = "Error Registering: No Slots Available"
                    logger.color = discord.Color.red()
                    await logger.log(
                        f"No tokens in queue. Run `{self.bot.command_prefix}tokens` for information on how to add more."
                    )
                    return

                # Confirm add
                confirmation = BotConfirmation(ctx, discord.Color.blue())
                await confirmation.confirm(
                    f"Create member for {account} with member {', '.join(system_names)}?"
                )
                if confirmation.confirmed:
                    await confirmation.message.delete()
                    await logger.log("Adding to database...")
                else:
                    await confirmation.message.delete()
                    logger.title = "Extend Cancelled"
                    logger.color = discord.Color.red()
                    await logger.log("Registration cancelled by user")
                    return

                # Get a token and update as used
                bot_token = tokens[0]
                update_token_as_used(bot_token["token"])

                # Insert new user into users database
                if get_user(account.id) is None:
                    await logger.log(
                        f"{account.mention} is a new user! Registering them with Polyphony"
                    )
                    insert_user(account.id)

                # Insert member unless already registered
                if get_member(pluralkit_member_id) is None:
                    insert_member(
                        bot_token["token"],
                        member["id"],
                        account.id,
                        0,
                        member["name"],
                        member["display_name"],
                        member["avatar_url"],
                        member["proxy_tags"][0],
                        member["keep_proxy"],
                        member_enabled=True,
                    )

                # Fail: Member Already Registered
                else:
                    logger.title = "Member Already Registered with Polyphony"
                    logger.color = discord.Color.light_grey()
                    await logger.log(
                        f"Member ID `{pluralkit_member_id}` was already registered with Polyphony"
                    )
                    return
                await logger.log("Creating member instance...")
                instance = create_member_instance(get_member(member["id"]))

            # Fail: Invalid ID
            else:
                logger.title = "Error Registering: Member ID invalid"
                logger.color = discord.Color.red()
                await logger.log(
                    f"Member ID `{pluralkit_member_id}` was not found")
                return

        # Success State
        logger.title = f"Registration of {member['name']} Successful"
        logger.color = discord.Color.green()
        c.execute("SELECT * FROM tokens WHERE used = 0")
        slots = c.fetchall()
        await logger.log(f"There are now {len(slots)} slots available")
        await logger.log(f"\nUser is {instance.user.mention}")
        log.info("New member instance extended and activated")