Пример #1
0
    async def rtfm(self,
                   ctx: commands.Context,
                   doc: str = None,
                   *,
                   term: str = None):
        print(doc, term)
        doc = doc.lower()
        target = None
        for aliases, target_name in self.aliases.items():
            print(aliases, doc in target_name)
            if doc in aliases:
                target = target_name

        if not target:
            return await ctx.send("Alias/target not found")

        cache = self.cache.get(target)
        if not cache:
            await ctx.trigger_typing()
            await self.build(target)
            cache = self.cache.get(target)

        results = fuzzy.finder(term,
                               list(cache.items()),
                               key=lambda x: x[0],
                               lazy=False)[:8]  # type: ignore

        await ctx.send(embed=Embed(
            title=f"Searched for {term} in {target}",
            description="\n".join([f"[{key}]({url})" for key, url in results]),
            color=Color.dark_purple(),
        ))
Пример #2
0
 async def leaderboard_(self, ctx):
     cookies = load(open('resources/cookies.json', 'r'))
     cookies = sorted(cookies.items(),
                      key=lambda kv: kv[1]['cookies'],
                      reverse=True)
     length = 10 if len(cookies) > 10 else len(cookies)
     embed = Embed(color=Color.dark_purple())
     embedValue = ''
     for i in range(length):
         amt = cookies[i][1]['cookies']
         embedValue += '{}. {}: {:,} {}\n\n'.format(i + 1,
                                                    cookies[i][1]['name'],
                                                    amt,
                                                    sform(amt, 'печенька'))
     embed.add_field(name='Глобальный топ', value=embedValue, inline=False)
     embed.add_field(name='\u200b', value='\u200b', inline=False)
     embedValue = ''
     i = 0
     for holder in cookies:
         if ctx.guild.get_member(holder[1]['id']) is not None:
             amt = holder[1]['cookies']
             embedValue += '{}. {}: {:,} {}\n\n'.format(
                 i + 1, holder[1]['name'], amt, sform(amt, 'печенька'))
             i += 1
             if i == length:
                 break
     embed.add_field(name='Топ сервера', value=embedValue, inline=False)
     return await ctx.send('{}'.format(ctx.author.mention), embed=embed)
Пример #3
0
 async def ping_(self, ctx):
     embed = Embed(color=Color.dark_purple(), description='Pong')
     ts = time()
     msg = await ctx.send(embed=embed)
     tm = (time() - ts) * 1000
     embed.description = '{:.2f}ms'.format(tm)
     return await msg.edit(embed=embed)
Пример #4
0
def random():
    # type: () -> Color

    chilipepper = Color(0x9B1B30)
    tan = Color(0xBEAA3E)
    icedcoffee = Color(0xB18F6A)

    return choice([
        Color.teal(),
        Color.dark_teal(),
        Color.green(),
        Color.dark_green(),
        Color.blue(),
        Color.dark_blue(),
        Color.purple(),
        Color.dark_purple(),
        Color.magenta(),
        Color.dark_magenta(),
        Color.gold(),
        Color.dark_gold(),
        Color.orange(),
        Color.dark_orange(),
        Color.red(),
        Color.dark_red(),
        Color.lighter_grey(),
        Color.darker_grey(),
        Color.blurple(),
        tan,
        icedcoffee,
        chilipepper,
    ])
Пример #5
0
def random():
    # type: () -> Color

    tan = Color(0xBEAA3E)

    return choice([
        Color.teal(),
        Color.dark_teal(),
        Color.green(),
        Color.dark_green(),
        Color.blue(),
        Color.dark_blue(),
        Color.purple(),
        Color.dark_purple(),
        Color.magenta(),
        Color.dark_magenta(),
        Color.gold(),
        Color.dark_gold(),
        Color.orange(),
        Color.dark_orange(),
        Color.red(),
        Color.dark_red(),
        Color.lighter_grey(),
        Color.darker_grey(),
        Color.blurple(),
        tan,
    ])
Пример #6
0
    async def trends(self, ctx, stock: str):
        """See the latest trends of a stock!"""
        is_valid = await self.cf.check_handle(stock)
        if ";" in stock or not is_valid[0]:
            await ctx.channel.send(embed=self.embed(ctx.author.mention +
                                                    ", Not a valid stock!"))
            return
        changes = await self.cf.get_rating_changes(stock)
        if not changes:
            await ctx.channel.send(
                embed=self.embed(ctx.author.mention +
                                 ", No recent trends found."))
            return

        profit_symbol = ":arrow_up_small:"
        loss_symbol = ":small_red_triangle_down:"

        result = []
        for name, old, new, time in changes:
            oldvalue = self.stock_value(old)
            value = self.stock_value(new)
            symbol = profit_symbol if new >= old else loss_symbol
            percent = round(abs(oldvalue - value) / oldvalue * 100, 2)
            result.append("**$%.2f** ⟶ **$%.2f** %s (%.2f%s)" %
                          (oldvalue, value, symbol, percent, "%"))
        e = Embed(title="Recent trends for %s" % stock,
                  description="\n".join(result),
                  color=Color.dark_purple())
        e.set_footer(text="Requested by " + str(ctx.author),
                     icon_url=ctx.author.avatar_url)
        await ctx.channel.send(embed=e)
Пример #7
0
def random():
    c = [
        Color.teal(),
        Color.dark_teal(),
        Color.green(),
        Color.dark_green(),
        Color.blue(),
        Color.dark_blue(),
        Color.purple(),
        Color.dark_purple(),
        Color.magenta(),
        Color.dark_magenta(),
        Color.gold(),
        Color.dark_gold(),
        Color.orange(),
        Color.dark_orange(),
        Color.red(),
        Color.dark_red(),
        Color.lighter_grey(),
        Color.darker_grey(),
        Color.blurple(),
        tan,
        icedcoffee,
        chilipepper
    ]
    return c[randint(0, len(c) - 1)]
