Python secrets 模块,choice() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用secrets.choice()

项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def table_unflipper(ev, message):
    if '(?°?°??? ???'.replace(' ', '') in message.content.replace(' ', ''):
        if message.guild:
            flip_settings = await ev.db.get_guild_settings(message.guild.id, 'Unflip')
            if flip_settings is None:
                unflip = False
            else:
                unflip = flip_settings
        else:
            unflip = True
        if unflip:
            await add_special_stats(ev.db, 'tables_fixed')
            table = ['??? ?( ^_^?)',
                     '??? ?(° -°?)',
                     '??? ?(?-??)',
                     '??? ?(?\_??)',
                     '???~~~~  ?(°?° ?)',
                     '???====  ?(°?° ?)',
                     ' ????? ¯\_(?)',
                     '(??_?)????',
                     '?(´° ?°)????']
            table_resp = secrets.choice(table)
            await message.channel.send(table_resp)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def catfact(cmd, message, args):
    global facts
    if not facts:
        resource = 'http://www.animalplanet.com/xhr.php'
        resource += '?action=get_facts&limit=500&page_id=37397'
        resource += '&module_id=cfct-module-bdff02c2a38ff3c34ce90ffffce76104&used_slots=W10='
        async with aiohttp.ClientSession() as session:
            async with session.get(resource) as data:
                data = await data.read()
                data = json.loads(data)
                facts = data
    fact = secrets.choice(facts)
    fact_text = fact['description'].strip()
    embed = discord.Embed(color=0xFFDC5D)
    embed.add_field(name='?? Did you know...', value=fact_text)
    await message.channel.send(None, embed=embed)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def dab(cmd, message, args):
    faces = [
        ' ( ?-? )', '( ?_? )', '????', '( ?-? )', '????)',
        '(???’)', '???', '?????', '???', '?(O_O?)', '?_?',
        '?_?', '?_?', '?_?', '???', '???', '?', '??', '?_??',
        '??_??', '(¬_¬)', '(??´)', '(???)', '(?_?)', '(¬?¬)',
        '(???)', '(?_?)', '(¬?¬)', '(\`A´)', '?????', '-\`?´-',
        '(’?’)', '(???)', '??_??', '(?', '??)', '(????)',
        '?(\`o´)', '(?_??)', '(????)', '??????', '(??´)',
        '(#??´)', '(¬_¬)?', '(????)', '(?', '??)', '(', '>?<)',
        '?(¬?¬)', '(????)', '????)?', '(?¬?¬)', '(-_-?)',
        '(º?º)', '????)?', '(???)', '(°?°?)', '???´??',
        '(???)?', '?#????', '??????', '(????)', '(#\`?´)'
    ]
    face = secrets.choice(faces)
    signs = ['.', '...', '!', '!!!']
    sign = secrets.choice(signs)
    output = f'`{face}` No{sign}'
    await message.channel.send(output)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def e621(cmd, message, args):
    url_base = 'https://e621.net/post/index.json'
    if args:
        url = url_base + '?tags=' + '+'.join(args)
    else:
        url = url_base + '?tags=nude'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0'}
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers) as data:
            data = await data.read()
            data = json.loads(data)
    if data:
        post = secrets.choice(data)
        image_url = post['file_url']
        icon_url = 'https://e621.net/favicon.ico'
        post_url = f'https://e621.net/post/show/{post["id"]}'
        embed = discord.Embed(color=0x152F56)
        embed.set_author(name='e621', url=post_url, icon_url=icon_url)
        embed.set_image(url=image_url)
        embed.set_footer(text=f'Score: {post["score"]} | Size: {post["width"]}x{post["height"]}')
    else:
        embed = discord.Embed(color=0x696969, title='?? Nothing found.')
    await message.channel.send(None, embed=embed)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def yandere(cmd, message, args):
    url_base = 'https://yande.re/post.json?limit=100&tags='
    if not args:
        tags = 'nude'
    else:
        tags = '+'.join(args)
    url = url_base + tags
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as data:
            data = await data.read()
            data = json.loads(data)
    if len(data) == 0:
        embed = discord.Embed(color=0x696969, title='?? No results.')
    else:
        post = secrets.choice(data)
        image_url = post['file_url']
        icon_url = 'https://i.imgur.com/vgJwau2.png'
        post_url = f'https://yande.re/post/show/{post["id"]}'
        embed = discord.Embed(color=0xad3d3d)
        embed.set_author(name='Yande.re', url=post_url, icon_url=icon_url)
        embed.set_image(url=image_url)
        embed.set_footer(
            text=f'Score: {post["score"]} | Size: {post["width"]}x{post["height"]} | Uploaded By: {post["author"]}')
    await message.channel.send(None, embed=embed)
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def smitten(cmd, message, args):
    dan_id = 285232223127601152
    dawn_id = 222234484064518156
    if message.author.id == dan_id:
        target_id = dawn_id
    elif message.author.id == dawn_id:
        target_id = dan_id
    else:
        return
    target = discord.utils.find(lambda x: x.id == target_id, cmd.bot.get_all_members())
    if target:
        url_list = [
            'https://i.imgur.com/HQHsDOY.gif',
            'https://i.imgur.com/Kj9x7Az.gif'
        ]
        img_url = secrets.choice(url_list)
        response = discord.Embed(color=0xff6699, title='?? Dan x Dawn')
        response.set_image(url=img_url)
        await target.send(embed=response)
