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)
python类choice()的实例源码
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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 = 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)
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 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 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)
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 = 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)
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)
def random_key(self):
return "".join(secrets.choice(LC) for _ in range(128))
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)
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)
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)
def _password(length, alphabet=_default_letters):
return ''.join(secrets.choice(alphabet) for i in range(length))
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))
def _class(self):
return random.choice(_diepio_tanks)
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))
def gen_bindhost():
return random.choice(BIND_HOST_NET)