Пример #8
0
 def __init__(self, client):
     self.client = client
     self.client_color = Color.red()
     self.color_dict = {
         1: [Color.teal(), 'teal'],
         2: [Color.dark_teal(), 'dark_teal'],
         3: [Color.green(), 'green'],
         4: [Color.dark_green(), 'dark_green'],
         5: [Color.blue(), 'blue'],
         6: [Color.dark_blue(), 'dark_blue'],
         7: [Color.purple(), 'purple'],
         8: [Color.dark_purple(), 'dark_purple'],
         9: [Color.magenta(), 'magenta'],
         10: [Color.dark_magenta(), 'dark_magenta'],
         11: [Color.gold(), 'gold'],
         12: [Color.dark_gold(), 'dark_gold'],
         13: [Color.orange(), 'orange'],
         14: [Color.dark_orange(), 'dark_orange'],
         15: [Color.red(), 'red'],
         16: [Color.dark_red(), 'dark_red'],
         17: [Color.lighter_grey(), 'lighter_grey'],
         18: [Color.dark_grey(), 'grey'],
         19: [Color.light_grey(), 'light_grey'],
         20: [Color.darker_grey(), 'darker_grey']
     }
Пример #9
0
def status_embed(member: Member, *, description: str = "") -> Embed:
    """Construct status embed for certain member."""
    embed = Embed(title=member.display_name,
                  description=description,
                  color=Color.dark_purple())

    if member.status == Status.offline:
        embed.add_field(name="**DEVICE**", value=":no_entry:")
    elif member.is_on_mobile():
        embed.add_field(name="**DEVICE**", value="Phone: :iphone:")
    else:
        embed.add_field(name="**DEVICE**", value="PC: :desktop:")

    embed.add_field(name="**Status**",
                    value=get_member_status(member=member),
                    inline=False)
    embed.add_field(name="**Joined server at**",
                    value=member.joined_at,
                    inline=False)
    embed.add_field(name="**Roles**",
                    value=get_member_roles_as_mentions(member),
                    inline=False)
    embed.add_field(name="**Activity**",
                    value=get_member_activity(member=member),
                    inline=False)
    embed.set_thumbnail(url=member.avatar_url)

    return embed
Пример #10
0
    async def roll(self, ctx, args=""):
        dice = args.split("d")

        secrets = {
            "adb":
            "Don't get smart with me. Replace A and B with positive integers.",
            "d": "I don't want the d...",
            "a": "B, C, D, E, F... Wait, this isn't preschool!",
        }

        secret = args.lower()
        if secret in secrets:
            await ctx.send(secrets[secret])

        elif len(dice) != 2:
            await ctx.send(f"'{args}' doesn't look like a dice roll to me..." +
                           " Did you mean >help roll?" * ("help" in args))

        elif not dice[0].isdigit() or not dice[1].isdigit():
            await ctx.send(
                "The format is AdB, where A and B are natural numbers (1, 2, 3, 4)."
            )

        else:
            dice[0], dice[1] = int(dice[0]), int(dice[1])
            if dice[0] < 1:
                await ctx.send("I need to roll at least *one* dice, bud.")

            elif dice[0] > 10:
                await ctx.send(
                    "I appreciate the enthusiasm, but you can only roll up to 10 dice at once."
                )

            elif dice[1] < 2:
                await ctx.send(
                    "I cannot mathematically roll anything less than a d2 and still call it rolling."
                )

            elif dice[1] > 1000:
                await ctx.send(
                    "Going beyond a d1000 is a bit silly, so... Don't.")

            else:
                total = 0
                results = []
                for i in range(dice[0]):
                    result = randint(1, dice[1])
                    results.append(str(result))
                    total = total + result
                resultstr = f"{args}: {', '.join(results)} = {total}."

                emb = Embed(**{
                    "description": resultstr,
                },
                            color=Color.dark_purple(),
                            timestamp=datetime.now())
                emb.set_author(name=ctx.author.name,
                               icon_url=ctx.author.avatar_url)
                await ctx.send(embed=emb)
Пример #11
0
 async def fact_(self, ctx, *, msg=None):
     user = ctx.author
     if msg is None:
         msg = user.mention
     with open('resources/facts.json', 'r') as f:
         facts = load(f)
         fact = choice(facts)
     embed = Embed(color=Color.dark_purple(), description=fact)
     return await ctx.send(msg, embed=embed)
Пример #12
0
 async def raccoon_(self, ctx, *, msg=None):
     user = ctx.author
     if msg is None:
         msg = user.mention
     with open('resources/raccoons.txt', 'r') as f:
         raccoons = load(f)
         raccoon = choice(raccoons)
     embed = Embed(color=Color.dark_purple())
     embed.set_image(url=raccoon)
     return await ctx.send(msg, embed=embed)