项目:Chiaki-Nanami    作者:Ikusaba-san    | 项目源码 | 文件源码
def ball(self, ctx, *, question: str):
        """...it's a 8-ball"""
        if not question.endswith('?'):
            return await ctx.send(f"{ctx.author.mention}, that's not a question, I think.")

        colour = discord.Colour(random.randint(0, 0xFFFFFF))

        eight_ball_field_name = '\N{BILLIARDS} 8-ball'
        embed = (discord.Embed(colour=colour)
                 .add_field(name='\N{BLACK QUESTION MARK ORNAMENT} Question', value=question)
                 .add_field(name=eight_ball_field_name, value='\u200b', inline=False)
                 )

        msg = await ctx.send(content=ctx.author.mention, embed=embed)

        new_colour = discord.Colour.from_rgb(*(round(c * 0.7) for c in colour.to_rgb()))
        default = _8default._replace(colour=new_colour)

        async with ctx.typing():
            for answer in (default, random.choice(BALL_ANSWERS)):
                await asyncio.sleep(random.uniform(0.75, 1.25) * 2)
                embed.colour = answer.colour
                embed.set_field_at(-1, name=eight_ball_field_name, value=answer.answer, inline=False)
                await msg.edit(embed=embed)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def catfact(cmd, message, args):
    global facts
    if not facts:
        resource = 'http://www.animalplanet.com/xhr.php'
        resource += '?action=get_facts&limit=500&page_id=37397'
        resource += '&module_id=cfct-module-bdff02c2a38ff3c34ce90ffffce76104&used_slots=W10='
        async with aiohttp.ClientSession() as session:
            async with session.get(resource) as data:
                data = await data.read()
                data = json.loads(data)
                facts = data
    fact = secrets.choice(facts)
    fact_text = fact['description'].strip()
    embed = discord.Embed(color=0xFFDC5D)
    embed.add_field(name='?? Did you know...', value=fact_text)
    await message.channel.send(None, embed=embed)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def dab(cmd, message, args):
    faces = [
        ' ( ?-? )', '( ?_? )', '????', '( ?-? )', '????)',
        '(???’)', '???', '?????', '???', '?(O_O?)', '?_?',
        '?_?', '?_?', '?_?', '???', '???', '?', '??', '?_??',
        '??_??', '(¬_¬)', '(??´)', '(???)', '(?_?)', '(¬?¬)',
        '(???)', '(?_?)', '(¬?¬)', '(`A´)', '?????', '-`?´-',
        '(’?’)', '(???)', '??_??', '(?', '??)', '(????)',
        '?(`o´)', '(?_??)', '(????)', '??????', '(??´)',
        '(#??´)', '(¬_¬)?', '(????)', '(?', '??)', '(', '>?<)',
        '?(¬?¬)', '(????)', '????)?', '(?¬?¬)', '(-_-?)',
        '(º?º)', '????)?', '(???)', '(°?°?)', '???´??',
        '(???)?', '?#????', '??????', '(????)', '(#`?´)'
    ]
    face = secrets.choice(faces)
    signs = ['.', '...', '!', '!!!']
    sign = secrets.choice(signs)
    output = f'`{face}` No{sign}'
    await message.channel.send(output)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def e621(cmd, message, args):
    url_base = 'https://e621.net/post/index.json'
    if args:
        url = url_base + '?tags=' + '+'.join(args)
    else:
        url = url_base + '?tags=nude'
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as data:
            data = await data.read()
            data = json.loads(data)
    if data:
        post = secrets.choice(data)
        image_url = post['file_url']
        icon_url = 'https://e621.net/favicon.ico'
        post_url = f'https://e621.net/post/show/{post["id"]}'
        embed = discord.Embed(color=0x152F56)
        embed.set_author(name='e621', url=post_url, icon_url=icon_url)
        embed.set_image(url=image_url)
        embed.set_footer(text=f'Score: {post["score"]} | Size: {post["width"]}x{post["height"]}')
    else:
        embed = discord.Embed(color=0x696969, title='?? Nothing found.')
    await message.channel.send(None, embed=embed)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def konachan(cmd, message, args):
    url_base = 'https://konachan.com/post.json?limit=100&tags='
    if not args:
        tags = 'nude'
    else:
        tags = '+'.join(args)
    url = url_base + tags
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as data:
            data = await data.read()
            data = json.loads(data)
    if len(data) == 0:
        embed = discord.Embed(color=0x696969, title='?? No results.')
    else:
        post = secrets.choice(data)
        image_url = f'https:{post["file_url"]}'
        post_url = f'http://konachan.com/post/show/{post["id"]}'
        icon_url = 'https://i.imgur.com/qc4awFL.png'
        embed = discord.Embed(color=0x473a47)
        embed.set_author(name='Konachan', url=post_url, icon_url=icon_url)
        embed.set_image(url=image_url)
        embed.set_footer(
            text=f'Score: {post["score"]} | Size: {post["width"]}x{post["height"]} | Uploaded By: {post["author"]}')
    await message.channel.send(None, embed=embed)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def add_participant(channel_id, user):
    race = races[channel_id]
    icons = race['icons']
    users = race['users']
    usr_icon = secrets.choice(icons)
    icons.remove(usr_icon)
    race.update({'icons': icons})
    participant_data = {
        'user': user,
        'icon': usr_icon
    }
    users.append(participant_data)
    race.update({'users': users})
    races.update({channel_id: race})
    return usr_icon
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def recipes(cmd, message, args):
    global recipe_core
    if not recipe_core:
        recipe_core = RecipeCore(cmd.resource('data'))
    if args:
        try:
            page = int(args[0]) - 1
            if page < 0:
                page = 0
        except ValueError:
            page = 0
    else:
        page = 0
    list_start = page * 10
    list_end = (page + 1) * 10
    recipe_list = sorted(recipe_core.recipes, key=lambda x: x.name)[list_start:list_end]
    recipe_look = secrets.choice(recipe_core.recipes)
    recipe_icon = recipe_look.icon
    recipe_color = recipe_look.color
    recipe_boop_head = ['Name', 'Type', 'Value', 'Ingr.']
    recipe_boop_list = []
    stats_text = f'Showing recipes: {list_start}-{list_end}.'
    stats_text += f'\nThere is a total of {len(recipe_core.recipes)} recipes.'
    if recipe_list:
        for recipe in recipe_list:
            req_satisfied = await check_requirements(cmd, message, recipe)
            recipe_boop_list.append([recipe.name, recipe.type, recipe.value, req_satisfied])
        recipe_table = boop(recipe_boop_list, recipe_boop_head)
        response = discord.Embed(color=recipe_color)
        response.add_field(name=f'{recipe_icon} Recipe Stats', value=f'```py\n{stats_text}\n```', inline=False)
        response.add_field(name=f'?? Recipes On Page {page + 1}', value=f'```hs\n{recipe_table}\n```')
    else:
        response = discord.Embed(color=0x696969, title=f'?? This page is empty.')
    await message.channel.send(embed=response)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def pick_item_in_rarity(self, item_category, rarity):
        in_rarity = []
        for item in self.all_items:
            if item.type.lower() == item_category:
                if item.rarity == rarity:
                    in_rarity.append(item)
        choice = secrets.choice(in_rarity)
        return choice
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def dadjoke(cmd, message, args):
    with open(cmd.resource('dadjokes.json'), 'r', encoding='utf-8') as dadjokes_file:
        jokes = dadjokes_file.read()
        jokes = json.loads(jokes)
    joke_list = jokes['JOKES']
    end_joke_choice = secrets.choice(joke_list)
    end_joke = end_joke_choice['setup']
    punchline = end_joke_choice['punchline']
    embed = discord.Embed(color=0xFFDC5D)
    embed.add_field(name='?? Have An Awful Dad Joke', value=f'{end_joke}\n...\n{punchline}')
    await message.channel.send(None, embed=embed)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def cat(cmd, message, args):
    if 'api_key' in cmd.cfg:
        cat_api_key = cmd.cfg['api_key']
        api_url = f'http://thecatapi.com/api/images/get?format=xml&results_per_page=100&api_key={cat_api_key}'
    else:
        api_url = f'http://thecatapi.com/api/images/get?format=xml&results_per_page=100'
    async with aiohttp.ClientSession() as session:
        async with session.get(api_url) as raw_page:
            results = html.fromstring(await raw_page.text())[0][0]
    choice = secrets.choice(results)
    image_url = str(choice[0].text)
    embed = discord.Embed(color=0xFFDC5D, title='?? Meow~')
    embed.set_image(url=image_url)
    await message.channel.send(None, embed=embed)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def deezer(cmd, message, args):
    if args:
        search = '%20'.join(args)
        qry_url = f'http://api.deezer.com/search/track?q={search}'
        async with aiohttp.ClientSession() as session:
            async with session.get(qry_url) as data:
                data = await data.read()
                data = json.loads(data)
                data = data['data']
        if data:
            data = data[0]
            track_url = data['link']
            track_title = data['title_short']
            track_duration = data['duration']
            preview_url = data['preview']
            artist_name = data['artist']['name']
            artist_image = data['artist']['picture_medium']
            album_title = data['album']['title']
            album_image = data['album']['cover_medium']
            deezer_icon = 'http://e-cdn-files.deezer.com/images/common/favicon/favicon-96x96-v00400045.png'
            deezer_colors = [0xff0000, 0xffed00, 0xff0092, 0xbed62f, 0x00c7f2]
            deezer_color = secrets.choice(deezer_colors)
            song_desc = f'Preview: [Here]({preview_url})'
            song_desc += f'\nDuration: {datetime.timedelta(seconds=track_duration)}'
            response = discord.Embed(color=deezer_color)
            response.set_author(name=artist_name, icon_url=artist_image, url=track_url)
            response.add_field(name=f'{track_title}', value=song_desc)
            response.set_thumbnail(url=album_image)
            response.set_footer(icon_url=deezer_icon, text=f'Album: {album_title}')
        else:
            response = discord.Embed(color=0x696969, title='?? No results.')
    else:
        response = discord.Embed(color=0xBE1931, title='? Nothing inputted.')
    await message.channel.send(embed=response)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def generate_embed(post, titles, color=0xff6699, icon='https://i.imgur.com/WQbzk9y.png'):
    image_url = post.attrib['file_url']
    image_source = f'http://safebooru.org/index.php?page=post&s=view&id={post.attrib["id"]}'
    if image_url.startswith('//'):
        image_url = 'https:' + image_url
    embed = discord.Embed(color=color)
    embed.set_author(name=secrets.choice(titles), icon_url=icon, url=image_source)
    embed.set_image(url=image_url)
    embed.set_footer(
        text=f'Score: {post.attrib["score"]} | Size: {post.attrib["width"]}x{post.attrib["height"]}')
    return embed
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def grab_post(subreddit, argument):
    if argument == 'tophot':
        post = list(subreddit.hot(limit=1))[0]
    elif argument == 'topnew':
        post = list(subreddit.new(limit=1))[0]
    elif argument == 'randomnew':
        post = secrets.choice(list(subreddit.new(limit=100)))
    elif argument == 'toptop':
        post = list(subreddit.top(limit=1))[0]
    elif argument == 'randomtop':
        post = secrets.choice(list(subreddit.top(limit=100)))
    else:
        post = secrets.choice(list(subreddit.hot(limit=100)))
    return post
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def dance(cmd, message, args):
    interaction = await grab_interaction(cmd.db, 'dance')
    target = get_target(message)
    auth = message.author
    icons = ['??', '??']
    icon = secrets.choice(icons)
    if not target or target.id == message.author.id:
        response = discord.Embed(color=0xdd2e44, title=f'{icon} {auth.display_name} dances.')
    else:
        response = discord.Embed(color=0xdd2e44, title=f'{icon} {auth.display_name} dances with {target.display_name}.')
    response.set_image(url=interaction['URL'])
    response.set_footer(text=make_footer(cmd, interaction))
    await message.channel.send(embed=response)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def combinechains(cmd, message, args):
    if not await cmd.bot.cool_down.on_cooldown(cmd.name, message.author):
        if len(message.mentions) == 2:
            target_one = message.mentions[0]
            target_two = message.mentions[1]
            chain_one = await cmd.db[cmd.db.db_cfg.database]['MarkovChains'].find_one({'UserID': target_one.id})
            chain_two = await cmd.db[cmd.db.db_cfg.database]['MarkovChains'].find_one({'UserID': target_two.id})
            if chain_one and chain_two:
                await cmd.bot.cool_down.set_cooldown(cmd.name, message.author, 20)
                init_embed = discord.Embed(color=0xbdddf4, title='?? Hmm... Let me think...')
                init_message = await message.channel.send(embed=init_embed)
                string_one = ' '.join(chain_one.get('Chain'))
                string_two = ' '.join(chain_two.get('Chain'))
                with ThreadPoolExecutor() as threads:
                    chain_task_one = functools.partial(markovify.Text, string_one)
                    chain_task_two = functools.partial(markovify.Text, string_two)
                    markov_one = await cmd.bot.loop.run_in_executor(threads, chain_task_one)
                    markov_two = await cmd.bot.loop.run_in_executor(threads, chain_task_two)
                    combine_task = functools.partial(markovify.combine, [markov_one, markov_two], [1, 1])
                    combination = await cmd.bot.loop.run_in_executor(threads, combine_task)
                    sentence_function = functools.partial(combination.make_short_sentence, 500)
                    sentence = await cmd.bot.loop.run_in_executor(threads, sentence_function)
                if not sentence:
                    response = discord.Embed(color=0xBE1931, title='?? I could not think of anything...')
                else:
                    icon_choice = secrets.choice([target_one, target_two])
                    combined_name = combine_names(target_one, target_two)
                    response = discord.Embed(color=0xbdddf4)
                    response.set_author(name=combined_name, icon_url=user_avatar(icon_choice))
                    response.add_field(name='?? Hmm... something like...', value=sentence)
                await init_message.edit(embed=response)
            else:
                no_chain = discord.Embed(color=0xBE1931, title='? One of the users does not have a chain.')
                await message.channel.send(embed=no_chain)
        else:
            no_target = discord.Embed(color=0xBE1931, title='? Invalid number of targets.')
            await message.channel.send(embed=no_target)
    else:
        timeout = await cmd.bot.cool_down.get_cooldown(cmd.name, message.author)
        on_cooldown = discord.Embed(color=0xccffff, title=f'? On cooldown for another {timeout} seconds.')
        await message.channel.send(embed=on_cooldown)
