def format_output(item, show_url=False): """ takes a reddit post and returns a formatted string """ item["title"] = formatting.truncate(item["title"], 70) item["link"] = short_url.format(item["id"]) raw_time = datetime.fromtimestamp(int(item["created_utc"])) item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True) item["comments"] = formatting.pluralize_auto(item["num_comments"], 'comment') item["points"] = formatting.pluralize_auto(item["score"], 'point') if item["over_18"]: item["warning"] = colors.parse(" $(b, red)NSFW$(clear)") else: item["warning"] = "" if show_url: item["url"] = " - " + item["link"] else: item["url"] = "" return colors.parse( "$(b){title} : {subreddit}$(b) - {comments}, {points}" " - $(b){author}$(b) {timesince} ago{url}{warning}").format(**item)
def format_output(item, show_url=False): """ takes a voat post and returns a formatted string """ if not item["Title"]: item["Title"] = formatting.truncate(item["Linkdescription"], 70) else: item["Title"] = formatting.truncate(item["Title"], 70) item["link"] = voat_fill_url.format(item["Subverse"], item["Id"]) raw_time = isodate.parse_date(item['Date']) item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True) item["comments"] = formatting.pluralize_auto(item["CommentCount"], 'comment') item["points"] = formatting.pluralize_auto(item["Likes"], 'point') if item["Type"] == 2: item["warning"] = " \x02Link\x02" else: item["warning"] = "" if show_url: return "\x02{Title} : {Subverse}\x02 - {comments}, {points}" \ " - \x02{Name}\x02 {timesince} ago - {link}{warning}".format(**item) else: return "\x02{Title} : {Subverse}\x02 - {comments}, {points}" \ " - \x02{Name}\x02, {timesince} ago{warning}".format(**item)
def duck_stats(chan, conn, db, message): """- Prints duck statistics for the entire channel and totals for the network.""" ducks = defaultdict(int) scores = db.execute(select([table.c.name, table.c.chan, table.c.shot, table.c.befriend]) .where(table.c.network == conn.name)).fetchall() if scores: ducks["friendchan"] = defaultdict(int) ducks["killchan"] = defaultdict(int) for row in scores: ducks["friendchan"][row["chan"]] += row["befriend"] ducks["killchan"][row["chan"]] += row["shot"] # ducks["chans"] += 1 if row["chan"].lower() == chan.lower(): ducks["chankilled"] += row["shot"] ducks["chanfriends"] += row["befriend"] ducks["killed"] += row["shot"] ducks["friend"] += row["befriend"] ducks["chans"] = int((len(ducks["friendchan"]) + len(ducks["killchan"])) / 2) killerchan, killscore = sorted(ducks["killchan"].items(), key=operator.itemgetter(1), reverse=True)[0] friendchan, friendscore = sorted(ducks["friendchan"].items(), key=operator.itemgetter(1), reverse=True)[0] message( "\x02Duck Stats:\x02 {:,} killed and {:,} befriended in \x02{}\x02. Across {} \x02{:,}\x02 ducks have been killed and \x02{:,}\x02 befriended. \x02Top Channels:\x02 \x02{}\x02 with {} and \x02{}\x02 with {}".format( ducks["chankilled"], ducks["chanfriends"], chan, pluralize_auto(ducks["chans"], "channel"), ducks["killed"], ducks["friend"], killerchan, pluralize_auto(killscore, "kill"), friendchan, pluralize_auto(friendscore, "friend") )) else: return "It looks like there has been no duck activity on this channel or network."
def duck_merge(text, conn, db, message): """<user1> <user2> - Moves the duck scores from one nick to another nick. Accepts two nicks as input the first will have their duck scores removed the second will have the first score added. Warning this cannot be undone.""" oldnick, newnick = text.lower().split() if not oldnick or not newnick: return "Please specify two nicks for this command." oldnickscore = db.execute(select([table.c.name, table.c.chan, table.c.shot, table.c.befriend]) .where(table.c.network == conn.name) .where(table.c.name == oldnick)).fetchall() newnickscore = db.execute(select([table.c.name, table.c.chan, table.c.shot, table.c.befriend]) .where(table.c.network == conn.name) .where(table.c.name == newnick)).fetchall() duckmerge = defaultdict(lambda: defaultdict(int)) duckmerge["TKILLS"] = 0 duckmerge["TFRIENDS"] = 0 channelkey = {"update": [], "insert": []} if oldnickscore: if newnickscore: for row in newnickscore: duckmerge[row["chan"]]["shot"] = row["shot"] duckmerge[row["chan"]]["befriend"] = row["befriend"] for row in oldnickscore: if row["chan"] in duckmerge: duckmerge[row["chan"]]["shot"] = duckmerge[row["chan"]]["shot"] + row["shot"] duckmerge[row["chan"]]["befriend"] = duckmerge[row["chan"]]["befriend"] + row["befriend"] channelkey["update"].append(row["chan"]) duckmerge["TKILLS"] = duckmerge["TKILLS"] + row["shot"] duckmerge["TFRIENDS"] = duckmerge["TFRIENDS"] + row["befriend"] else: duckmerge[row["chan"]]["shot"] = row["shot"] duckmerge[row["chan"]]["befriend"] = row["befriend"] channelkey["insert"].append(row["chan"]) duckmerge["TKILLS"] = duckmerge["TKILLS"] + row["shot"] duckmerge["TFRIENDS"] = duckmerge["TFRIENDS"] + row["befriend"] else: for row in oldnickscore: duckmerge[row["chan"]]["shot"] = row["shot"] duckmerge[row["chan"]]["befriend"] = row["befriend"] channelkey["insert"].append(row["chan"]) # TODO: Call dbupdate() and db_add_entry for the items in duckmerge for channel in channelkey["insert"]: dbadd_entry(newnick, channel, db, conn, duckmerge[channel]["shot"], duckmerge[channel]["befriend"]) for channel in channelkey["update"]: dbupdate(newnick, channel, db, conn, duckmerge[channel]["shot"], duckmerge[channel]["befriend"]) query = table.delete() \ .where(table.c.network == conn.name) \ .where(table.c.name == oldnick) db.execute(query) db.commit() message("Migrated {} and {} from {} to {}".format( pluralize_auto(duckmerge["TKILLS"], "duck kill"), pluralize_auto(duckmerge["TFRIENDS"], "duck friend"), oldnick, newnick )) else: return "There are no duck scores to migrate from {}".format(oldnick)
def get_video_description(video_id): dev_key = bot.config.get_api_key("google_dev_key") request = requests.get(api_url.format(video_id, dev_key)) json = request.json() if json.get('error'): if json['error']['code'] == 403: raise APIError(err_no_api, json) raise APIError("Unknown error", json) data = json['items'] if not data: return None snippet = data[0]['snippet'] statistics = data[0]['statistics'] content_details = data[0]['contentDetails'] out = '\x02{}\x02'.format(snippet['title']) if not content_details.get('duration'): return out length = isodate.parse_duration(content_details['duration']) out += ' - length \x02{}\x02'.format(timeformat.format_time(int(length.total_seconds()), simple=True)) try: total_votes = float(statistics['likeCount']) + float(statistics['dislikeCount']) except (LookupError, ValueError): total_votes = 0 if total_votes != 0: # format likes = pluralize_auto(int(statistics['likeCount']), "like") dislikes = pluralize_auto(int(statistics['dislikeCount']), "dislike") percent = 100 * float(statistics['likeCount']) / total_votes out += ' - {}, {} (\x02{:.1f}\x02%)'.format(likes, dislikes, percent) if 'viewCount' in statistics: views = int(statistics['viewCount']) out += ' - \x02{:,}\x02 view{}'.format(views, "s"[views == 1:]) uploader = snippet['channelTitle'] upload_time = time.strptime(snippet['publishedAt'], "%Y-%m-%dT%H:%M:%S.000Z") out += ' - \x02{}\x02 on \x02{}\x02'.format(uploader, time.strftime("%Y.%m.%d", upload_time)) if 'contentRating' in content_details: out += ' - \x034NSFW\x02' return out
def karma(text, reply): """<reddituser> - will return the information about the specified reddit username""" user = get_user(text) data = get_user_data('about.json', user, reply) data = data['data'] out = "$(b){}$(b) ".format(user) parts = [ "$(b){:,}$(b) link karma and $(b){:,}$(b) comment karma".format( data['link_karma'], data['comment_karma']) ] if data['is_gold']: parts.append("has reddit gold") if data['is_mod']: parts.append("moderates a subreddit") if data['has_verified_email']: parts.append("email has been verified") parts.append("cake day is {}".format( datetime.fromtimestamp(data['created_utc']).strftime('%B %d'))) account_age = datetime.now() - datetime.fromtimestamp(data['created']) age = account_age.days age_unit = "day" if age > 365: age //= 365 age_unit = "year" parts.append("redditor for {}.".format(pluralize_auto(age, age_unit))) return colors.parse(out + ' | '.join(parts))
def cake_day(text, reply): """<reddituser> - will return the cakeday for the given reddit username.""" user = get_user(text) url = user_url + "about.json" r = requests.get(url.format(user), headers=agent) try: r.raise_for_status() except HTTPError as e: reply(statuscheck(e.response.status_code, user)) raise if r.status_code != 200: return statuscheck(r.status_code, user) data = r.json() out = colors.parse("$(b){}'s$(b) ".format(user)) out += "cake day is {}, ".format( datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d')) account_age = datetime.now() - datetime.fromtimestamp( data['data']['created']) age = account_age.days age_unit = "day" if age > 365: age //= 365 age_unit = "year" out += "they have been a redditor for {}.".format( pluralize_auto(age, age_unit)) return out
def format_output(item, show_url=False): """ takes a reddit post and returns a formatted string """ item["title"] = html.unescape(formatting.truncate(item["title"], 200)) item["link"] = short_url.format(item["id"]) # Fix some URLs if not item["is_self"] and item["url"]: # Use .gifv links for imgur if "imgur.com/" in item["url"] and item["url"].endswith(".gif"): item["url"] += "v" # Fix i.reddituploads.com crap ("&" in URL) if "i.reddituploads.com/" in item["url"]: # Get i.redditmedia.com preview (first one is full size) item["url"] = item["preview"]["images"][0]["source"]["url"] # Unescape since reddit gives links for HTML item["url"] = html.unescape(item["url"]) raw_time = datetime.fromtimestamp(int(item["created_utc"])) item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True) item["comments"] = formatting.pluralize_auto(item["num_comments"], 'comment').replace(",", "") item["points"] = formatting.pluralize_auto(item["score"], 'point').replace(",", "") out = [] if show_url and item["link"]: out.append("[h3]{link}[/h3]") out.append("{title}") if not item["is_self"]: out.append("{url}") if item["over_18"]: out.append("$(red)NSFW$(c)") out.extend(["/r/{subreddit}", "/u/{author}", "{timesince} ago", "{points}", "{comments}"]) if item["gilded"]: item["gilded"] = formatting.pluralize_auto(item["gilded"], 'gild') out.append("$(yellow){gilded}$(c)") return "[h1]Reddit:[/h1] " + " [div] ".join(out).format(**item)
def chainallow(text, db, notice_doc, bot): """{add [hook] [{allow|deny}]|del [hook]} - Manage the allowed list fo comands for the chain command""" args = text.split() subcmd = args.pop(0).lower() if not args: return notice_doc() name = args.pop(0) _hook = get_hook_from_command(bot, name) if _hook is None: return "Unable to find command '{}'".format(name) hook_name = format_hook_name(_hook) if subcmd == "add": values = {'hook': hook_name} if args: allow = args.pop(0).lower() if allow == "allow": allow = True elif allow == "deny": allow = False else: return notice_doc() values['allowed'] = allow updated = True res = db.execute(commands.update().values(**values).where( commands.c.hook == hook_name)) if res.rowcount == 0: updated = False db.execute(commands.insert().values(**values)) db.commit() load_cache(db) if updated: return "Updated state of '{}' in chainallow to allowed={}".format( hook_name, allow_cache.get(hook_name)) if allow_cache.get(hook_name): return "Added '{}' as an allowed command".format(hook_name) return "Added '{}' as a denied command".format(hook_name) if subcmd == "del": res = db.execute(commands.delete().where(commands.c.hook == hook_name)) db.commit() load_cache(db) return "Deleted {}.".format(pluralize_auto(res.rowcount, "row")) return notice_doc()
def ducks_user(text, nick, chan, conn, db, message): """<nick> - Prints a users duck stats. If no nick is input it will check the calling username.""" name = nick.lower() if text: name = text.split()[0].lower() ducks = defaultdict(int) scores = db.execute( select([table.c.name, table.c.chan, table.c.shot, table.c.befriend]).where(table.c.network == conn.name).where( table.c.name == name)).fetchall() if text: name = text.split()[0] else: name = nick if scores: has_hunted_in_chan = False for row in scores: if row["chan"].lower() == chan.lower(): has_hunted_in_chan = True ducks["chankilled"] += row["shot"] ducks["chanfriends"] += row["befriend"] ducks["killed"] += row["shot"] ducks["friend"] += row["befriend"] ducks["chans"] += 1 # Check if the user has only participated in the hunt in this channel if ducks["chans"] == 1 and has_hunted_in_chan: message("{} has killed {} and befriended {} in {}.".format( name, pluralize_auto(ducks["chankilled"], "duck"), pluralize_auto(ducks["chanfriends"], "duck"), chan)) return kill_average = int(ducks["killed"] / ducks["chans"]) friend_average = int(ducks["friend"] / ducks["chans"]) message( "\x02{}'s\x02 duck stats: \x02{}\x02 killed and \x02{}\x02 befriended in {}. Across {}: \x02{}\x02 killed and \x02{}\x02 befriended. Averaging \x02{}\x02 and \x02{}\x02 per channel." .format(name, pluralize_auto(ducks["chankilled"], "duck"), pluralize_auto(ducks["chanfriends"], "duck"), chan, pluralize_auto(ducks["chans"], "channel"), pluralize_auto(ducks["killed"], "duck"), pluralize_auto(ducks["friend"], "duck"), pluralize_auto(kill_average, "kill"), pluralize_auto(friend_average, "friend"))) else: return "It appears {} has not participated in the {} hunt.".format( name, get_animal())
def format_output(item, show_url=False): """ takes a reddit post and returns a formatted string """ item["title"] = formatting.truncate(item["title"], 70) item["link"] = short_url.format(item["id"]) raw_time = datetime.fromtimestamp(int(item["created_utc"])) item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True) item["comments"] = formatting.pluralize_auto(item["num_comments"], 'comment') item["points"] = formatting.pluralize_auto(item["score"], 'point') if item["over_18"]: item["warning"] = " \x02NSFW\x02" else: item["warning"] = "" if show_url: return "\x02{title} : {subreddit}\x02 - {comments}, {points}" \ " - \x02{author}\x02 {timesince} ago - {link}{warning}".format(**item) else: return "\x02{title} : {subreddit}\x02 - {comments}, {points}" \ " - \x02{author}\x02, {timesince} ago{warning}".format(**item)
def cake_day(text, reply): """<reddituser> - will return the cakeday for the given reddit username.""" user = get_user(text) data = get_user_data('about.json', user, reply) out = colors.parse("$(b){}'s$(b) ".format(user)) out += "cake day is {}, ".format( datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d')) account_age = datetime.now() - datetime.fromtimestamp( data['data']['created']) age = account_age.days age_unit = "day" if age > 365: age //= 365 age_unit = "year" out += "they have been a redditor for {}.".format( pluralize_auto(age, age_unit)) return out
def karma(text, reply): """<reddituser> - will return the information about the specified reddit username""" user = get_user(text) url = user_url + "about.json" r = requests.get(url.format(user), headers=agent) try: r.raise_for_status() except HTTPError as e: reply(statuscheck(e.response.status_code, user)) raise if r.status_code != 200: return statuscheck(r.status_code, user) data = r.json() data = data['data'] out = "$(b){}$(b) ".format(user) parts = [ "$(b){:,}$(b) link karma and $(b){:,}$(b) comment karma".format( data['link_karma'], data['comment_karma']) ] if data['is_gold']: parts.append("has reddit gold") if data['is_mod']: parts.append("moderates a subreddit") if data['has_verified_email']: parts.append("email has been verified") parts.append("cake day is {}".format( datetime.fromtimestamp(data['created_utc']).strftime('%B %d'))) account_age = datetime.now() - datetime.fromtimestamp(data['created']) age = account_age.days age_unit = "day" if age > 365: age //= 365 age_unit = "year" parts.append("redditor for {}.".format(pluralize_auto(age, age_unit))) return colors.parse(out + ' | '.join(parts))
def format_count(nicks, masks, hosts, addresses, is_admin, duration): counts = [ (len(nicks), 'nick'), (len(masks), 'mask'), ] if is_admin: counts.extend([ (len(hosts), 'host'), (len(addresses), 'address'), ]) if all(count == 0 for count, thing in counts): return "None." else: return "Done. Found {} in {:.3f} seconds".format( get_text_list( [pluralize_auto(count, thing) for count, thing in counts], 'and'), duration)
def attack(event, nick, chan, message, db, conn, notice, attack): global game_status, scripters if chan in opt_out: return network = conn.name status = game_status[network][chan] out = "" if attack == "shoot": miss = [ "WHOOSH! You missed the duck completely!", "Your gun jammed!", "Better luck next time.", "WTF?! Who are you, Kim Jong Un firing missiles? You missed." ] no_duck = "There is no duck! What are you shooting at?" msg = "{} you shot a duck in {:.3f} seconds! You have killed {} in {}." scripter_msg = "You pulled the trigger in {:.3f} seconds, that's mighty fast. Are you sure you aren't a script? Take a 2 hour cool down." attack_type = "shoot" else: miss = [ "The duck didn't want to be friends, maybe next time.", "Well this is awkward, the duck needs to think about it.", "The duck said no, maybe bribe it with some pizza? Ducks love pizza don't they?", "Who knew ducks could be so picky?" ] no_duck = "You tried befriending a non-existent duck. That's freaking creepy." msg = "{} you befriended a duck in {:.3f} seconds! You have made friends with {} in {}." scripter_msg = "You tried friending that duck in {:.3f} seconds, that's mighty fast. Are you sure you aren't a script? Take a 2 hour cool down." attack_type = "friend" if not status['game_on']: return "There is no hunt right now. Use .starthunt to start a game." elif status['duck_status'] != 1: if status['no_duck_kick'] == 1: conn.cmd("KICK", chan, nick, no_duck) return return no_duck else: status['shoot_time'] = time() deploy = status['duck_time'] shoot = status['shoot_time'] if nick.lower() in scripters: if scripters[nick.lower()] > shoot: notice( "You are in a cool down period, you can try again in {:.3f} seconds.".format( scripters[nick.lower()] - shoot ) ) return chance = hit_or_miss(deploy, shoot) if not random.random() <= chance and chance > .05: out = random.choice(miss) + " You can try again in 7 seconds." scripters[nick.lower()] = shoot + 7 return out if chance == .05: out += scripter_msg.format(shoot - deploy) scripters[nick.lower()] = shoot + 7200 if not random.random() <= chance: return random.choice(miss) + " " + out else: message(out) status['duck_status'] = 2 try: args = { attack_type: 1 } score = update_score(nick, chan, db, conn, **args)[attack_type] except Exception: status['duck_status'] = 1 event.reply("An unknown error has occurred.") raise message(msg.format(nick, shoot - deploy, pluralize_auto(score, "duck"), chan)) set_ducktime(chan, conn.name)
def attack(event, nick, chan, message, db, conn, notice, attack): global game_status, scripters if chan in opt_out: return network = conn.name status = game_status[network][chan] animal = get_animal() out = "" if attack == "smoke": pronoun = random.choice([ ('He', 'his'), ('She', 'her'), ('They', 'their'), ('Ze', 'hir'), ]) duck_stories = [ '{} tells you about {} xmonad setup.', '{} talks about IceWM.', '{} talks about evilwm.', '{} discusses gentoo.', '{} reminisces about freshmeat.net, and other stuff before github.', '{} discusses arch linux.', '{} discusses HaikuOS.', '{} discusses OpenBSD.', '{} discusses life, the universe, and everything.', '{} tells you about {} Amiga.', '{} tells you about {} Sun station.', '{} wants to play OpenTTD with you.', '{} draws a picture of Lennart Poettering.', ] story = random.choice(duck_stories).format(pronoun[0], pronoun[1]) smoke_types = [ "smoke a bud", "smoke a bowl", "smoke a joint", "smoke a spliff", "smoke a rollie", "smoke a bowl of kief", "hit the blunt", "eat magic brownies", "do knifers", "dab", "vape", "toke up", "get blazed", ] smoke_type = random.choice(smoke_types) msg = "{} " + "You {} with the {} ".format( smoke_type, animal ) + "for {:.3f} seconds." + " {} You just made a new {} friend. :)".format( story, animal) if random.random() > 0.75: msg = ' '.join([ random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), ]) + '.' no_duck = "No {}s around to {} with, so you {} with rblor.".format( animal, random.choice(WORDS), smoke_type) if random.random() >= 0.5: no_duck = ' '.join([ random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), random.choice(WORDS), ]) + '.' scripter_msg = "You tried smoking with that " + animal + " in {:.3f} seconds!! Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "friend" # TODO: add secret 420 functionality elif attack == "shoot": miss = [ "uhhh. You missed the {} completely! Phew! Be nice to {}s. Try being friends next time." .format(animal, animal), "Your gun jammed! Be nice to {}s. Try being friends next time.". format(animal), "The {} somehow survived your brutal attack. Be nice to {}s. Try being friends next time." .format(animal, animal), "The {} is using Linux and they avoid your attack with a crazy firewall." .format(animal), ] no_duck = random.choice([ "You shoot in the air and scare away all teh {}s.".format(animal), "You shoot in the air and attract some {}s.".format(animal), "Damn, you accidentally shot yourself and turn into a {}!".format( animal), ]) msg = "{} you shot the blood in {:.3f} seconds. Your hands are covered in " + animal + "s! .wash them off, weirdo! You've killed {} in {}." scripter_msg = "You pulled the trigger in {:.3f} seconds, that's really fast. Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "shoot" else: miss = [ "The {} didn't want to be friends, maybe next time.".format( animal), "Well this is awkward, the {} needs to think about it. 🤔".format( animal), "The {} said no, maybe bribe it with some mota? {}s love mota don't they?" .format(animal), ] no_duck = "You tried befriending a non-existent " + animal + ". Some people would say that's creepy. But you're probably just lonely. Look up some funny youtube videos." msg = "{} you made friends a cup of " + animal + " blood and the " + animal + " that it used to belong to in {:.3f} seconds! You've made friends with {} in {}." scripter_msg = "You tried friending that " + animal + " in {:.3f} seconds, that's fast as hell. Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "friend" if not status['game_on']: return None elif status['duck_status'] != 1: if status['no_duck_kick'] == 1: conn.cmd("KICK", chan, nick, no_duck) return return no_duck else: status['shoot_time'] = time() deploy = status['duck_time'] shoot = status['shoot_time'] if nick.lower() in scripters: if scripters[nick.lower()] > shoot: notice( "You are in a cool down period, you can try again in {:.3f} seconds." .format(scripters[nick.lower()] - shoot)) return chance = hit_or_miss(deploy, shoot) if not random.random() <= chance and chance > .05: out = random.choice(miss) + " You can try again in 7 seconds." scripters[nick.lower()] = shoot + 7 return out if chance == .05: out += scripter_msg.format(shoot - deploy) scripters[nick.lower()] = shoot + 7200 if not random.random() <= chance: return random.choice(miss) + " " + out else: message(out) status['duck_status'] = 2 try: args = {attack_type: 1} score = update_score(nick, chan, db, conn, **args)[attack_type] except Exception: status['duck_status'] = 1 event.reply("An unknown error has occurred.") raise message( msg.format(nick, shoot - deploy, pluralize_auto(score, "duck"), chan)) set_ducktime(chan, conn.name)
def attack(event, nick, chan, message, db, conn, notice, attack): global game_status, scripters if chan in opt_out: return network = conn.name status = game_status[network][chan] out = "" if attack == "smoke": pronoun = random.choice([ ('He', 'his'), ('She', 'her'), ]) duck_stories = [ '{} tells you about {} xmonad setup.', '{} talks about IceWM.', '{} discusses gentoo.', '{} discusses arch linux.', '{} discusses HaikuOS.', '{} discusses OpenBSD.', '{} tells you about {} Amiga.', '{} tells you about {} Sun station.', '{} shows you {} laptop and it\'s covered with mustard and ketchup! lol.', ] story = random.choice(duck_stories).format(pronoun[0], pronoun[1]) smoke_types = [ "a bud", "a joint", "a spliff", "a rollie", ] smoke_type = random.choice(smoke_types) pre_msg = "You smoke {} with the duck. {} You just made a new duck friend. :)".format( smoke_type, story) msg = "{} " + pre_msg no_duck = "No ducks around to smoke with, so you smoke {} with rblor.".format( smoke_type) scripter_msg = "You tried smoking with that duck in {:.3f} seconds!! Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "friend" # TODO: add secret 420 functionality elif attack == "shoot": miss = [ "uhhh. You missed the duck completely! Phew! Be nice to ducks. Try being friends next time.", "Your gun jammed! Be nice to ducks. Try being friends next time.", "The duck somehow survived your brutal attack. Be nice to ducks. Try being friends next time.", ] no_duck = "You shoot in the air and scare away all teh ducks." msg = "{} you shot the blood in {:.3f} seconds. Your hands are covered in ducks! .wash them off, weirdo! You've killed {} in {}." scripter_msg = "You pulled the trigger in {:.3f} seconds, that's really fast. Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "shoot" else: miss = [ "The duck didn't want to be friends, maybe next time.", "Well this is awkward, the duck needs to think about it. 🤔", "The duck said no, maybe bribe it with some mota? Ducks love mota don't they?", ] no_duck = "You tried befriending a non-existent duck. Some people would say that's creepy. But you're probably just lonely. Look up some funny youtube videos." msg = "{} you made friends a cup of duck blood and the duck that it used to belong to in {:.3f} seconds! You've made friends with {} in {}." scripter_msg = "You tried friending that duck in {:.3f} seconds, that's fast as hell. Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "friend" if not status['game_on']: return None elif status['duck_status'] != 1: if status['no_duck_kick'] == 1: conn.cmd("KICK", chan, nick, no_duck) return return no_duck else: status['shoot_time'] = time() deploy = status['duck_time'] shoot = status['shoot_time'] if nick.lower() in scripters: if scripters[nick.lower()] > shoot: notice( "You are in a cool down period, you can try again in {:.3f} seconds." .format(scripters[nick.lower()] - shoot)) return chance = hit_or_miss(deploy, shoot) if not random.random() <= chance and chance > .05: out = random.choice(miss) + " You can try again in 7 seconds." scripters[nick.lower()] = shoot + 7 return out if chance == .05: out += scripter_msg.format(shoot - deploy) scripters[nick.lower()] = shoot + 7200 if not random.random() <= chance: return random.choice(miss) + " " + out else: message(out) status['duck_status'] = 2 try: args = {attack_type: 1} score = update_score(nick, chan, db, conn, **args)[attack_type] except Exception: status['duck_status'] = 1 event.reply("An unknown error has occurred.") raise message( msg.format(nick, shoot - deploy, pluralize_auto(score, "duck"), chan)) set_ducktime(chan, conn.name)
def test_auto_pluralize(item, count, output): assert pluralize_auto(count, item) == output
def attack(event, nick, chan, message, db, conn, notice, attack): global game_status, scripters if chan in opt_out: return network = conn.name status = game_status[network][chan] out = "" if attack == "shoot": miss = [ "uhhh. You missed the duck completely!", "Your gun jammed!", "The duck somehow survived your brutal attack. Be nice to ducks. Try being friends next time." ] no_duck = ".bang - k, did i get it?" msg = "{} you shot a duck in {:.3f} seconds! 🍗 You've killed {} in {}." scripter_msg = "You pulled the trigger in {:.3f} seconds, that's really fast. Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "shoot" else: miss = [ "The duck didn't want to be friends, maybe next time.", "Well this is awkward, the duck needs to think about it. 🤔", "The duck said no, maybe bribe it with some mota? Ducks love mota don't they?", ] no_duck = "You tried befriending a non-existent duck. Some people would say that's creepy. But you're probably just lonely. Look up some funny youtube videos." msg = "{} you made friends a duck in {:.3f} seconds! You've made friends with {} in {}." scripter_msg = "You tried friending that duck in {:.3f} seconds, that's fast as hell. Are you sure you aren't a bot? Take a 2 hour cool down." attack_type = "friend" if not status['game_on']: return None elif status['duck_status'] != 1: if status['no_duck_kick'] == 1: conn.cmd("KICK", chan, nick, no_duck) return return no_duck else: status['shoot_time'] = time() deploy = status['duck_time'] shoot = status['shoot_time'] if nick.lower() in scripters: if scripters[nick.lower()] > shoot: notice( "You are in a cool down period, you can try again in {:.3f} seconds.".format( scripters[nick.lower()] - shoot ) ) return chance = hit_or_miss(deploy, shoot) if not random.random() <= chance and chance > .05: out = random.choice(miss) + " You can try again in 7 seconds." scripters[nick.lower()] = shoot + 7 return out if chance == .05: out += scripter_msg.format(shoot - deploy) scripters[nick.lower()] = shoot + 7200 if not random.random() <= chance: return random.choice(miss) + " " + out else: message(out) status['duck_status'] = 2 try: args = { attack_type: 1 } score = update_score(nick, chan, db, conn, **args)[attack_type] except Exception: status['duck_status'] = 1 event.reply("An unknown error has occurred.") raise message(msg.format(nick, shoot - deploy, pluralize_auto(score, "duck"), chan)) set_ducktime(chan, conn.name)