Пример #13
0
 async def ops_(self, ctx, *, nickname):
     api_link = 'https://osu.ppy.sh/api/'
     params = {'k': osu_key, 'u': nickname}
     async with ClientSession() as client:
         plays = await client.get(api_link + 'get_user_best',
                                  params=params,
                                  timeout=2)
         plays = await plays.json()
     if not plays:
         return await ctx.send('Пользователь не найден')
     embed = Embed(color=Color.dark_purple(), description='Loading...')
     msg = await ctx.send(ctx.author.mention, embed=embed)
     embed = Embed(color=Color.dark_purple())
     for i in range(len(plays)):
         params = {'k': osu_key, 'b': plays[i]['beatmap_id']}
         async with ClientSession() as client:
             info = await client.get(api_link + 'get_beatmaps',
                                     params=params)
             info = await info.json()
             info = info[0]
         accuracy = round(
             (int(plays[i]['count300']) * 300 + int(plays[i]['count100']) *
              100 + int(plays[i]['count50']) * 50) /
             ((int(plays[i]['count300']) + int(plays[i]['count100']) +
               int(plays[i]['count50'])) * 3), 2)
         combo = '{:,} ({})'.format(
             int(plays[i]['maxcombo']), 'FC' if plays[i]['maxcombo']
             == info['max_combo'] else info['max_combo'])
         mods = str(osumods(int(plays[i]['enabled_mods']))).replace(
             'osumods.', '', 1)
         if 'NC' in mods:
             mods = mods.replace('|DT', '')
         if 'PF' in mods:
             mods = mods.replace('|SD', '')
         name = '{}. {} [{}] ({})'.format(i + 1, info['title'],
                                          info['version'], mods)
         value = 'Score: {:,}; Combo: {}; PP: {:,}; Acc: {}%; Rank: {}'.format(
             int(plays[i]['score']), combo, round(float(plays[i]['pp']), 2),
             accuracy, plays[i]['rank'].replace('H', '', 1))
         embed.add_field(name=name, value=value, inline=False)
     await msg.edit(content=ctx.author.mention, embed=embed)
Пример #14
0
class card(object):
    roman_map = [
        "Egg", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X",
        "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX",
        "XIX"
    ]
    majors = [
        "The Fool", "The Magician", "The High Priestess", "The Empress",
        "The Emperor", "The Heirophant", "The Lovers", "The Chariot",
        "Justice", "The Hermit", "Wheel of Fortune", "Strength",
        "The Hanged Man", "Death", "Temperance", "The Devil", "The Tower",
        "The Star", "The Moon", "The Sun", "Judgement", "The World"
    ]
    court_conversion = {
        11: "Sister",
        12: "Brother",
        13: "Mother",
        14: "Father"
    }

    color_map = {
        suit.Majors: Color.dark_purple(),
        suit.Cups: Color.blue(),
        suit.Wands: Color.red(),
        suit.Swords: Color.gold(),
        suit.Pentacles: Color.green(),
        "back": Color.dark_grey()
    }

    def __init__(self, suit, number):
        self.suit = suit
        self.number = number
        self.flipped = False

    def __str__(self):
        if not self.flipped:
            return "Hidden Card"
        elif self.suit == suit.Majors:
            return f"{card.roman_map[self.number]}: {card.majors[self.number]}"
        elif self.number in card.court_conversion:
            return f"{card.court_conversion[self.number]} {self.suit.value}"
        else:
            return f"{card.roman_map[self.number]} {self.suit.value}"

    def embed(self):
        this_embed = Embed(color=card.color_map[self.suit]
                           if self.flipped else card.color_map["back"],
                           title=str(self))
        return this_embed
Пример #15
0
 async def changelog_(self, ctx):
     repo = Repo(getcwd())
     commits = list(repo.iter_commits('master'))
     cnt = 0
     unique = []
     embed = Embed(color=Color.dark_purple(),
                   title='Последние изменения',
                   description='')
     for commit in commits:
         if commit.message not in unique:
             unique.append(commit.message)
             cnt += 1
             embed.description += f'\n{strftime("%d-%m-%Y", gmtime(commit.authored_date - commit.author_tz_offset))}: {commit.message.strip()}'
         if cnt == 20:
             return await ctx.send(embed=embed)
Пример #16
0
 async def inspire_(self, ctx, *, msg=None):
     user = ctx.author
     if msg is None:
         msg = user.mention
     proxy = ProxyConnector.from_url('socks4://180.250.253.155:45123')
     async with ClientSession(connector=proxy) as client:
         try:
             image = await client.get(
                 'http://inspirobot.me/api?generate=true')
         except ClientProxyConnectionError:
             return await ctx.send('Ошибка подключения к прокси')
         image = await image.text()
     embed = Embed(color=Color.dark_purple())
     embed.set_image(url=image)
     return await ctx.send(msg, embed=embed)
Пример #17
0
 async def op_(self, ctx, *, nickname):
     api_link = 'https://osu.ppy.sh/api/'
     params = {'k': osu_key, 'u': nickname}
     async with ClientSession() as client:
         r = await client.get(api_link + 'get_user',
                              params=params,
                              timeout=2)
         r = await r.json()
     if not r:
         return await ctx.send('Пользователь не найден')
     result = r[0]
     if result['playcount'] is None:
         return await ctx.send('Слишком мало информации по пользователю')
     embed = Embed(color=Color.dark_purple(),
                   title=result['username'],
                   url='https://osu.ppy.sh/users/{}'.format(
                       result['user_id']))
     embed.set_thumbnail(
         url='https://a.ppy.sh/{}'.format(result['user_id']))
     embed.add_field(name='Rank',
                     value='{:,}'.format(int(result['pp_rank'])),
                     inline=False)
     embed.add_field(name='Country rank :flag_{}:'.format(
         result['country'].lower()),
                     value='{:,}'.format(int(result['pp_country_rank'])),
                     inline=False)
     embed.add_field(name='PP',
                     value='{:,}'.format(round(float(result['pp_raw']))),
                     inline=False)
     embed.add_field(name='Accuracy',
                     value=str(round(float(result['accuracy']), 2)) + '%',
                     inline=False)
     embed.add_field(name='Level',
                     value=str(int(float(result['level']))),
                     inline=False)
     embed.add_field(name='Play Count',
                     value='{:,}'.format(int(result['playcount'])),
                     inline=False)
     embed.add_field(name='Ranked Score',
                     value='{:,}'.format(int(result['ranked_score'])),
                     inline=False)
     embed.add_field(name='Total Score',
                     value='{:,}'.format(int(result['total_score'])),
                     inline=False)
     await ctx.send(ctx.author.mention, embed=embed)