项目:exercism-python    作者:unfo    | 项目源码 | 文件源码
def random_key(self):
        return "".join(secrets.choice(LC) for _ in range(128))
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def forage(cmd, message, args):
    all_plants = get_all_items('plants', cmd.resource('data'))
    if not cmd.cooldown.on_cooldown(cmd, message):
        cmd.cooldown.set_cooldown(cmd, message, 60)
        kud = cmd.db.get_points(message.author)
        if kud['Current'] >= 20:
            cmd.db.take_points(message.guild, message.author, 20)
            rarity = roll_rarity()
            if args:
                if message.author.id in permitted_id:
                    try:
                        rarity = int(args[0])
                    except TypeError:
                        pass
            all_items_in_rarity = get_items_in_rarity(all_plants, rarity)
            item = secrets.choice(all_items_in_rarity)
            value = item.value
            connector = 'a'
            if item.rarity_name[0].lower() in ['a', 'e', 'i', 'o', 'u']:
                connector = 'an'
            if value == 0:
                response_title = f'{item.icon} You found {connector} {item.name} and threw it away!'
            else:
                response_title = f'{item.icon} You found {connector} {item.rarity_name} {item.name}!'
                item_id = make_item_id()
                data_for_inv = {
                    'item_id': item_id,
                    'item_file_id': item.item_file_id,
                }
                cmd.db.inv_add(message.author, data_for_inv)
            response = discord.Embed(color=item.color, title=response_title)
            response.set_author(name=message.author.display_name, icon_url=user_avatar(message.author))
            if item.rarity >= 5:
                await notify_channel_of_special(message, cmd.bot.get_all_channels(), ItemWinChannelID, item)
        else:
            response = discord.Embed(color=0xDB0000, title=f'â?— You don\'t have enough {Currency}!')
    else:
        timeout = cmd.cooldown.get_cooldown(cmd, message)
        response = discord.Embed(color=0x696969, title=f'🕙 Your new bait will be ready in {timeout} seconds.')
    await message.channel.send(embed=response)
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def fish(cmd, message, args):
    all_fish = get_all_items('fish', cmd.resource('data'))
    if not cmd.cooldown.on_cooldown(cmd, message):
        cmd.cooldown.set_cooldown(cmd, message, 60)
        kud = cmd.db.get_points(message.author)
        if kud['Current'] >= 20:
            cmd.db.take_points(message.guild, message.author, 20)
            rarity = roll_rarity()
            if args:
                if message.author.id in permitted_id:
                    try:
                        rarity = int(args[0])
                    except TypeError:
                        pass
            all_items_in_rarity = get_items_in_rarity(all_fish, rarity)
            item = secrets.choice(all_items_in_rarity)
            value = item.value
            connector = 'a'
            if item.rarity_name[0].lower() in ['a', 'e', 'i', 'o', 'u']:
                connector = 'an'
            if value == 0:
                response_title = f'{item.icon} You caught {connector} {item.name} and threw it away!'
            else:
                response_title = f'{item.icon} You caught {connector} {item.rarity_name} {item.name}!'
                item_id = make_item_id()
                data_for_inv = {
                    'item_id': item_id,
                    'item_file_id': item.item_file_id,
                }
                cmd.db.inv_add(message.author, data_for_inv)
            response = discord.Embed(color=item.color, title=response_title)
            response.set_author(name=message.author.display_name, icon_url=user_avatar(message.author))
            if item.rarity >= 5:
                await notify_channel_of_special(message, cmd.bot.get_all_channels(), ItemWinChannelID, item)
        else:
            response = discord.Embed(color=0xDB0000, title=f'? You don\'t have enough {Currency}!')
    else:
        timeout = cmd.cooldown.get_cooldown(cmd, message)
        response = discord.Embed(color=0x696969, title=f'?? Your new bait will be ready in {timeout} seconds.')
    await message.channel.send(embed=response)
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def catfact(cmd, message, args):
        resource = 'http://www.catfact.info/api/v1/facts.json?page=0&per_page=700'
        async with aiohttp.ClientSession() as session:
            async with session.get(resource) as data:
                data = await data.read()
                data = json.loads(data)
        fact = secrets.choice(data['facts'])
        embed = discord.Embed(color=0x1abc9c)
        embed.add_field(name=':cat: Did you know...', value='```\n' + fact['details'] + '\n```')
        await message.channel.send(None, embed=embed)
