本文整理汇总了Python中random.randchoice函数的典型用法代码示例。如果您正苦于以下问题:Python randchoice函数的具体用法?Python randchoice怎么用?Python randchoice使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了randchoice函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: startSnack
async def startSnack(self, message):
scid = message.server.id+"-"+message.channel.id
if self.acceptInput.get(scid,False):
return
await self.bot.send_message(message.channel, randchoice(self.startPhrases))
#set econ here? don't need to unset it.
self.econ = self.bot.get_cog('Economy')
self.acceptInput[scid] = True
self.alreadySnacked[scid] = []
duration = self.settings[scid]["SNACK_DURATION"] + randint(-self.settings[scid]["SNACK_DURATION_VARIANCE"], self.settings[scid]["SNACK_DURATION_VARIANCE"])
await asyncio.sleep(duration)
#sometimes fails sending messages and stops all future snacktimes. Hopefully this fixes it.
try:
#list isn't empty
if self.alreadySnacked.get(scid,False):
await self.bot.send_message(message.channel, randchoice(self.outPhrases))
self.repeatMissedSnacktimes[scid] = 0
dataIO.save_json("data/snacktime/repeatMissedSnacktimes.json", self.repeatMissedSnacktimes)
else:
await self.bot.send_message(message.channel, randchoice(self.notakersPhrases))
self.repeatMissedSnacktimes[scid] = self.repeatMissedSnacktimes.get(scid,0) + 1
await asyncio.sleep(2)
if self.repeatMissedSnacktimes[scid] > 9: #move to a setting
await self.bot.send_message(message.channel, "`ʕ •ᴥ•ʔ < I guess you guys don't like snacktimes.. I'll stop comin around.`")
self.channels[scid] = False
dataIO.save_json("data/snacktime/channels.json", self.channels)
self.repeatMissedSnacktimes[scid] = 0
dataIO.save_json("data/snacktime/repeatMissedSnacktimes.json", self.repeatMissedSnacktimes)
except:
print("Failed to send message")
self.acceptInput[scid] = False
self.snackInProgress[scid] = False
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:33,代码来源:snacktime.py
示例2: insult
async def insult(self, ctx, user : discord.Member=None):
"""Insult the user"""
msg = ' '
if user != None:
if user.id == self.bot.user.id:
user = ctx.message.author
msg = " How original. No one else had thought of trying to get the bot to insult itself. I applaud your creativity. Yawn. Perhaps this is why you don't have friends. You don't add anything new to any conversation. You are more of a bot than me, predictable answers, and absolutely dull to have an actual conversation with."
await self.bot.say(user.mention + msg)
else:
await self.bot.say(user.mention + msg + randchoice(self.insults))
else:
await self.bot.say(ctx.message.author.mention + msg + randchoice(self.insults))
开发者ID:FishyFing,项目名称:Red-Cogs,代码行数:13,代码来源:insult.py
示例3: resetBrick
def resetBrick(brick):
brickShapes = [[(0,0), (1,0), (2,0), (3,0)],
[(0,0), (1,0), (1,1), (2,1)],
[(0,0), (1,0), (1,1), (2,0)]]
colors = [(1,0,0), (0,1,0), (0,0,1)]
randColor = randchoice(colors)
for x, y in randchoice(brickShapes):
newBox = box.clone()
newBox.position = x, y
# connect the free socket
box.var.outlineShader.inputs[0] = pyge.Shaders.Color(randColor)
brick.children.append(newBox)
brick.position = 3, 12
开发者ID:addam,项目名称:pyg,代码行数:13,代码来源:tetris.py
示例4: __init__
def __init__(self, position):
model.Object.__init__(self)
self.rect = pygame.Rect(0,0,*self.size)
self.image_green = pygame.surface.Surface(self.rect.size)
self.image_green.fill(Color('green'))
self.image_red = pygame.surface.Surface(self.rect.size)
self.image_red.fill(Color('red'))
self.image = self.image_green
self.position = position
choices = [-0.5,-0.4,-0.3,0.3,0.4,0.5]
self.step = Vec2d(randchoice(choices), randchoice(choices))
self.hit = 0
开发者ID:icarito,项目名称:sunset-adventure,代码行数:15,代码来源:24_spatialhash_stress_test.py
示例5: new_question
async def new_question(self):
for score in self.score_list.values():
if score == self.settings["TRIVIA_MAX_SCORE"]:
await self.end_game()
return True
if self.question_list == []:
await self.end_game()
return True
self.current_q = randchoice(self.question_list)
self.question_list.remove(self.current_q)
self.status = "waiting for answer"
self.count += 1
self.timer = int(time.perf_counter())
msg = "**Question number {}!**\n\n{}".format(str(self.count), self.current_q["QUESTION"])
try:
await trivia_manager.bot.say(msg)
except:
await asyncio.sleep(0.5)
await trivia_manager.bot.say(msg)
while self.status != "correct answer" and abs(self.timer - int(time.perf_counter())) <= self.settings["TRIVIA_DELAY"]:
if abs(self.timeout - int(time.perf_counter())) >= self.settings["TRIVIA_TIMEOUT"]:
await trivia_manager.bot.say("Guys...? Well, I guess I'll stop then.")
await self.stop_trivia()
return True
await asyncio.sleep(1) #Waiting for an answer or for the time limit
if self.status == "correct answer":
self.status = "new question"
await asyncio.sleep(3)
if not self.status == "stop":
await self.new_question()
elif self.status == "stop":
return True
else:
msg = randchoice(self.gave_answer).format(self.current_q["ANSWERS"][0])
if self.settings["TRIVIA_BOT_PLAYS"]:
msg += " **+1** for me!"
self.add_point(trivia_manager.bot.user.name)
self.current_q["ANSWERS"] = []
try:
await trivia_manager.bot.say(msg)
await trivia_manager.bot.send_typing(self.channel)
except:
await asyncio.sleep(0.5)
await trivia_manager.bot.say(msg)
await asyncio.sleep(3)
if not self.status == "stop":
await self.new_question()
开发者ID:BlazyDoesDev,项目名称:Toothy,代码行数:48,代码来源:trivia.py
示例6: get_user
async def get_user(self, ctx, username: str):
"""Get info about the specified user"""
message = ""
if username is not None:
api = self.authenticate()
user = api.get_user(username)
colour =\
''.join([randchoice('0123456789ABCDEF')
for x in range(6)])
colour = int(colour, 16)
url = "https://twitter.com/" + user.screen_name
emb = discord.Embed(title=user.name,
colour=discord.Colour(value=colour),
url=url,
description=user.description)
emb.set_thumbnail(url=user.profile_image_url)
emb.add_field(name="Followers", value=user.followers_count)
emb.add_field(name="Friends", value=user.friends_count)
if user.verified:
emb.add_field(name="Verified", value="Yes")
else:
emb.add_field(name="Verified", value="No")
footer = "Created at " + user.created_at.strftime("%Y-%m-%d %H:%M:%S")
emb.set_footer(text=footer)
await self.bot.send_message(ctx.message.channel, embed=emb)
else:
message = "Uh oh, an error occurred somewhere!"
await self.bot.say(message)
开发者ID:palmtree5,项目名称:palmtree5-cogs,代码行数:29,代码来源:tweets.py
示例7: __init__
def __init__(self):
self.gender = randchoice(('m','f'))
self.firstname = self._random_firstname()
self.lastname = self._random_lastname()
self.birthdate = self._random_birthdate()
self.placeofbirth = self._random_placeofbirth()
self.codfis = self._gen_cf()
开发者ID:eldios,项目名称:RCFG,代码行数:7,代码来源:rcfg.py
示例8: _user
async def _user(self, ctx, username: str):
"""Commands for getting user info"""
url = "https://oauth.reddit.com/user/{}/about".format(username)
headers = {
"Authorization": "bearer " + self.access_token,
"User-Agent": "Red-DiscordBotRedditCog/0.1 by /u/palmtree5"
}
async with aiohttp.get(url, headers=headers) as req:
resp_json = await req.json()
resp_json = resp_json["data"]
colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)])
colour = int(colour, 16)
created_at = dt.utcfromtimestamp(resp_json["created_utc"])
desc = "Created at " + created_at.strftime("%m/%d/%Y %H:%M:%S")
em = discord.Embed(title=resp_json["name"],
colour=discord.Colour(value=colour),
url="https://reddit.com/u/" + resp_json["name"],
description=desc)
em.add_field(name="Comment karma", value=resp_json["comment_karma"])
em.add_field(name="Link karma", value=resp_json["link_karma"])
if "over_18" in resp_json and resp_json["over_18"]:
em.add_field(name="Over 18?", value="Yes")
else:
em.add_field(name="Over 18?", value="No")
if "is_gold" in resp_json and resp_json["is_gold"]:
em.add_field(name="Is gold?", value="Yes")
else:
em.add_field(name="Is gold?", value="No")
await self.bot.send_message(ctx.message.channel, embed=em)
开发者ID:palmtree5,项目名称:palmtree5-cogs,代码行数:29,代码来源:reddit.py
示例9: subreddit_info
async def subreddit_info(self, ctx, subreddit: str):
"""Command for getting subreddit info"""
url = "https://oauth.reddit.com/r/{}/about".format(subreddit)
headers = {
"Authorization": "bearer " + self.access_token,
"User-Agent": "Red-DiscordBotRedditCog/0.1 by /u/palmtree5"
}
async with aiohttp.get(url, headers=headers) as req:
resp_json = await req.json()
if "data" not in resp_json and resp_json["error"] == 403:
await self.bot.say("Sorry, the currently authenticated account does not have access to that subreddit")
return
resp_json = resp_json["data"]
colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)])
colour = int(colour, 16)
created_at = dt.utcfromtimestamp(resp_json["created_utc"])
created_at = created_at.strftime("%m/%d/%Y %H:%M:%S")
em = discord.Embed(title=resp_json["url"],
colour=discord.Colour(value=colour),
url="https://reddit.com" + resp_json["url"],
description=resp_json["header_title"])
em.add_field(name="Title", value=resp_json["title"])
em.add_field(name="Created at", value=created_at)
em.add_field(name="Subreddit type", value=resp_json["subreddit_type"])
em.add_field(name="Subscriber count", value=resp_json["subscribers"])
if resp_json["over18"]:
em.add_field(name="Over 18?", value="Yes")
else:
em.add_field(name="Over 18?", value="No")
await self.bot.send_message(ctx.message.channel, embed=em)
开发者ID:palmtree5,项目名称:palmtree5-cogs,代码行数:30,代码来源:reddit.py
示例10: rps
async def rps(self, ctx, choice : str):
"""Play rock paper scissors"""
author = ctx.message.author
rpsbot = {"rock" : ":moyai:",
"paper": ":page_facing_up:",
"scissors":":scissors:"}
choice = choice.lower()
if choice in rpsbot.keys():
botchoice = randchoice(list(rpsbot.keys()))
msgs = {
"win": " You win {}!".format(author.mention),
"square": " We're square {}!".format(author.mention),
"lose": " You lose {}!".format(author.mention)
}
if choice == botchoice:
await self.bot.say(rpsbot[botchoice] + msgs["square"])
elif choice == "rock" and botchoice == "paper":
await self.bot.say(rpsbot[botchoice] + msgs["lose"])
elif choice == "rock" and botchoice == "scissors":
await self.bot.say(rpsbot[botchoice] + msgs["win"])
elif choice == "paper" and botchoice == "rock":
await self.bot.say(rpsbot[botchoice] + msgs["win"])
elif choice == "paper" and botchoice == "scissors":
await self.bot.say(rpsbot[botchoice] + msgs["lose"])
elif choice == "scissors" and botchoice == "rock":
await self.bot.say(rpsbot[botchoice] + msgs["lose"])
elif choice == "scissors" and botchoice == "paper":
await self.bot.say(rpsbot[botchoice] + msgs["win"])
else:
await self.bot.say("Choose rock, paper or scissors.")
开发者ID:srowhani,项目名称:Red-DiscordBot,代码行数:30,代码来源:general.py
示例11: pfps
async def pfps(self, ctx, choice : str):
"""Play rock paper scissors"""
author = ctx.message.author
rpsbot = {"pierre" : ":moyai:",
"papier": ":page_facing_up:",
"ciseaux":":scissors:"}
choice = choice.lower()
if choice in rpsbot.keys():
botchoice = randchoice(list(rpsbot.keys()))
msgs = {
"win": " Bravo {}!".format(author.mention),
"square": " Egalité {}!".format(author.mention),
"lose": " Dommage {}!".format(author.mention)
}
if choice == botchoice:
await self.bot.say(rpsbot[botchoice] + msgs["square"])
elif choice == "pierre" and botchoice == "papier":
await self.bot.say(rpsbot[botchoice] + msgs["lose"])
elif choice == "pierre" and botchoice == "ciseaux":
await self.bot.say(rpsbot[botchoice] + msgs["win"])
elif choice == "papier" and botchoice == "pierre":
await self.bot.say(rpsbot[botchoice] + msgs["win"])
elif choice == "papier" and botchoice == "ciseaux":
await self.bot.say(rpsbot[botchoice] + msgs["lose"])
elif choice == "ciseaux" and botchoice == "pierre":
await self.bot.say(rpsbot[botchoice] + msgs["lose"])
elif choice == "ciseaux" and botchoice == "papier":
await self.bot.say(rpsbot[botchoice] + msgs["win"])
else:
await self.bot.say("Choisis pierre, papier ou ciseaux.")
开发者ID:jak852,项目名称:FATbot,代码行数:30,代码来源:general.py
示例12: cute
async def cute(self, ctx):
"""Tell pirra she's a cute girl
"""
author = ctx.message.author
if author.name == "DrQuint":
return await self.bot.say("Cute! Pirra is CUTE! :sparkling_heart:")
else:
return await self.bot.say(randchoice(self.settings["Disobey_Pokemon"]).format(self.settings["Botname"]))
开发者ID:DrQuint,项目名称:QuintbotCogs,代码行数:8,代码来源:pirra.py
示例13: punish
async def punish(self, ctx):
"""Tell pirra she's a bad girl
"""
author = ctx.message.author
if author.name == "DrQuint":
return await self.bot.say("Bad girl! Pirra's a BAD girl!")
else:
return await self.bot.say(randchoice(self.settings["Disobey_Pokemon"]).format(self.settings["Botname"]))
开发者ID:DrQuint,项目名称:QuintbotCogs,代码行数:8,代码来源:pirra.py
示例14: fuzz_value
def fuzz_value(self, value, fuzz_type=None):
"""
This method mutates a given string value. The input string is *value*, which
may or may not affect the mutation. *fuzz_type* specifies how the string will
be mutated. A value of None indicates that a random fuzz_type should be used
for each mutation of the string.
The result is a mutation which may or may not be based on the original string.
"""
if fuzz_type is None:
fuzz_type = self.random_fuzz_type()
else:
self._validate_fuzz_type(fuzz_type)
if fuzz_type == STRFUZZ_EMPTY:
result = ""
elif fuzz_type == STRFUZZ_CORRUPT:
result = os.urandom(len(value))
elif fuzz_type == STRFUZZ_NULL:
if len(value):
out = list(value)
out[randint(0, len(value)-1)] = chr(0)
result = "".join(out)
else:
result = value
elif fuzz_type == STRFUZZ_INT:
result = IntegerFuzzer().fuzz_value(FuzzableInteger("0"))
elif fuzz_type == STRFUZZ_SHRINK:
result = value[:-1]
elif fuzz_type == STRFUZZ_GROW:
result = "%saa" % value
elif fuzz_type == STRFUZZ_JUNK:
result = os.urandom(randint(1, self.max_len))
elif fuzz_type == STRFUZZ_XSS:
result = randchoice(STRFUZZ_XSS_VALUES)
elif fuzz_type == STRFUZZ_SPECIAL:
result = self.special
elif fuzz_type == STRFUZZ_PREV_DIRS:
result = "../" * randint(1, 32)
elif fuzz_type == STRFUZZ_FORMAT_CHAR:
result = randchoice(["%n", "%s"]) * randint(1, 32)
elif fuzz_type == STRFUZZ_DELIMITERS:
result = randchoice([" ", ",", ".", ";", ":", "\n", "\t"])
else:
raise ValueError("Unhandled Fuzz Type: %d" % fuzz_type)
return result
开发者ID:blackberry,项目名称:ALF,代码行数:46,代码来源:ValueFuzz.py
示例15: check_lang_file
def check_lang_file(speech):
# Check language file
for lang_name in lang_commands: # For item in lang_commands variable
for item in lang[lang_name]['Alternatives']: # For each item in alternartives list
if speech in item: # If speech in item
say(randchoice(lang[lang_name]['Responses'])) # Say response
return True # Return true
return False # Return false
开发者ID:jakeyjdavis,项目名称:Ada,代码行数:8,代码来源:assistant.py
示例16: main
def main():
pchars = printable[:96] + printable[97:]
s = StringIO()
with redirect_stdout(s):
n = 10**6
print(n)
s1 = ''.join(randchoice(pchars) for _ in range(n))
print(s1)
s2 = ''.join(randchoice(pchars) for _ in range(n))
print(s2)
m = 10**6
print(m)
for _ in range(m):
l = randrange(n)
r = randrange(l, n)
print(l, r)
#print(s.getvalue(), end='')
print(s.getvalue(), end='', file=open('{}.in'.format(sys.argv[1]), 'w'))
开发者ID:eightnoteight,项目名称:compro,代码行数:18,代码来源:stavatar_testgen.py
示例17: _8ball
async def _8ball(self, *, question : str):
"""Ask 8 ball a question
Question must end with a question mark.
"""
if question.endswith("?") and question != "?":
await self.bot.say("`" + randchoice(self.ball) + "`")
else:
await self.bot.say("That doesn't look like a question.")
开发者ID:d3fin3d,项目名称:mercycogs,代码行数:9,代码来源:general.py
示例18: choose
async def choose(self, *choices):
"""Chooses between multiple choices.
To denote multiple choices, you should use double quotes.
"""
if len(choices) < 2:
await self.bot.say('Not enough choices to pick from.')
else:
await self.bot.say(randchoice(choices))
开发者ID:srowhani,项目名称:Red-DiscordBot,代码行数:9,代码来源:general.py
示例19: _random_firstname
def _random_firstname(self):
"""Pick a random firstname from 50 of the most common Italian male/female firstnames"""
firstname_list = {
'f' : (
'alessandra','alessia','alice','angela','anna','arianna','beatrice','camilla','caterina','chiara','claudia','cristina','debora','elena','eleonora','elisa','erica','erika','federica','francesca','gaia','giada','giorgia','giulia','greta','ilaria','irene','jessica','laura','lisa','lucia','maria','marta','martina','michela','monica','nicole','noemi','paola','roberta','sara','serena','silvia','simona','sofia','stefania','valentina','valeria','vanessa','veronica' ) ,
'm' : (
'alberto','alessandro','alessio','alex','andrea','angelo','antonio','christian','claudio','daniele','dario','davide','domenico','edoardo','emanuele','enrico','fabio','federico','fernando','filippo','francesco','gabriele','giacomo','gianluca','giorgio','giovanni','giulio','giuseppe','jacopo','leonardo','lorenzo','luca','luigi','manuel','marco','matteo','mattia','michele','mirko','nicola','nicolò','paolo','pietro','riccardo','roberto','salvatore','simone','stefano','tommaso','valerio','vincenzo' )
}
return randchoice(firstname_list[self.gender]).title()
开发者ID:eldios,项目名称:RCFG,代码行数:9,代码来源:rcfg.py
示例20: choose
async def choose(self, *choices):
"""Chooses between multiple choices.
To denote multiple choices, you should use double quotes.
"""
choices = [escape_mass_mentions(choice) for choice in choices]
if len(choices) < 2:
await self.bot.say('Not enough choices to pick from.')
else:
await self.bot.say(randchoice(choices))
开发者ID:b0r3d0,项目名称:kitty,代码行数:10,代码来源:general.py
注:本文中的random.randchoice函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论