Пример #18
0
    async def on_message(self, message):

        if self.c.logMessages:
            self.logger.log_message(message)

        if self.busy:
            return

        if not message.author == self.user:
            print(message.content)
            e = await self.create_embed(
                "Github CeroProgramming", "https://github.com/CeroProgramming",
                "GitHub Profile URL", Color.dark_purple(), "CeroProgramming",
                "https://github.com/CeroProgramming/",
                "https://avatars3.githubusercontent.com/u/22818389?s=460&v=4",
                "https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fimage.freepik.com%2Ffree-icon%2Fgithub-logo_318-53553.jpg&f=1"
            )
            await self.io_embed(message.channel, e)

        if message.content == "shutdown":
            await self.shutdown()
Пример #19
0
    async def members(self, ctx: Context) -> None:
        """Returns the number of members in a server."""
        member_by_status = Counter(str(m.status) for m in ctx.guild.members)
        bots = len([member for member in ctx.guild.members if member.bot])
        type = f"""
                Humans: {ctx.guild.member_count - bots}
                Bots: {bots}
            """
        status = f"""
                {STATUSES[Status.online]} {member_by_status["online"]}
                {STATUSES[Status.idle]} {member_by_status["idle"]}
                {STATUSES[Status.dnd]} {member_by_status["dnd"]}
                {STATUSES[Status.offline]} {member_by_status["offline"]}
            """
        embed = Embed(title="Member count",
                      description=ctx.guild.member_count,
                      color=Color.dark_purple())
        embed.add_field(name="**❯❯ Member Status**", value=status)
        embed.add_field(name="**❯❯ Member Type**", value=type)
        embed.set_author(name=f"SERVER : {ctx.guild.name}")

        await ctx.send(embed=embed)
Пример #20
0
    async def members(self, ctx: Context) -> None:
        """Returns the number of members in a server."""
        member_by_status = Counter(str(m.status) for m in ctx.guild.members)
        bots = len([member for member in ctx.guild.members if member.bot])
        type = f"""
                Humans: {ctx.guild.member_count - bots}
                Bots: {bots}
            """
        status = f"""
                <:online:346921745279746048> {member_by_status["online"]}
                <:away:346921747330891780> {member_by_status["idle"]}
                <:dnd:346921781786836992> {member_by_status["dnd"]}
                <:offline:346921814435430400> {member_by_status["offline"]}
            """
        embed = Embed(title="Member count",
                      description=ctx.guild.member_count,
                      color=Color.dark_purple())
        embed.add_field(name="**❯❯ Member Status**", value=status)
        embed.add_field(name="**❯❯ Member Type**", value=type)
        embed.set_author(name=f"SERVER : {ctx.guild.name}")

        await ctx.send(embed=embed)
Пример #21
0
    async def rtfm(self, ctx: commands.Context, doc: str, *, term: str = None):
        """
        Search through docs of a module/python
        Args: target, term
        """
        doc = doc.lower()
        target = None
        for aliases, target_name in self.aliases.items():
            if doc in aliases:
                target = target_name

        if not target:
            return await ctx.reply("Alias/target not found")
        if not term:
            return await ctx.reply(self.targets[target])

        cache = self.cache.get(target)
        if not cache:
            await ctx.trigger_typing()
            await self.build(target)
            cache = self.cache.get(target)

        results = fuzzy.finder(term,
                               list(cache.items()),
                               key=lambda x: x[0],
                               lazy=False)[:8]  # type: ignore

        if not results:
            return await ctx.reply("Couldn't find any results")

        await ctx.reply(embed=Embed(
            title=f"Searched in {target}",
            description="\n".join(
                [f"[`{key}`]({url})" for key, url in results]),
            color=Color.dark_purple(),
        ))