项目:Chiaki-Nanami    作者:Ikusaba-san    | 项目源码 | 文件源码
def _password(length, alphabet=_default_letters):
    return ''.join(secrets.choice(alphabet) for i in range(length))
项目:Chiaki-Nanami    作者:Ikusaba-san    | 项目源码 | 文件源码
def choose(self, ctx, *choices: commands.clean_content):
        """Chooses between a list of choices.

        If one of your choices requires a space, it must be wrapped in quotes.
        """
        if len(set(choices)) < 2:
            return await ctx.send('I need more choices than that...')

        with ctx.channel.typing():
            msg = await ctx.send('\N{THINKING FACE}')
            await asyncio.sleep(random.uniform(0.25, 1))
            await msg.edit(content=random.choice(choices))
项目:Chiaki-Nanami    作者:Ikusaba-san    | 项目源码 | 文件源码
def _class(self):
        return random.choice(_diepio_tanks)
项目:bnc-bot    作者:snoonetIRC    | 项目源码 | 文件源码
def gen_pass(chars: str = (string.ascii_letters + string.digits), length: int = 16) -> str:
    """
    Generate a password
    :param chars: The characters to use for password generation
    :return: The generated password
    """
    return ''.join(secrets.choice(chars) for _ in range(length))
项目:bnc-bot    作者:snoonetIRC    | 项目源码 | 文件源码
def gen_bindhost():
    return random.choice(BIND_HOST_NET)
