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
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))
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
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
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()
async def status(self, ctx): """Shows antilink status.""" channel = ctx.message.channel server = ctx.message.server directory = fileIO(self.link_data, "load") db = directory[server.id] if len(db["Blacklisted"]) != 0: words = "- {}".format("\n-".join( ["{}".format(x) for x in db["Blacklisted"]])) else: words = "No Links/Words blacklisted for this server" colour = ''.join( [randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) status = (str(db["Toggle"]).replace("True", "Enabled")).replace( "False", "Disabled") e = discord.Embed() e.colour = colour e.description = "Showing AntiLink Settings For {0}\nDo {1.prefix}help {1.command.qualified_name} for more info".format( server.name, ctx) e.set_author(name="AntiLink Settings") e.add_field(name="AntiLink Status", value=status) e.add_field(name="AntiInvite Enabled", value=db["No Invite"]) e.add_field(name="AntiLinks Enabled", value=db["Toggle Blacklist"]) e.add_field(name="Blacklisted Words", value=words, inline=False) e.set_footer(text="AntiLink Settings", icon_url=server.icon_url) e.timestamp = ctx.message.timestamp try: await self.bot.send_message(channel, embed=e) except discord.Forbidden: msg = "```css\nAntiLink Settings for {0.name}.\nDo {1.prefix}help {1.command.qualified_name} for more info\n".format( server, ctx) msg += "AntiLink Status : {0}\nAntiInvite Enabled : {1}\nAntilinks Enabled : {2}\nBlacklisted Words: {3}\n```".format( status, db["No Invite"], db["Toggle Blacklist"], words) await self.bot.send_message(channel, msg)
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.")
async def errorlogger(self, ctx): """Manage Logging Settings.""" channel = ctx.message.channel server = ctx.message.server my = server.me data = fileIO(self.log_data, "load") if ctx.invoked_subcommand is None: colour = ''.join( [randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) if data["Channel"] is None: kek = "No Channel Chosen" else: kek = "Channel: #{0.name}\nID: {0.id}".format( self.bot.get_channel(data["Channel"])) e = discord.Embed() e.colour = colour e.description = "Showing Error Log Settings\nDo {}help errorlogger for more info".format( ctx.prefix) e.set_author(name="Error Logging") e.add_field(name="Logging Enabled", value=data["Toggle"]) e.add_field(name="Server Logging", value=data["Server Logs"]) e.add_field(name="Error Logging", value=data["Error Logs"]) e.add_field(name="Startup Logging", value=data["Startup"]) e.add_field(name="Session Resume Logs", value=data["Resumed"]) e.add_field(name="DirectMessage Enabled", value=data["Direct Message"]) e.add_field(name="Channel Messages Enabled", value=data["Channel Logs"]) e.add_field(name="Channel Chosen", value=kek) e.set_footer(text="Error Logs", icon_url=self.bot.user.avatar_url) await self.bot.send_message(ctx.message.channel, embed=e)
async def on_resumed(self): print("Error Logger: On Resumed") data = fileIO(self.log_data, "load") owner = discord.utils.get(self.bot.get_all_members(), id=owner_id) colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) name = self.bot.user.name + "#" + self.bot.user.discriminator cogs = "\n".join(e for e in self.bot.cogs) prefix = " , ".join(e for e in self.bot.command_prefix) e = discord.Embed() uptime = self.bot.get_cog("Utility").get_bot_uptime() e.title = "{} has Resumed the Session \U00002705".format(name) e.set_author(name="Log : Session Resume") e.add_field(name="Commands", value=str(len(self.bot.commands))) e.add_field(name="Servers", value=str(len(self.bot.servers))) e.add_field(name="Prefix", value=prefix) e.add_field(name="Total Cogs", value=str(len(self.bot.cogs))) e.add_field(name="Uptime", value=uptime) e.add_field(name="Cog List", value=cogs, inline=False) e.colour = colour e.timestamp = datetime.datetime.utcnow() e.set_footer(text="Started At |", icon_url=self.bot.user.avatar_url) if data["Toggle"] is True and data["Startup"] is True: if data["Channel Logs"] is True: if data["Channel"] is not None: channel = self.bot.get_channel(data["Channel"]) await self.bot.send_message(channel, embed=e) else: pass if data["Direct Message"] is True: await self.bot.send_message(owner, embed=e) else: pass else: pass
async def embed_serverdata(self, server): #To make it look less ugly """Because I think it's neater""" colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) owner = server.owner namea = owner.name + "#" + owner.discriminator url = "http://dahoo.fr/wordpress/wp-content/uploads/2015/09/discord.jpg" if not server.icon_url else server.icon_url date = self.time_parse(value=(datetime.datetime.utcnow() - server.created_at)) e = discord.Embed() e.title = "Joined a Server \U00002611\nMy Server Count: {}".format( len(self.bot.servers)) e.set_thumbnail(url=url) e.colour = colour e.set_author(name="Log : Server Joins") e.add_field(name="Name", value=server.name) e.add_field(name="ID", value=server.id) e.add_field(name="Owner", value=namea) e.add_field(name="Total Members", value=str(len(server.members))) e.add_field(name="Created At", value="{0} ({1})".format( format(server.created_at, "%d %b %Y at %H:%M"), date)) e.timestamp = datetime.datetime.utcnow() e.set_footer(text="Server Join Logs", icon_url=self.bot.user.avatar_url) return e
async def _9ball(self, *, question): """Asks Beatrice's 9-Ball a question Question must end with a question mark.""" if question.endswith("?") and question != "?": return await self.bot.say("`" + randchoice(self.ball) + "`") else: return await self.bot.say("That doesn't look like a question.")
async def _afoff(self, ctx, *, item: str): """Displays an anonymous random f**k off message.""" try: await self.bot.delete_message(ctx.message) except discord.Forbidden: pass await self.bot.say("{} {}. ".format(randchoice(self.foffmsg), item))
async def automeme(self, message): user = message.author msg = message.content channel = message.channel if msg == "meme": await self.bot.send_message(channel, randchoice(self.spicymemes))
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)
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)
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)
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)
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.")
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.")
async def snacktime(self, ctx): """Man i'm hungry! When's snackburr gonna get back with more snacks?""" scid = ctx.message.server.id + "-" + ctx.message.channel.id if self.snacktimePrediction.get(scid, None) == None: if self.acceptInput.get(scid, False): return else: phrases = [ "Don't look at me. I donno where snackburr's at ¯\_(ツ)_/¯", "I hear snackburr likes parties. *wink wink", "I hear snackburr is attracted to channels with active conversations", "If you party, snackburr will come! 〈( ^o^)ノ" ] await self.bot.say(randchoice(phrases)) return seconds = self.snacktimePrediction[scid] - self.loop.time() if self.snacktimeCheckLock.get(scid, False): if randint(1, 4) == 4: await self.bot.say( "Hey, snackburr's on errands. I ain't his keeper Kappa") return self.snacktimeCheckLock[scid] = True if seconds < 0: await self.bot.say( "I'm not sure where snackburr is.. He's already " + str(-int(seconds / 60)) + " minutes late!") else: await self.bot.say( "snackburr's out on errands! I think he'll be back in " + str(int(seconds / 60)) + " minutes") await asyncio.sleep(40) self.snacktimeCheckLock[scid] = False
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)
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()
async def gn(self, ctx): a = ctx.message.author n = discord.Embed(colour=0x191970) avi = a.avatar_url contrast = await self.bot.get_user_info('238598123159683073') images = ( 'https://cdn.shopify.com/s/files/1/1698/6547/files/starcatalog_600x600.jpg?v=1511346010', 'https://wallpapertag.com/wallpaper/middle/7/1/c/544439-best-nighttime-wallpaper-2560x1440-for-phone.jpg', 'https://i.pinimg.com/originals/bc/6e/fc/bc6efc08653224473f590eab54647da4.jpg', 'http://www.newhdwallpaper.in/wp-content/uploads/2014/07/Good-night-time-best-wishes.jpg', 'https://ak5.picdn.net/shutterstock/videos/5633555/thumb/3.jpg', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSEsvQm_6YaslxY9lOIu5kMXxL174x4PXTwYetByCx70Xqot9uQ' ) image = randchoice(images) n.set_thumbnail(url=image) n.set_author(name='{} is going to sleep!'.format(a.name), icon_url=avi) if a.id == contrast.id: n.description = '{} says good night to all her cute little boys and girls!'.format( a.name) else: n.description = '{} says good night to all these cute little boys and girls!'.format( a.name) n.set_footer(text='Good Night!') await self.bot.say(embed=n) await self.bot.delete_message(ctx.message)
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)
def new(cls, player_info, difficulty): # pylint: disable=protected-access, attribute-defined-outside-init new_game = cls() new_game._difficulty = difficulty money = 1000 - (500 * difficulty) if money == 0: money = 100 clean_items() universe = Universe.new() Player.new(*player_info, money, randchoice(universe.regions)) victory_region = randchoice(universe.regions) victory_region.marketplace.add_winning_item(victory_region, Player()) return new_game
async def urban(self, *, search_terms: str, definition_number: int = 1): """Urban Dictionary search Definition number must be between 1 and 10""" # definition_number is just there to show up in the help # all this mess is to avoid forcing double quotes on the user search_terms = search_terms.split(" ") colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) try: if len(search_terms) > 1: pos = int(search_terms[-1]) - 1 search_terms = search_terms[:-1] else: pos = 0 if pos not in range(0, 11): # API only provides the pos = 0 # top 10 definitions except ValueError: pos = 0 search_terms = "+".join(search_terms) url = "http://api.urbandictionary.com/v0/define?term=" + search_terms try: async with aiohttp.get(url) as r: result = await r.json() if result["list"]: definition = result['list'][pos]['definition'] likes = result['list'][pos]['thumbs_up'] da_link = result['list'][pos]['permalink'] example = result['list'][pos]['example'] dislikes = result['list'][pos]['thumbs_down'] author = result['list'][pos]['author'] defs = len(result['list']) msg = ("***Definition #{} out of {}:\n***{}\n\n" "**Example:\n**{}".format(pos + 1, defs, definition, example)) msg = pagify(msg, ["\n"]) for page in msg: em = discord.Embed(description=page, colour=discord.Colour(value=colour)) em.set_footer( text= "Urban Dictionary | Likes 👍{} | Dislikes 👎{} | Creator {}" .format(likes, dislikes, author), icon_url=self.bot.user.avatar_url) em.set_author( name="Definition For {}".format(search_terms), icon_url= 'http://www.dimensionalbranding.com/userfiles/urban_dictionary.jpg', url=da_link) em.set_thumbnail(url=self.bot.user.avatar_url) await self.bot.say(embed=em) else: await self.bot.say( ":x: **Your** **search terms gave no results.** :no_good:") except IndexError: await self.bot.say("There is no definition #{}".format(pos + 1)) except: await self.bot.say("Error.")
async def nut(ctx, member: discord.Member): nut_gifs = static_lists.nut_gifs name = member.name user = ctx.author.name message = ("**" + user + "** nutted on **" + name + "**") embed = discord.Embed(title=message) embed.set_image(url=randchoice(nut_gifs)) await ctx.send(embed=embed)
async def poke(ctx, member: discord.Member): poke_gifs = static_lists.poke_gifs user = ctx.author.name name = member.name message = ("**" + user + "** " + "poked **" + name + "**") embed = discord.Embed(title=message) embed.set_image(url=randchoice(poke_gifs)) await ctx.send(embed=embed)
async def hug(ctx, member: discord.Member): user = ctx.author.name name = member.name message = ("**" + user + "** " + "gives **" + name + "** much hugs") hug_gifs = static_lists.hug_gifs embed = discord.Embed(title=message) embed.set_image(url=randchoice(hug_gifs)) await ctx.send(embed=embed)
def one_search(self, board, color): b = copy(board) current_color = copy(color) while not b.finished: move = randchoice(b.get_legal_moves(current_color)) b.execute_move(move, current_color) current_color *= -1 return b.winner
async def say(self, ctx, *, content): """Repeats your message""" channel = ctx.message.channel name = ctx.message.author.name colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) em = discord.Embed(title=content, colour=discord.Colour(value=colour)) await self.bot.send_message(channel, embed=em)
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
async def szkaluj(self, ctx, user: discord.Member = None): """Insults the specified user""" if user == ctx.message.author: await self.bot.say( "Hmm, why do you want this?\nhttps://imgur.com/ZeRe5GD") return if user != None: if user.id == self.bot.user.id: user = ctx.message.author await self.bot.say("(╯°□°)╯︵ ┻━┻\n{}".format( randchoice(self.angery))) else: await self.bot.say(":mega: **{}** {}".format( user.display_name, randchoice(self.insults))) else: await self.bot.say( ":heavy_multiplication_x: You need to mention a user")
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
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.sm = self.bot.get_cog('StorageManager') self.acceptInput[scid] = True self.alreadySnacked[scid] = [] self.currentSnack = randchoice(self.snacks) 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
def osnovni_seznam(tip_el, tip_iz, opis_sp, n, tez): seznam = [] def ze_v_seznamu(opis): for i in seznam: if i == opis: return True return False elementi_1 = tip_el.query.filter(tip_el.naboj > 0).all() elementi_2 = tip_el.query.filter(tip_el.naboj < 0).all() izjeme = tip_iz.query.all() while len(seznam) < n: if tez == 1 or len(izjeme) == 0: el1 = randchoice(elementi_1) el2 = randchoice(elementi_2) lcm = el1.naboj * el2.naboj // gcd(el1.naboj, el2.naboj) n_el1 = abs(lcm // el1.naboj) n_el2 = abs(lcm // el2.naboj) stock_n = abs(el2.naboj * n_el2 // n_el1) tip = "obicajna" data = { "ime1": el1.imena, "n1": n_el1, "ime2": el2.imena, "n2": n_el2, "simbol1": el1.simbol, "simbol2": el2.simbol, "stock_n": stock_n, } else: spojina = randchoice(izjeme) tip = "izjema" data = { "imena": spojina.imena, "formula_raw": spojina.formula, } opis = opis_sp(tip, data) if not ze_v_seznamu(opis): seznam.append(opis) return seznam
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"]))
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"]))
async def friends_menu(self, ctx, friends_list: list, message: discord.Message=None, page=0, timeout: int=30): """menu control logic for this taken from https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py""" s = friends_list[page] colour =\ ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) created_at = dt.utcfromtimestamp(s["time"]) created_at = created_at.strftime("%Y-%m-%d %H:%M:%S") post_url = "https://www.hypixel.net" em = discord.Embed(title="Friends", colour=discord.Colour(value=colour), url=post_url) em.add_field(name="Name", value=s["name"]) em.add_field(name="Friend", value=str(s["fname"])) em.add_field(name="Since", value=created_at, inline=False) em.set_thumbnail(url="http://minotar.net/avatar/{}/128.png".format(s["fname"])) if not message: message =\ await self.bot.send_message(ctx.message.channel, embed=em) await self.bot.add_reaction(message, "⬅") await self.bot.add_reaction(message, "❌") await self.bot.add_reaction(message, "➡") else: message = await self.bot.edit_message(message, embed=em) react = await self.bot.wait_for_reaction( message=message, user=ctx.message.author, timeout=timeout, emoji=["➡", "⬅", "❌"] ) if react is None: await self.bot.remove_reaction(message, "⬅", self.bot.user) await self.bot.remove_reaction(message, "❌", self.bot.user) await self.bot.remove_reaction(message, "➡", self.bot.user) return None reacts = {v: k for k, v in numbs.items()} react = reacts[react.reaction.emoji] if react == "next": next_page = 0 if page == len(friends_list) - 1: next_page = 0 # Loop around to the first item else: next_page = page + 1 return await self.friends_menu(ctx, friends_list, message=message, page=next_page, timeout=timeout) elif react == "back": next_page = 0 if page == 0: next_page = len(friends_list) - 1 # Loop around to the last item else: next_page = page - 1 return await self.friends_menu(ctx, friends_list, message=message, page=next_page, timeout=timeout) else: return await\ self.bot.delete_message(message)
async def mute(self, ctx, user: discord.Member, duration: str = None, *, reason: str = None): """Puts a user into timeout for a specified time period, with an optional reason. Time Units ==> s,m,h,d. Example: ~mute @Dumbass#4053 1.1h10m ***Enough bitching Hue dumbass!***""" server = ctx.message.server role = await self.setup_role(server) colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) if role is None: return self.json = dataIO.load_json(self.location) if server.id not in self.json: self.json[server.id] = {} if user.id in self.json[server.id]: msg = 'User was already Muted\nResetting Dat timer :timer: Boii...' elif role in user.roles: msg = 'User was Muted but had no timer, Muting dat bitch now!...' else: msg = '***Bam Muted :speak_no_evil: :pencil2:️:no_entry_sign: BABA BIITCCCH Now stay muted :wave: !!~***.' if not duration: msg += ' \n`Using default duration of` ' + DEFAULT_TIMEOUT duration = _parse_time(DEFAULT_TIMEOUT) timestamp = time.time() + duration elif duration.lower() in ['forever', 'inf', 'infinite']: duration = None timestamp = None else: duration = _parse_time(duration) timestamp = time.time() + duration if server.id not in self.json: self.json[server.id] = {} self.json[server.id][user.id] = { 'until': timestamp, 'by': ctx.message.author.id, 'reason': reason } await self.bot.add_roles(user, role) dataIO.save_json(self.location, self.json) # schedule callback for role removal if duration: self.schedule_unmute(duration, user, reason) em = discord.Embed(description=msg, colour=discord.Colour(value=colour), timestamp=__import__('datetime').datetime.utcnow()) await self.bot.say(embed=em)
async def child(self, ctx, *, user: discord.Member): """Have a children with another user""" server = ctx.message.server a = ctx.message.author if a != user: req = discord.Embed() req.title = "Childs Protocol" req.description = "**{}** has requested to **{}** to have a children!\n{} do you accept?".format( a.name, user.name, user.name) req.set_author(name='{} wants a children!'.format(a.name), icon_url=a.avatar_url) req.set_thumbnail(url=user.avatar_url) await self.bot.say(embed=req) answer = await self.bot.wait_for_message(author=user) answer1 = ('yes') if answer.content.lower().strip() in answer1: success = discord.Embed(colour=0x00ff00) success.title = "Childs Protocol" p = (a.name, user.name) pregnant = randchoice(p) success.description = "{} is now pregnant! Congratulations!".format( pregnant) success.set_author(name='{} has accepted!'.format(user.name), icon_url=user.avatar_url) success.set_thumbnail(url=a.avatar_url) fail = discord.Embed(colour=0xff0000) fail.title = "Childs Protocol" fail.description = "{} is not pregnant! Something went wrong, you may be more lucky next time!".format( pregnant) fail.set_author(name='{} has accepted!'.format(user.name), icon_url=user.avatar_url) fail.set_thumbnail(url=a.avatar_url) rate = (success, fail) child = randchoice(rate) await self.bot.say(embed=child) else: no = discord.Embed(colour=0xff0000) no.title = "Childs Protocol" no.description = "**{}** has rejected **{}**'s proposal to have a children!".format( user.name, a.name) await self.bot.say(embed=no) else: await self.bot.say( 'Dude, have you really tried to f**k yourself?! What the hell...' )
async def get_random(self, server: discord.Server, which): if which == "templates": coll = self.templates.keys() else: coll = self.sources.keys() if server is not None: if server.id in self.servers: coll = list(coll) + list(self.servers[server.id][which].keys()) return randchoice(list(coll))
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.")
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'))
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.")
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()
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))
async def pat(self, ctx, user : discord.Member=None): """ Gives a pat to someone or no one... """ author = ctx.message.author pat = randchoice(self.patgif) if user != None: await self.bot.say("_{} pats {}_ \n".format(author.name, user.mention) + pat) if user.id == self.bot.user.id: await self.bot.say("*purrs*") else: await self.bot.say(pat)
def call(*args, **kwargs): keystruct = tuple(args), tuple(kwargs.items()) key = hash(keystruct) if key in cdict: return cdict[key] newresult = func(*args, **kwargs) if len(cdict)>maxsize: del cdict[randchoice(cdict.keys())] cdict[key] = newresult return newresult
async def _8ball(self, *question): """Ask 8 ball a question Question must end with a question mark. """ question = " ".join(question) if question.endswith("?") and question != "?": return await self.bot.say("`" + randchoice(self.ball) + "`") else: return await self.bot.say("That doesn't look like a question.")
def send_citation(message): global url if get_tl_user(message[1]): # loading and choosing citation f = open('files/citations.db', 'r') tosend = randchoice(f.read().split('\n\n')) f.close() # sending citation tl.sendmsg(url, message[1], tosend)
async def _boule8(self, *question): """Ask 8 ball a question Question must end with a question mark. """ question = " ".join(question) if question.endswith("?") and question != "?": return await self.bot.say("`" + randchoice(self.ball) + "`") else: return await self.bot.say("Ca ressemble pas à une question.")
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))
def fuzz_value(self, fuzzable_integer, fuzz_type=None): """ This method mutates a given integer value, wrapped in a :class:`FuzzableInteger` instance. The input value may not affect the mutation, depending on the fuzz type selected. *fuzz_type* specifies how the integer will be mutated. A value of None indicates that a random fuzz_type should be used for each mutation of the integer. The result is a stringified mutation which may or may not be based on the original integer value. """ if fuzz_type is None: fuzz_type = self.random_fuzz_type() else: self._validate_fuzz_type(fuzz_type) result = copy(fuzzable_integer) if fuzz_type == INTFUZZ_RANDOM: result.value = randint(0, result.maxint) elif fuzz_type == INTFUZZ_INC: result.value += 1 elif fuzz_type == INTFUZZ_DEC: result.value -= 1 elif fuzz_type == INTFUZZ_MAX: result.value = result.maxint elif fuzz_type == INTFUZZ_MIN: result.value = -result.maxint-1 elif fuzz_type == INTFUZZ_ZERO: result.value = 0 elif fuzz_type == INTFUZZ_ONE: result.value = 1 elif fuzz_type == INTFUZZ_FLOAT: result.is_hex = False out = list(str(result)) if len(out) > 1: out.insert(randint(1, len(out)-1), ".") return "".join(out) elif fuzz_type == INTFUZZ_STRING: return StringFuzzer().fuzz_value(str(result)) elif fuzz_type == INTFUZZ_SPECIAL: result.value = self.special elif fuzz_type == INTFUZZ_BOUNDARY: result.value = (2**randint(0, 31)) + randint(-2, 0) elif fuzz_type == INTFUZZ_ALTERNATE: result.value = randchoice((0xAAAAAAAA, 0x55555555, 0xAAAA0000, 0x55550000, 0x0000AAAA, 0x00005555, 0xFFFF0000, 0xFF00FF00, 0x00FF00FF, 0x00FFFF00, 0xF0F0F0F0, 0x0F0F0F0F, 0xFF0000FF, 0xF000000F)) else: assert False, "Unhandled Fuzz Type: %d" % fuzz_type return str(result)
def gen_rand_str(length = 5000): from random import randint, choice as randchoice from string import ascii_letters ents = list(__simplechars_dec) data = [] append = data.append for x in xrange(length): r = randint(0, 10) if r == 0: append('&%s;' % randchoice(ents)) elif r == 1: append('&%d;' % randint(0, 65535)) elif r == 2: append('&%x;' % randint(0, 65535)) if r > 3: append(randchoice(ascii_letters)) return ''.join(data)
def ai_move(self, player): """Capture player piece if possible, otherwise move to a blank if possible, or try another piece.""" shuffle(player.pieces) for p in player.pieces: nbrs = board.neighbour_locs(p) pl = [loc for loc in nbrs if same_side(board[loc].piece, p1)] blanks = [loc for loc in nbrs if board[loc].blank] loc = first(pl) or randchoice(blanks) if blanks else None if loc: p.move(loc) break
async def alot_of_checks(self, message): if message.author.id == self.bot.user.id: return server = message.server #let PMs if server != None: if server.id not in self.settings["SERVERS"]: #default off self.settings["SERVERS"][server.id] = False if not self.settings["SERVERS"][server.id]: return lower = message.content.lower() if ' ' not in lower: return if lower == "what's an alot?": await self.bot.send_message(message.channel, "This is an alot: http://hyperboleandahalf.blogspot.com/2010/04/alot-is-better-than-you-at-everything.html") return lowerm = re.sub(self.alotRegex,"",lower,1) if lowerm == lower: return matchedKeys = re.findall(self.keyRegex,lowerm) matchedTags = [] print(matchedKeys) for k in matchedKeys: vals = self.alotTags[k] for tag in vals: if tag not in matchedTags: matchedTags.append(tag) url = "" if matchedTags == []: url = randchoice(list(self.alots.values())) else: url = self.alots[randchoice(matchedTags)] await self.bot.send_message(message.channel,url)
async def noah(self, ctx, *, question="none"): """Speak with Noah""" author = ctx.message.author msg = "" found = [] for k,v in self.responses.items(): if k in question.lower(): found.append(v) if found: msg = randchoice(randchoice(found)) if not msg: msg = randchoice(self.responses["none"]) await asyncio.sleep(1) await self.bot.say(msg.format(author=author)) if "sing it for me" in question.lower() and "Audio" in self.bot.cogs and author.voice_channel: audio = self.bot.get_cog("Audio") if audio.music_player.is_done(): link = "https://www.youtube.com/watch?v=hchUl3QlJZE" # probably dont need. just too lazy to check. ctx.message.content = "{}play {}".format(self.bot.command_prefix[0],link) if await audio.check_voice(ctx.message.author, ctx.message): audio.queue.append(link)