Пример #22
0
    async def setup(self):

        owner = await self._get_owner_by_id()
        await self.io_message(owner, 'Welcome. I am the CeroXBot aka CXBot. You or someone who knows your ID has set you as my owner. If you don\'t know about me, this is probably a mistake, simply ignore me in this case. Otherwise, can we start with the setup? If yes type \'start\'.')
        await self.wait_for_message(timeout=None, author=owner, content='start')
        await self.io_message(owner, 'Do not use me on diffrent servers in this state of development. If you want to use me on diffrent servers, create multiple instances with a unique bot token per instance.')
        await self.io_message(owner, 'Do you want to set my name? (This means the name that will be displayed in the developer settings and if you don\'t set a nickname.) (No/Yes)')
        b = await self._wait_for_bool(owner)
        if b:
            await self.io_message(owner, 'Okay, which one?')
            message = await self.wait_for_message(timeout=None, author=owner)
            await self.edit_profile(username=message.content)
        await self.io_message(owner, 'Do you like me to have a nickname? (No/Yes)')
        b = await self._wait_for_bool(owner)
        if b:
            await self.io_message(owner, 'Okay, which one?')
            message = await self.wait_for_message(timeout=None, author=owner)
            self.c.nickname = message.content
            await self.io_message(owner, 'Shall I try to set my nickname? (Never[0]/Always[1]/Only if added to a new server[2]')
            self.c.autoSetNickname = await self._wait_for_list(owner, ['0', '1', '2'])
        else:
            del self.c.nickname
        await self.io_message(owner, 'Do you like to set my avatar now? (No/Yes)')
        b = await self._wait_for_bool(owner)
        if b:
            await self.io_message(owner, 'Send the picture..')
            url = await self._wait_for_picture_url(owner)
            self.c.avatarUrl = "config/avatar.%s" % (url.split(".")[len(url.split("."))-1])
            user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
            headers={'User-Agent':user_agent,}
            request=urllib.request.Request(url,None,headers)
            response = urllib.request.urlopen(request)
            data = response.read()
            await self.edit_profile(avatar=data)
        await self.io_message(owner, 'Do you want me to use a prefix that is needed to trigger commands? (No/Yes)')
        b = await self._wait_for_bool(owner)
        if b:
            await self.io_message(owner, 'Which one? It can be a whole string, but I will cut all trailing whitspaces.')
            message = await self.wait_for_message(timeout=None, author=owner)
            while message.content.endswith(' '):
                message.content = message.content[:-1]
            self.c.prefix = message.content
        else:
            del self.c.prefix
        await self.send_message(owner, content="Shall I save logs? (No/Yes)")
        b = await self._wait_for_bool(owner)
        if b:
            self.c.logging = b
            await self.io_message(owner, 'Okay, I log all basic stuff.')
            await self.io_message(owner, 'Shall I also log all messages? (No/Yes)')
            self.c.logMessages = await self._wait_for_bool(owner)
            await self.io_message(owner, 'Shall I also log all interactions between me and everything else? (No/Yes)')
            self.c.logBotActivities = await self._wait_for_bool(owner)
            await self.io_message(owner, 'Shall I log all public available user data like online time and played games? (this may or may not generate huge amounts of data) (No/Yes)')
            self.c.logUserActivities = await self._wait_for_bool(owner)
        else:
            self.c.logMessages = False
            self.c.logBotActivities = False
            self.c.logUserActivities = False
        await self.io_message(owner, 'Do you want me to track all played games? (some functions will not work otherwise) (No/Yes)')
        self.c.trackGameHistory = await self._wait_for_bool(owner)
        await self.io_message(owner, 'Do you want me to track statistics about how much games were played? (some functions will not work otherwise) (No/Yes)')
        self.c.trackGameStatistics = await self._wait_for_bool(owner)
        await self.io_message(owner, 'Do you want me to automatically create permament roles for registered games? (No/Yes)')
        self.c.autoCreateGameRoles = await self._wait_for_bool(owner)
        if self.c.autoCreateGameRoles:
            await self.io_message(owner, 'Do you want me to automatically register games that somebody played? (this may cause unwanted behavior if a game or process is recognized wrong or if someone renamed a game in his settings) (No/Yes)')
            self.c.autoAddGames = await self._wait_for_bool(owner)
            await self.io_message(owner, 'Do you want me to automatically append roles to users that play the respective game? (No/Yes)')
            self.c.autoGiveGameRoles = await self._wait_for_bool(owner)
            self.c.autoCreateTemporaryGameRoles = False # TODO outsource into config,py
        else:
            await self.io_message(owner, 'Do you want me to automatically create and append temporary roles for played games? (No/Yes)')
            self.c.autoCreateTemporaryGameRoles = await self._wait_for_bool(owner)
            self.c.autoAddGames = False
            self.c.autoGiveGameRoles = False
        await self.io_message(owner, 'You can choose between several settings of default user persmissions. You can manually edit them later on.')
        await self.io_message(owner, '0: No one except you can use any command unless you explicit allow it later on.')
        await self.io_message(owner, '1: Users can per default use several harmless features like surveys and reminders. (suggested)')
        await self.io_message(owner, '2: Users can per default use the same as in 1 and have some special commands for temporary channels and such things.')
        await self.io_message(owner, '3: Users can per default administrate the complete server (THIS COULD BE DANGEROUS IF YOU DO NOT TRUST YOUR SERVER MEMBERS!!)')
        self.c.defaultCommandPermissions = await self._wait_for_number(owner, 0, 3)
        await self.io_message(owner, '...')
        await self.io_message(owner, '_**Welcome. You can now start to use me.**_')
        await self.io_message(owner, 'This bot was written by CeroProgramming.')
        e = await self.create_embed("Github CeroProgramming", "https://github.com/CeroProgramming", "GitHub Profile URL", Color.dark_purple(), "CeroProgramming", "https://github.com/CeroProgramming/", "https://avatars3.githubusercontent.com/u/22818389?s=460&v=4", "https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fimage.freepik.com%2Ffree-icon%2Fgithub-logo_318-53553.jpg&f=1")
        await self.io_embed(message.channel, e)
        await self.io_message(owner, 'I\'m licensed under the MIT license.')
        await self.io_message(owner, '```MIT License \n\n Copyright (c) 2017 CeroProgramming\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.```')
        await self.io_message(owner, 'If you want to see the source, visit https://github.com/CeroProgramming/CeroXBot')
        await self.io_message(owner, 'If you find any bugs or if you have feature requests, you can open an issue at https://github.com/CeroProgramming/CeroXBot/issues')
        await self.io_message(owner, 'To see all commands, type %shelp . To see more information about a command, type %shelp \'command\' \nIf you havn\'t already done, you can apply this bot to a server here: https://discordapp.com/oauth2/authorize?client_id=%s&scope=bot&permissions=0' % (self.c.prefix if self.c.prefix else '', self.c.prefix if self.c.prefix else '', self.c.clientID))
        self.c.firstStart = False