项目:Django-Code-Review-CodeEntrepreneurs    作者:guinslym    | 项目源码 | 文件源码
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
    return ''.join(choice(chars) for _ in range(size))
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def add_participant(channel_id, user):
    race = races[channel_id]
    icons = race['icons']
    users = race['users']
    usr_icon = secrets.choice(icons)
    icons.remove(usr_icon)
    race.update({'icons': icons})
    participant_data = {
        'user': user,
        'icon': usr_icon
    }
    users.append(participant_data)
    race.update({'users': users})
    races.update({channel_id: race})
    return usr_icon
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def recipes(cmd, message, args):
    global recipe_core
    if not recipe_core:
        recipe_core = RecipeCore(cmd.resource('data'))
    if args:
        try:
            page = int(args[0]) - 1
            if page < 0:
                page = 0
        except ValueError:
            page = 0
    else:
        page = 0
    list_start = page * 10
    list_end = (page + 1) * 10
    recipe_list = sorted(recipe_core.recipes, key=lambda x: x.name)[list_start:list_end]
    recipe_look = secrets.choice(recipe_core.recipes)
    recipe_icon = recipe_look.icon
    recipe_color = recipe_look.color
    recipe_boop_head = ['Name', 'Type', 'Value', 'Ingr.']
    recipe_boop_list = []
    stats_text = f'Showing recipes: {list_start}-{list_end}.'
    stats_text += f'\nThere is a total of {len(recipe_core.recipes)} recipes.'
    if recipe_list:
        for recipe in recipe_list:
            req_satisfied = check_requirements(cmd, message, recipe)
            recipe_boop_list.append([recipe.name, recipe.type, recipe.value, req_satisfied])
        recipe_table = boop(recipe_boop_list, recipe_boop_head)
        response = discord.Embed(color=recipe_color)
        response.add_field(name=f'{recipe_icon} Recipe Stats', value=f'```py\n{stats_text}\n```', inline=False)
        response.add_field(name=f'?? Recipes On Page {page + 1}', value=f'```hs\n{recipe_table}\n```')
    else:
        response = discord.Embed(color=0x696969, title=f'?? This page is empty.')
    await message.channel.send(embed=response)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def pick_item_in_rarity(self, item_category, rarity):
        in_rarity = []
        for item in self.all_items:
            if item.type.lower() == item_category:
                if item.rarity == rarity:
                    in_rarity.append(item)
        choice = secrets.choice(in_rarity)
        return choice
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def nablie_plant(ev, message):
    if message.author.id in responses:
        roll = secrets.randbelow(5)
        if roll == 0:
            try:
                symbol = secrets.choice(responses.get(message.author.id))
                await message.add_reaction(symbol)
            except discord.Forbidden:
                pass
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def fortune(cmd, message, args):
    if not fortune_files:
        for fortune_file in os.listdir(cmd.resource('fortune')):
            with open(cmd.resource(f'fortune/{fortune_file}')) as forfile:
                text_data = forfile.read()
                fortune_files.append(text_data.split('%'))
    category = secrets.choice(fortune_files)
    fort = None
    while fort is None or len(fort) > 800:
        fort = secrets.choice(category)
    response = discord.Embed(color=0x8CCAF7)
    response.add_field(name='?? Fortune', value=fort)
    await message.channel.send(embed=response)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def dadjoke(cmd, message, args):
    with open(cmd.resource('dadjokes.json'), 'r', encoding='utf-8') as dadjokes_file:
        jokes = dadjokes_file.read()
        jokes = json.loads(jokes)
    joke_list = jokes['JOKES']
    end_joke_choice = secrets.choice(joke_list)
    end_joke = end_joke_choice['setup']
    punchline = end_joke_choice['punchline']
    embed = discord.Embed(color=0xFFDC5D)
    embed.add_field(name='?? Have An Awful Dad Joke', value=f'{end_joke}\n...\n{punchline}')
    await message.channel.send(None, embed=embed)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def cat(cmd, message, args):
    if 'api_key' in cmd.cfg:
        cat_api_key = cmd.cfg['api_key']
        api_url = f'http://thecatapi.com/api/images/get?format=xml&results_per_page=100&api_key={cat_api_key}'
    else:
        api_url = f'http://thecatapi.com/api/images/get?format=xml&results_per_page=100'
    async with aiohttp.ClientSession() as session:
        async with session.get(api_url) as raw_page:
            results = html.fromstring(await raw_page.text())[0][0]
    choice = secrets.choice(results)
    image_url = str(choice[0].text)
    embed = discord.Embed(color=0xFFDC5D, title='?? Meow~')
    embed.set_image(url=image_url)
    await message.channel.send(None, embed=embed)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def safebooru(cmd, message, args):
    if not args:
        tag = 'cute'
    else:
        tag = ' '.join(args)
        tag = tag.replace(' ', '+')
    resource = 'http://safebooru.org/index.php?page=dapi&s=post&q=index&tags=' + tag
    async with aiohttp.ClientSession() as session:
        async with session.get(resource) as data:
            data = await data.read()
    posts = html.fromstring(data)
    if len(posts) == 0:
        embed = discord.Embed(color=0x696969, title='?? Nothing found.')
    else:
        choice = secrets.choice(posts)
        image_url = choice.attrib['file_url']
        icon_url = 'https://i.imgur.com/3Vb6LdJ.png'
        post_url = f'http://safebooru.org/index.php?page=post&s=view&id={choice.attrib["id"]}'
        if image_url.startswith('//'):
            image_url = 'http:' + image_url
        embed = discord.Embed(color=0x8bb2a7)
        embed.set_author(name='Safebooru', icon_url=icon_url, url=post_url)
        embed.set_image(url=image_url)
        embed.set_footer(
            text=f'Score: {choice.attrib["score"]} | Size: {choice.attrib["width"]}x{choice.attrib["height"]}')
    await message.channel.send(None, embed=embed)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def generate_embed(post, titles, color=0xff6699, icon='https://i.imgur.com/WQbzk9y.png'):
    image_url = post.attrib['file_url']
    image_source = f'http://safebooru.org/index.php?page=post&s=view&id={post.attrib["id"]}'
    if image_url.startswith('//'):
        image_url = 'https:' + image_url
    embed = discord.Embed(color=color)
    embed.set_author(name=secrets.choice(titles), icon_url=icon, url=image_source)
    embed.set_image(url=image_url)
    embed.set_footer(
        text=f'Score: {post.attrib["score"]} | Size: {post.attrib["width"]}x{post.attrib["height"]}')
    return embed
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def grab_post(subreddit, argument):
    if argument == 'tophot':
        post = list(subreddit.hot(limit=1))[0]
    elif argument == 'topnew':
        post = list(subreddit.new(limit=1))[0]
    elif argument == 'randomnew':
        post = secrets.choice(list(subreddit.new(limit=100)))
    elif argument == 'toptop':
        post = list(subreddit.top(limit=1))[0]
    elif argument == 'randomtop':
        post = secrets.choice(list(subreddit.top(limit=100)))
    else:
        post = secrets.choice(list(subreddit.hot(limit=100)))
    return post
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def dance(cmd, message, args):
    interaction = grab_interaction(cmd.db, 'dance')
    target = get_target(message)
    auth = message.author
    icons = ['??', '??']
    icon = secrets.choice(icons)
    if not target or target.id == message.author.id:
        response = discord.Embed(color=0xdd2e44, title=f'{icon} {auth.display_name} dances.')
    else:
        response = discord.Embed(color=0xdd2e44, title=f'{icon} {auth.display_name} dances with {target.display_name}.')
    response.set_image(url=interaction['URL'])
    response.set_footer(text=make_footer(cmd, interaction))
    await message.channel.send(embed=response)
