def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return ''.join(choice(chars) for _ in range(size))
python类choice()的实例源码
models_utils.py 文件源码
项目:Django-Code-Review-CodeEntrepreneurs
作者: guinslym
项目源码
文件源码
阅读 15
收藏 0
点赞 0
评论 0
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
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)
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
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
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)
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)
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)
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)
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
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
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)
def getRoll(die=d6):
return secrets.choice(die)
# All math in 40k is based on rolling higher than something else.
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
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
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)
def random_stream(things):
'''
Generate an infinite sequence of random things from a list of things.
'''
return map(random_choice, itertools.repeat(things))
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)
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)
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)