Пример #23
0
    async def lyrics(self, ctx, *, title):
        text_channel = ctx.message.channel
        user = ctx.message.author
        ftitle = re.sub(r'\[([^)]+?)]', '',
                        re.sub(r'\(([^)]+?)\)', '', title.lower()))
        params = {'q': ftitle}
        headers = {'Authorization': 'Bearer ' + genius_token}
        async with ClientSession() as client:
            req = await client.get('https://api.genius.com/search',
                                   params=params,
                                   headers=headers)
            req = await req.json()
        r = req['response']['hits']
        if len(r) == 0:
            return await ctx.send('Песни не найдены')
        else:
            new_results = []
            embedValue = ''
            i = 0
            for result in r:
                if result['type'] == 'song' and result['result'][
                        'lyrics_state'] == 'complete':
                    i += 1
                    embedValue += '{}. {} - {}\n'.format(
                        i, result['result']['primary_artist']['name'],
                        result['result']['title'])
                    new_results.append(result)

            embed = Embed(color=Color.dark_purple(),
                          title='Выберите трек',
                          description=embedValue)
            embed.set_footer(
                text=
                'Автоматическая отмена через 30 секунд\nОтправьте 0 для отмены'
            )
            choicemsg = await ctx.send(embed=embed)
            canc = False
            prefixes = await self.bot.get_prefix(ctx.message)

            def verify(m):
                nonlocal canc
                if m.content.isdigit():
                    return 0 <= int(m.content) <= len(
                        new_results
                    ) and m.channel == text_channel and m.author == user
                canc = m.channel == text_channel and m.author == user and any(
                    m.content.startswith(prefix)
                    and len(m.content) > len(prefix) for prefix in prefixes)
                return canc

            msg = await self.bot.wait_for('message', check=verify, timeout=30)
            if canc:
                return await choicemsg.delete()
            if int(msg.content) == 0:
                return await choicemsg.delete()
            result = new_results[int(msg.content) - 1]
            url = result['result']['url']
            title = '{} - {}'.format(
                result['result']['primary_artist']['name'],
                result['result']['title'])
            async with ClientSession() as client:
                lyrics = await client.get(url)
                lyrics = await lyrics.text()
            soup = BeautifulSoup(lyrics, 'html.parser')
            lyrics = soup.p.get_text()
            if len(lyrics) > 2000:
                lyrlist = lyrics.split('\n')
                lyrics = ''
                it = 1
                for i in range(len(lyrlist)):
                    lyrics += lyrlist[i] + '\n'
                    if i < len(lyrlist) - 1 and len(lyrics +
                                                    lyrlist[i + 1]) > 2000:
                        embed = Embed(color=Color.dark_purple(),
                                      title='Текст {} ({})'.format(title, it),
                                      description=lyrics)
                        await ctx.send(embed=embed)
                        lyrics = ''
                        it += 1
                    elif i == len(lyrlist) - 1:
                        embed = Embed(color=Color.dark_purple(),
                                      title='Текст {} ({})'.format(title, it),
                                      description=lyrics)
                        return await ctx.send(embed=embed)
            else:
                embed = Embed(color=Color.dark_purple(),
                              title='Текст ' + title,
                              description=lyrics)
                return await ctx.send(embed=embed)
Пример #24
0
    async def svart_(self, ctx, *, search):
        cards = self.cards
        results = []
        if not isinstance(cards, dict):
            return await ctx.send(
                f'Не удалось получить список карт. Попробуйте использовать {ctx.prefix}svupdate'
            )
        text_channel = ctx.message.channel
        user = ctx.message.author
        terms = search.split(' ')
        for card in cards:
            if all(term.lower() in cards[card]['searchableText'].lower()
                   for term in terms):
                results.append(cards[card])
                if len(results) == 10:
                    break
        if not results:
            return await ctx.send('Карты не найдены')
        else:
            if len(results) == 1:
                result = results[0]
            else:
                content = ''
                for i in range(len(results)):
                    content += '{}. {}\n'.format(i + 1, results[i]['name'])
                embed = Embed(color=Color.dark_purple(),
                              title='Выберите карту',
                              description=content)
                embed.set_footer(
                    text=
                    'Автоматическая отмена через 30 секунд\nОтправьте 0 для отмены'
                )
                choice = await ctx.send(embed=embed)
                canc = False
                prefixes = await self.bot.get_prefix(ctx.message)

                def verify(m):
                    nonlocal canc
                    if m.content.isdigit():
                        return 0 <= int(m.content) <= len(
                            results
                        ) and m.channel == text_channel and m.author == user
                    canc = m.channel == text_channel and m.author == user and any(
                        m.content.startswith(prefix)
                        and len(m.content) > len(prefix)
                        for prefix in prefixes)
                    return canc

                msg = await self.bot.wait_for('message',
                                              check=verify,
                                              timeout=30)
                if canc:
                    return await choice.delete()
                if int(msg.content) == 0:
                    return await choice.delete()
                result = results[int(msg.content) - 1]
            embed = Embed(color=Color.dark_purple(),
                          title=result['name'],
                          url='https://sv.bagoum.com/cards/{}'.format(
                              result['id']))
            embed.set_image(url='https://sv.bagoum.com/getRawImage/0/0/{}'.
                            format(result['id']))
            if result['hasEvo']:
                evoembed = Embed(color=Color.dark_purple(),
                                 title=result['name'] + ' (evolved)',
                                 url='https://sv.bagoum.com/cards/{}'.format(
                                     result['id']))
                evoembed.set_image(
                    url='https://sv.bagoum.com/getRawImage/1/0/{}'.format(
                        result['id']))
                await ctx.send(embed=embed)
                return await ctx.send(embed=evoembed)
            return await ctx.send(embed=embed)
Пример #25
0
 def color(self):
     if self.player.current:
         return get_embed_color(self.player.current.uri)
     return Color.dark_purple()