项目:mathhammer    作者:daed    | 项目源码 | 文件源码
def getRoll(die=d6):
    return secrets.choice(die)

# All math in 40k is based on rolling higher than something else.
项目:python-web-boilerplate    作者:svenstaro    | 项目源码 | 文件源码
def generate_auth_token(self):
        """Generate an auth token and save it to the `current_auth_token` column."""
        alphabet = string.ascii_letters + string.digits
        new_auth_token = ''.join(secrets.choice(alphabet) for i in range(32))
        self.current_auth_token = new_auth_token
        self.last_action = datetime.utcnow()
        db.session.add(self)
        db.session.commit()
        return new_auth_token
项目:ycml    作者:skylander86    | 项目源码 | 文件源码
def main():
    parser = ArgumentParser(description='Generate a secret key.')
    parser.add_argument('-l', '--length', type=int, default=32, help='Length of secret key in bytes.')
    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('-x', '--hex', action='store_true', help='Convert secret key to hexadecimal.')
    group.add_argument('-a', '--alphanum', action='store_true', help='Generate alphanumeric keys only.')
    A = parser.parse_args()

    if A.alphanum:
        alphabet = string.ascii_letters + string.digits
        print(''.join(choice(alphabet) for i in range(A.length)))
    elif A.hex: print(token_hex(A.length))
    else: print(token_bytes(A.length))
    #end if
#end def
项目:Windless    作者:chiaki64    | 项目源码 | 文件源码
def load(self):
        (eternity, instant) = ({}, {
            'tk': b'\x9f?\x05\xb90\x01R\xb9\xc0\xa5V`\xb3\xaa\xf3\xa0]\xceN\xb0C\xcc\x9d=~\xa5U\xc2W\x88\xd2\xc4'
        })
        try:
            with open('./eternity.yaml') as file:
                eternity = yaml.load(file)
            if not eternity:
                raise ValueError
        except (TypeError, FileNotFoundError, ValueError):
            raise SystemExit('Please configure eternity.yaml correctly.')

        if eternity['env']['hostname'] == socket.gethostname():
            self.dev = True

        if 'maintain' not in eternity['server']:
            self.maintain = eternity['server']['maintain'] = False
            self.dumps(eternity)

        if 'otp_key' not in eternity['admin'] or eternity['admin']['otp_key'] == '':
            eternity['admin']['otp_key'] = ''.join(
                map(lambda x: secrets.choice(f'{string.ascii_uppercase}234567'), [1] * 16)
            )
            self.dumps(eternity)

        if 'identity' not in eternity['admin'] or eternity['admin']['identity'] == '':
            eternity['admin']['identity'] = ''.join(
                map(lambda x: secrets.choice(f'{string.ascii_letters}{string.digits}'), [1] * 4)
            )
            self.dumps(eternity)

        if self.dev:
            self.redis_ip = eternity['redis']['host']
            self.template_addr = f"./resource/templates/{eternity['server']['template']}"
        else:
            self.redis_ip = os.environ['REDIS_PORT_6379_TCP_ADDR']
            self.template_addr = f"/code/core/resource/templates/{eternity['server']['template']}"

        self.eternity = eternity
        self.config = ChainMap(instant, eternity)