Пример #26
0
    async def bj_(self, ctx, amt: int):
        if amt <= 0:
            return await ctx.send('Ставка должна быть положительным числом')
        user = ctx.author
        cookies = get_cookies(user.id)
        if cookies is None:
            return await ctx.send('У вас нет печенек')
        if amt > cookies:
            return await ctx.send(
                'У вас недостаточно печенек ({:,}, а необходимо {:,})'.format(
                    cookies, amt))
        deck = gen_deck()
        add(user.id, -1 * amt)
        cookies = get_cookies(user.id)
        fst, snd, trd, frt = draw(deck), draw(deck), draw(deck), draw(deck)
        hand = [fst[1], trd[1]]
        split = [hand]
        dealer = [snd[1], frt[1]]
        embedValue = '''
        Дилер выдает вам {}
        Дилер берет {}
        Дилер выдает вам {}
        Дилер берет в закрытую'''.format(fst[0], snd[0], trd[0])
        embed = Embed(color=Color.dark_purple(),
                      title='Ход игры',
                      description=embedValue)
        msg = await ctx.send(embed=embed)
        if sum(split[0]) == 21:
            add(user.id, amt * 2)
            cookies = get_cookies(user.id)
            embed.description += '\n\nУ вас блэкджек, вы выиграли\nТеперь у вас {:,} {}'.format(
                cookies, sform(cookies, 'печенька'))
            return await msg.edit(embed=embed)
        if sum(dealer) == 21:
            cookies = get_cookies(user.id)
            embed.description += '\n\nУ дилера блэкджек, вы проиграли\nТеперь у вас {:,} {}'.format(
                cookies, sform(cookies, 'печенька'))
            return await msg.edit(embed=embed)

        def verify(m):
            if m.content.lower() in ['hit', 'stand']:
                return m.author == user and m.channel == ctx.message.channel
            if m.content.lower() == 'dd' and cookies >= amt:
                return m.author == user and m.channel == ctx.message.channel
            return False

        def versplit(m):
            if m.content.lower() in ['да', 'нет']:
                return m.author == user and m.channel == ctx.message.channel
            return False

        if split[0][0] == split[0][1] and cookies >= amt:
            embed.description += '\n\nХотите разделить руку? (да/нет)\nАвтоматическая отмена через 300 секунд'
            await msg.edit(embed=embed)
            response = await self.bot.wait_for('message',
                                               check=versplit,
                                               timeout=300)
            if response.content.lower() == 'да':
                split = ([hand[0]], [hand[1]])
                add(user.id, -1 * amt)
                spamt = [amt] * 2
        num = 0
        snum = ''
        for hand in split:
            if len(split) == 2:
                num += 1
                snum = ' ' + str(num)
            while True:
                embed.description += '''
                
                Сумма карт у вас в руке{} - {}
                Хотите взять карту?
                (hit - взять, stand - пас)'''.format(snum, sum(hand))
                cookies = get_cookies(user.id)
                if cookies >= amt:
                    embed.description += '\nВы можете удвоить ставку (dd)'
                embed.description += '\nАвтоматическая отмена через 300 секунд'
                await msg.edit(embed=embed)
                response = await self.bot.wait_for('message',
                                                   check=verify,
                                                   timeout=300)
                if response.content.lower() == 'hit':
                    new = draw(deck)
                    hand.append(new[1])
                    embed.description += '\n\nВы взяли {}'.format(new[0])
                    if sum(hand) == 21:
                        embed.description += '\n\nУ вас 21 очко!'
                        await msg.edit(embed=embed)
                        break
                    if sum(hand) > 21:
                        if 11 in hand:
                            hand[hand.index(11)] = 1
                            await msg.edit(embed=embed)
                        else:
                            cookies = get_cookies(user.id)
                            embed.description += '\n\nУ вас больше 21 очка, вы проиграли\nТеперь у вас {:,} {}'.format(
                                cookies, sform(cookies, 'печенька'))
                            await msg.edit(embed=embed)
                            break
                if response.content.lower() == 'dd':
                    add(user.id, -1 * amt)
                    if len(split) == 2:
                        # noinspection PyUnboundLocalVariable
                        spamt[num - 1] *= 2
                    else:
                        amt *= 2
                    embed.description += '\n\nВы удвоили ставку'
                    new = draw(deck)
                    hand.append(new[1])
                    embed.description += '\nВы взяли {}'.format(new[0])
                    if sum(hand) == 21:
                        embed.description += '\n\nУ вас 21 очко!'
                        await msg.edit(embed=embed)
                        break
                    if sum(hand) > 21:
                        if 11 in hand:
                            hand[hand.index(11)] = 1
                            await msg.edit(embed=embed)
                        else:
                            cookies = get_cookies(user.id)
                            embed.description += '\n\nУ вас больше 21 очка, вы проиграли\nТеперь у вас {:,} {}'.format(
                                cookies, sform(cookies, 'печенька'))
                            await msg.edit(embed=embed)
                            break
                    embed.description += '\nСумма карт у вас в руке{} - {}'.format(
                        snum, sum(hand))
                    break
                if response.content.lower() == 'stand':
                    embed.description += '\n\nВы оставили текущую руку\nСумма карт у вас в руке{} - {}'.format(
                        snum, sum(hand))
                    break
        if len(split) == 1 and sum(split[0]) > 21:
            return
        embed.description += '\n\nДилер открывает вторую карту - {}\n'.format(
            frt[0])
        await msg.edit(embed=embed)
        while sum(dealer) < 17:
            embed.description += '\nСумма карт в руке у дилера - {}'.format(
                sum(dealer))
            new = draw(deck)
            embed.description += '\nДилер берет {}'.format(new[0])
            dealer.append(new[1])
            if sum(dealer) > 21:
                if 11 in dealer:
                    dealer[dealer.index(11)] = 1
                    await msg.edit(embed=embed)
                else:
                    if len(split) == 2:
                        for i in range(len(split)):
                            if sum(split[i]) <= 21:
                                add(user.id, spamt[i] * 2)
                    else:
                        add(user.id, amt * 2)
                    cookies = get_cookies(user.id)
                    embed.description += '\nУ дилера больше 21 очка, вы победили\nТеперь у вас {:,} {}'.format(
                        cookies, sform(cookies, 'печенька'))
                    return await msg.edit(embed=embed)
        embed.description += '\nСумма карт в руке в дилера - {}'.format(
            sum(dealer))
        num = 0
        for hand in split:
            if len(split) == 2:
                num += 1
            if sum(hand) <= 21:
                if len(split) == 2:
                    embed.description += '\n\nРука {}'.format(num)
                    amt = spamt[num - 1]
                if sum(dealer) == sum(hand):
                    add(user.id, amt)
                    cookies = get_cookies(user.id)
                    embed.description += '\nУ вас одинаковый счет, вам возвращена ставка\nТеперь у вас {:,} {}'.format(
                        cookies, sform(cookies, 'печенька'))
                    await msg.edit(embed=embed)
                if sum(dealer) > sum(hand):
                    cookies = get_cookies(user.id)
                    embed.description += '\nУ вас меньше очков, чем у дилера\nВы проиграли\nТеперь у вас {:,} {}'.format(
                        cookies, sform(cookies, 'печенька'))
                    await msg.edit(embed=embed)
                if sum(hand) > sum(dealer):
                    cookies = get_cookies(user.id)
                    add(user.id, amt * 2)
                    cookies = get_cookies(user.id)
                    embed.description += '\nУ вас больше очков, чем у дилера\nВы победили\nТеперь у вас {:,} {}'.format(
                        cookies, sform(cookies, 'печенька'))
                    await msg.edit(embed=embed)
Пример #27
0
import asyncio
import datetime
import typing
import pytz

import discord
from discord import Color

from cogs.misc import LikeUser, FakeMember

colours = {
    'unban': Color.green(),
    'unmute': Color.dark_green(),
    'note': Color.light_grey(),
    'warn': Color.orange(),
    'mute': Color.dark_purple(),
    'kick': Color.dark_orange(),
    'softban': Color.red(),
    'ban': Color.dark_red()
}


async def ban(victim: discord.Member, reason: str = None):
    await victim.guild.ban(victim, reason=reason)


async def softban(victim: discord.Member, reason: str = None):
    await victim.guild.ban(victim, reason=reason)
    await victim.guild.unban(victim, reason=reason)

Пример #28
0
    async def wikia_(self, ctx, *, query=None):
        try:
            text_channel = ctx.message.channel
            if query is None:
                return await ctx.send(
                    f'Использование: {ctx.prefix}[wikia|wiki] <запрос>')
            apiurl = 'https://community.fandom.com/api/v1/Search/CrossWiki'
            user = ctx.message.author
            params = {
                'expand': 1,
                'query': query,
                'lang': 'ru,en',
                'limit': 10,
                'batch': 1,
                'rank': 'default'
            }
            async with ClientSession() as client:
                result = await client.get(apiurl, params=params, timeout=0.5)
                result = await result.json()
            if 'exception' in result.keys():
                return await ctx.send('Ничего не найдено')
            results = result['items']
            new_results = []
            embedValue = ''
            i = 0
            for result in results:
                if result:
                    if result['title']:
                        i += 1
                        embedValue += '{}. {}\n'.format(i, result['title'])
                        new_results.append(result)
            embed = Embed(color=Color.dark_purple(),
                          title='Выберите фэндом',
                          description=embedValue)
            embed.set_footer(
                text=
                'Автоматическая отмена через 30 секунд\nОтправьте 0 для отмены'
            )
            choicemsg = await ctx.send(embed=embed)
            canc = False
            prefixes = await self.bot.get_prefix(ctx.message)

            def verify(m):
                nonlocal canc
                if m.content.isdigit():
                    return 0 <= int(m.content) <= len(
                        new_results
                    ) and m.channel == text_channel and m.author == user
                canc = m.channel == text_channel and m.author == user and any(
                    m.content.startswith(prefix)
                    and len(m.content) > len(prefix) for prefix in prefixes)
                return canc

            msg = await self.bot.wait_for('message', check=verify, timeout=30)
            if canc:
                return await choicemsg.delete()
            if int(msg.content) == 0:
                return await choicemsg.delete()
            result = new_results[int(msg.content) - 1]
            await choicemsg.delete()
            if result['url'].endswith('/'):
                apiurl = '{}api/v1/'.format(result['url'])
            else:
                apiurl = '{}/api/v1/'.format(result['url'])
            params = {
                'query': query,
                'namespaces': '0,14',
                'limit': 1,
                'minArticleQuality': 0,
                'batch': 1
            }
            try:
                async with ClientSession() as client:
                    result = await client.get(apiurl + 'Search/List',
                                              params=params,
                                              timeout=0.5)
                    result = await result.json()
            except Exception as e:
                await ctx.send('Ничего не найдено')
                return print(e)
            if 'exception' in result.keys():
                return await ctx.send('Ничего не найдено')
            page_id = result['items'][0]['id']
            params = {
                'ids': page_id,
                'abstract': 500,
                'width': 200,
                'height': 200
            }
            async with ClientSession() as client:
                result = await client.get(apiurl + 'Articles/Details',
                                          params=params,
                                          timeout=0.5)
                result = await result.json()
            basepath = result['basepath']
            result = result['items'][str(page_id)]
            page_url = basepath + result['url']
            title = result['title']
            desc = unescape(result['abstract'])
            dims = result['original_dimensions']
            thumb = result['thumbnail']
            if dims is not None:
                width = dims['width']
                height = dims['height']
                if width <= 200:
                    params = {
                        'ids': page_id,
                        'abstract': 0,
                        'width': int(width),
                        'height': int(height)
                    }
                else:
                    ratio = height / width
                    width = 200
                    height = ratio * width
                    params = {
                        'ids': page_id,
                        'abstract': 0,
                        'width': int(width),
                        'height': int(height)
                    }
                async with ClientSession() as client:
                    result = await client.get(apiurl + 'Articles/Details',
                                              params=params,
                                              timeout=0.5)
                    result = await result.json()
                thumb = result['items'][str(page_id)]['thumbnail']
            embed = Embed(color=Color.dark_purple(),
                          title=title,
                          url=page_url,
                          description=desc)
            if thumb is not None:
                embed.set_thumbnail(url=thumb)
            return await ctx.send(user.mention, embed=embed)
        except ServerTimeoutError:
            await ctx.send('Не удалось подключиться к Wikia')