项目:MakePass    作者:Lucretiel    | 项目源码 | 文件源码
def random_stream(things):
    '''
    Generate an infinite sequence of random things from a list of things.
    '''
    return map(random_choice, itertools.repeat(things))
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def unscramble(cmd, message, args):
    if message.channel.id not in ongoing_list:
        ongoing_list.append(message.channel.id)
        source_urls = [
            'http://www.wordgenerator.net/application/p.php?type=1&id=dictionary_words&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_easy&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_moderate&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_hard&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_very_hard&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=animal_names&spaceflag=false'
        ]
        source_url = secrets.choice(source_urls)
        async with aiohttp.ClientSession() as session:
            async with session.get(source_url) as source_session:
                source_text = await source_session.text()
        words = source_text.split(',')
        clean_words = []
        for word in words:
            if word:
                if len(word) > 3:
                    clean_words.append(word)
        word_choice = secrets.choice(clean_words)
        kud_reward = len(word_choice)
        scrambled = scramble(word_choice)
        question_embed = discord.Embed(color=0x3B88C3, title=f'?? {scrambled}')
        await message.channel.send(embed=question_embed)

        def check_answer(msg):
            if message.channel.id == msg.channel.id:
                if msg.content.lower() == word_choice.lower():
                    correct = True
                else:
                    correct = False
            else:
                correct = False
            return correct

        try:
            answer_message = await cmd.bot.wait_for('message', check=check_answer, timeout=30)
            await cmd.db.add_currency(answer_message.author, message.guild, kud_reward)
            author = answer_message.author.display_name
            currency = cmd.bot.cfg.pref.currency
            win_title = f'?? Correct, {author}, it was {word_choice}. You won {kud_reward} {currency}!'
            win_embed = discord.Embed(color=0x77B255, title=win_title)
            await message.channel.send(embed=win_embed)
        except asyncio.TimeoutError:
            timeout_title = f'?? Time\'s up! It was {word_choice}...'
            timeout_embed = discord.Embed(color=0x696969, title=timeout_title)
            await message.channel.send(embed=timeout_embed)
        if message.channel.id in ongoing_list:
            ongoing_list.remove(message.channel.id)
    else:
        ongoing_error = discord.Embed(color=0xBE1931, title='? There is one already ongoing.')
        await message.channel.send(embed=ongoing_error)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def dokidoki(cmd, message, args):
    char = None
    glitch = False
    if args:
        if args[0][0].lower() in files:
            char = args[0][0].lower()
        if args[-1].startswith(':g'):
            glitch = True
    if not char:
        char = secrets.choice(list(files))
    char_file = files[char]
    with open(f'doki/{char_file}.luci', 'rb') as quote_file:
        quotes = quote_file.read()
    key = cmd.bot.cfg.pref.raw.get('key_to_my_heart')
    if key:
        key = key.encode('utf-8')
        cipher = Fernet(key)
        try:
            ciphered = cipher.decrypt(quotes).decode('utf-8')
        except InvalidToken:
            ciphered = None
        if ciphered:
            if not glitch:
                glitch = secrets.randbelow(6)
                glitch = not bool(glitch)
            if glitch:
                line_count = 1
                thumbnail = chars_glitch[char]
            else:
                line_count = 3
                thumbnail = secrets.choice(chars[char])
            lines = []
            for x in range(0, line_count):
                output = markovify.Text(ciphered).make_short_sentence(500, tries=100)
                output = clean(output, message.author)
                if glitch:
                    output = cipher.encrypt(output.encode('utf-8')).decode('utf-8')
                lines.append(output)
            output_final = ' '.join(lines)
            if glitch:
                title = titles_glitch[char]
            else:
                title = titles[char]
            response = discord.Embed(color=0xe75a70)
            response.add_field(name=f'?? {title}', value=output_final)
            response.set_thumbnail(url=thumbnail)
        else:
            response = discord.Embed(color=0xe75a70, title='?? Sorry but that key is incorrect!')
    else:
        response = discord.Embed(color=0xe75a70, title='?? You are missing the key to my heart!')
    await message.channel.send(embed=response)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def unscramble(cmd, message, args):
    if message.channel.id not in ongoing_list:
        ongoing_list.append(message.channel.id)
        source_urls = [
            'http://www.wordgenerator.net/application/p.php?type=1&id=dictionary_words&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_easy&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_moderate&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_hard&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=charades_very_hard&spaceflag=false',
            'http://www.wordgenerator.net/application/p.php?type=1&id=animal_names&spaceflag=false'
        ]
        source_url = secrets.choice(source_urls)
        async with aiohttp.ClientSession() as session:
            async with session.get(source_url) as source_session:
                source_text = await source_session.text()
        words = source_text.split(',')
        clean_words = []
        for word in words:
            if word:
                if len(word) > 3:
                    clean_words.append(word)
        word_choice = secrets.choice(clean_words)
        kud_reward = len(word_choice)
        scrambled = scramble(word_choice)
        question_embed = discord.Embed(color=0x3B88C3, title=f'?? {scrambled}')
        await message.channel.send(embed=question_embed)

        def check_answer(msg):
            if message.channel.id == msg.channel.id:
                if msg.content.lower() == word_choice.lower():
                    correct = True
                else:
                    correct = False
            else:
                correct = False
            return correct

        try:
            answer_message = await cmd.bot.wait_for('message', check=check_answer, timeout=30)
            cmd.db.add_currency(answer_message.author, message.guild, kud_reward)
            author = answer_message.author.display_name
            currency = cmd.bot.cfg.pref.currency
            win_title = f'?? Correct, {author}, it was {word_choice}. You won {kud_reward} {currency}!'
            win_embed = discord.Embed(color=0x77B255, title=win_title)
            await message.channel.send(embed=win_embed)
        except asyncio.TimeoutError:
            timeout_title = f'?? Time\'s up! It was {word_choice}...'
            timeout_embed = discord.Embed(color=0x696969, title=timeout_title)
            await message.channel.send(embed=timeout_embed)
        if message.channel.id in ongoing_list:
            ongoing_list.remove(message.channel.id)
    else:
        ongoing_error = discord.Embed(color=0xBE1931, title='? There is one already ongoing.')
        await message.channel.send(embed=ongoing_error)