def __use_spider(self, pname, pid): try: # Try to use a rubber spider on them c = CursePlayerRequest(self.__session, pid, 7698) c.doRequest() except Exception as e: # Something went wrong! Maybe they're in HC or ronin self.log("I couldn't use a spider on {} (#{}): {}".format( pname, pid, str(e))) try: self.__send_kmail(pname, pid, "You already have a rubber spider on you, " "so I'm returning this one.", 7698) except Error as e2: self.log("I couldn't return their spider: {}".format(str(e2))) self.__chat_say(pname, pid, "I couldn't use that spider on you and " "something went wrong when I tried to " "return it. Sorry!") else: # Success! Tell them they can expect their spider self.log("I used a spider on {} (#{}).".format(pname, pid)) self.__chat_say(pname, pid, "I used that spider on you.") bookkeeping[id(self)][1] += 1
def __use_arrow(self, pid): try: # Try to use a time's arrow on them c = CursePlayerRequest(self.__session, pid, 4939) c.doRequest() except Exception as e: # Something went wrong! Maybe they're in HC or ronin self.log("I couldn't use an arrow on them: {}".format(str(e))) self.__chat_say(pid, "I couldn't use that arrow on you.") else: # Success! No need to tell them, they'll be notified self.log("I used an arrow on them.") self.actions += 1
def __use_spider(self, pid): try: # Try to use a rubber spider on them c = CursePlayerRequest(self.__session, pid, 7698) c.doRequest() except Exception as e: # Something went wrong! Maybe they're in HC or ronin self.log("I couldn't use a spider on them: {}".format(str(e))) self.__chat_say(pid, "I couldn't use that spider on you.") else: # Success! Tell them they can expect their spider self.log("I used a spider on them.") self.__chat_say(pid, "I used that spider on you.") self.actions += 1
def _doArrow(self, message): arrows = message.items.get(4939, 0) if arrows == 0: return None if arrows >= 2: return (self.newMessage(message.uid, "Please do not send more than one time's arrow.", message.meat) .addItems(message.items)) try: r = CursePlayerRequest(self.session, message.uid, 4939) self.tryRequest(r, numTries=1) return self.newMessage(-1) except kol.Error.Error as e: if e.code == kol.Error.USER_IN_HARDCORE_RONIN: return (self.newMessage(message.uid, "You are in hardcore or ronin.", message.meat) .addItems(message.items)) if e.code == kol.Error.ALREADY_COMPLETED: return (self.newMessage(message.uid, "You have already been arrow'd today.", message.meat) .addItems(message.items)) return (self.newMessage(message.uid, "Unknown error: {}".format(e.msg), message.meat) .addItems(message.items))
def _doMallows(self, message): mallows = message.items.get(3128, 0) if mallows == 0: return None with InventoryLock.lock: self.inventoryManager.refreshInventory() cinv = self.inventoryManager.completeInventory() inv = self.inventoryManager.inventory() gun = cinv.get(5066, 0) if gun == 0: return (self.newMessage(message.uid, "Sorry, I don't have a s'more gun. " "Somebody needs to donate one, or you " "can send one along with your " "marshmallows.", message.meat) .addItems(message.items)) self.inventoryManager.refreshInventory() mallowsBefore = inv.get(3128, 0) print mallowsBefore try: for _ in range(min(mallows, 40)): r = CursePlayerRequest(self.session, message.uid, 5066) self.tryRequest(r, numTries=1) except kol.Error.Error: pass self.inventoryManager.refreshInventory() mallowsAfter = self.inventoryManager.inventory().get(3128, 0) print mallowsAfter mallowsSent = mallowsBefore - mallowsAfter returnItems = message.items if mallowsSent == mallows: del returnItems[3128] else: returnItems[3128] -= mallowsSent returnItems[3128] = min(returnItems[3128], mallowsAfter) print returnItems sendStuffBack = returnItems or message.meat > 0 if not sendStuffBack: return self.newMessage(-1) elif 3128 in returnItems: return self.newMessage(message.uid, "There was an error sending you all " "of your smores (are you in " "Ronin/Hardcore? Did you request too " "many?). You can have your " "marshmallows back.", message.meat).addItems(returnItems) else: return self.newMessage(message.uid, "Enjoy your smores!\n\n(Also, you sent " "me some other stuff. You can have it " "back.)", message.meat).addItems(returnItems)
def __use_wang(self, pname, pid, target): try: c = CursePlayerRequest(self.__session, target, 625) c.doRequest() except Error as e: if e.code == kol.Error.ITEM_NOT_FOUND: self.__chat_say(pname, pid, "I'm sorry, I'm out of wangs.") elif e.code == kol.Error.USER_NOT_FOUND: self.__chat_say(pname, pid, "Your kmail contained a message but it wasn't a valid " "username.") else: self.log("Something went wrong wanging: " + e) else: if target != pname: self.__chat_say(pname, pid, "Successfully wanged {}.".format(target)) else: self.log("Successfully wanged {}.".format(target))
def __use_arrow(self, pname, pid): try: # Try to use a time's arrow on them c = CursePlayerRequest(self.__session, pid, 4939) c.doRequest() except Exception as e: # Something went wrong! Maybe they're in HC or ronin self.log("I couldn't use an arrow on them: {}".format(str(e))) try: self.__send_kmail(pname, pid, "I couldn't use that arrow on you, " "so I'm returning it.", 4939) except Error as e2: self.log("I couldn't return their arrow: {}".format(str(e2))) self.__chat_say(pname, pid, "I couldn't use that arrow on you and " "something went wrong when I tried to " "return it. Sorry!") else: # Success! No need to tell them, they'll be notified self.log("I used an arrow on {} (#{})".format(pname, pid)) bookkeeping[id(self)][1] += 1
def botProcessChat(context, **kwargs): returnCode = FilterManager.CONTINUE bot = kwargs['bot'] chat = kwargs['chat'] if chat['type'] in ['private']: # Initialize variables for response formatting user_name = str(chat['userName']) user_id = str(chat['userId']) current_time = time.time() exprlist = [] exprresults = [] channel = '' clan = alea.clan.Clan(0, '') target_name = '' target_id = '0' uneffectable = alea.util.Uneffectable('') msg = '' try: # Parse the abomination that our chat partner hath wrought request = alea.parser.aleabot_parse(chat['text']) if request[0] == 'rollrequest': # Handle a dice rolling request exprlist = request[1] channel = request[2] # Get the reply text that applies to this kind of roll request diceless = all(expr.classify_dice() == 0 for expr in exprlist) if channel == '': # Private rolling if diceless: msg = aleabot.config.get('rolltext_diceless_private') else: msg = aleabot.config.get('rolltext_private') else: # Public rolling if diceless: msg = aleabot.config.get('rolltext_diceless_public') else: msg = aleabot.config.get('rolltext_public') # Check if channel is allowed, and switch clan if needed if channel != '': if channel in aleabot.config.get('channels').split(): # Allowed public channel (e.g. /games) pass elif channel in aleabot.config.get('clanchannels').split(): # Allowed clan channel (e.g. /clan, /hobopolis, ...) aleabot.clanstate.set_session(bot.session) clan = aleabot.clanstate.player_clan(user_id) Report.info('bot', '%s asked me to roll in clan %s' % (user_name, clan.name())) if clan.id() == 0: Report.warning('bot', 'A player who is not in a clan asked me to roll in ' + channel) raise ClanlessPlayerError('clanless player') elif not aleabot.clanstate.have_whitelist(clan): Report.warning('bot', 'I do not have a whitelist in clan %s' % clan.name()) raise NeedWhitelistError('need whitelist') else: Report.info('bot', 'I have a whitelist in clan %s' % clan.name()) aleabot.clanstate.switch(clan) # Set timer to switch back to home clan aleabot.home_clan_timer = 0 else: raise ChannelDisallowedError(channel) # Apply time-based limits aleabot.rolllimiter.check(channel, user_id, clan.id(), current_time, aleabot.config) # Evaluate dice expressions exprresults = alea.expr.aleabot_eval(exprlist, channel != '', aleabot.rng, aleabot.config) # Update time-based roll limiter aleabot.rolllimiter.update(channel, user_id, clan.id(), current_time, aleabot.config) # Record roll and result in roll verification list state = bot.states['global'] rollverify_key = 'rollverify_' + user_id if rollverify_key not in state: state[rollverify_key] = [] state[rollverify_key].insert(0, ( current_time, [str(x) for x in exprlist], [str(x) for x in exprresults], str(channel), str(clan.name()))) rollverify_count = aleabot.config.get('rollverify_count') state[rollverify_key] = state[rollverify_key][0:rollverify_count] bot.writeState('global') elif request[0] == 'rollverifyrequest': # Handle a roll verification request try: target_name, target_id = resolve_target(bot, user_name, user_id, request[1]) # Get config settings rollverify_count = aleabot.config.get('rollverify_count') rollverify_header = aleabot.config.get('rollverify_header') rollverify_entry_private = aleabot.config.get('rollverify_entry_private') rollverify_entry_public = aleabot.config.get('rollverify_entry_public') rollverify_entry_clan = aleabot.config.get('rollverify_entry_clan') # Get saved list of rolls state = bot.states['global'] rollverify_key = 'rollverify_' + target_id rolls = state.get(rollverify_key, []) rolls = rolls[0:rollverify_count] # Build kmail rollverify_kmail = {} rollverify_kmail['userId'] = user_id rollverify_kmail['text'] = format_reply(rollverify_header, user_name=user_name, user_id=user_id, current_time=current_time, target_name=target_name, target_id=target_id) rollverify_kmail['text'] += '\n\n' for roll in rolls: if roll[4] != '': # clan != '' rollverify_entry = rollverify_entry_clan elif roll[3] != '': # channel != '' rollverify_entry = rollverify_entry_public else: rollverify_entry = rollverify_entry_private rollverify_kmail['text'] += format_reply(rollverify_entry, user_name=user_name, user_id=user_id, current_time=roll[0], target_name=target_name, target_id=target_id, exprlist=roll[1], exprresults=roll[2], channel=roll[3], clan=roll[4]) rollverify_kmail['text'] += '\n' # Try to send the kmail bot.sendKmail(rollverify_kmail) except Error.Error as err: if err.code == Error.USER_NOT_FOUND: msg = aleabot.config.get('error_rollverify_player_not_found') else: msg = aleabot.config.get('error_generic') elif request[0] == 'helprequest': # Handle a help request msg = aleabot.config.get('helptext') elif request[0] == 'hellorequest': # Handle a hello request msg = aleabot.config.get('hellotext') elif request[0] == 'thanksrequest': # Handle a thanks request msg = aleabot.config.get('thankstext') elif request[0] == 'timerequest': # Handle a time request msg = aleabot.config.get('timetext') elif request[0] == 'wangrequest': # Handle a wang request try: target_name, target_id = resolve_target(bot, user_name, user_id, request[1]) # Check limits # Use 'rollover' bot state which is cleared each rollover state = bot.states['rollover'] wang_sender_count_key = 'wang_sender_count_' + user_id wang_sender_count = state.get(wang_sender_count_key, 0) wang_target_count_key = 'wang_target_count_' + target_id wang_target_count = state.get(wang_target_count_key, 0) if target_id == str(bot.session.userId): msg = aleabot.config.get('error_wang_self') elif wang_sender_count >= aleabot.config.get('wang_sender_limit'): msg = aleabot.config.get('error_wang_sender_limit') elif wang_target_count >= aleabot.config.get('wang_target_limit'): msg = aleabot.config.get('error_wang_target_limit') elif target_id != user_id and ('dontwangme_' + target_id) in bot.states['global']: msg = aleabot.config.get('error_wang_notwanted') else: # Limits not reached yet. Slap! Report.info('bot', 'Slapping player with wang: ' + target_name) wangreq = CursePlayerRequest(bot.session, target_id, ITEM_ID_WANG) wangreq.doRequest() if target_id == user_id: msg = aleabot.config.get('wangtext_self') else: msg = aleabot.config.get('wangtext') # Increase limit counters state[wang_sender_count_key] = wang_sender_count + 1 state[wang_target_count_key] = wang_target_count + 1 bot.writeState('rollover') except Error.Error as err: if err.code == Error.ITEM_NOT_FOUND: msg = aleabot.config.get('error_wang_no_wangs') elif err.code == Error.USER_NOT_FOUND: msg = aleabot.config.get('error_wang_player_not_found') else: msg = aleabot.config.get('error_wang_generic') elif request[0] == 'arrowrequest': # Handle an arrow request try: target_name, target_id = resolve_target(bot, user_name, user_id, request[1]) # Check limits # Use 'rollover' bot state which is cleared each rollover state = bot.states['rollover'] arrow_sender_count_key = 'arrow_sender_count_' + user_id arrow_sender_count = state.get(arrow_sender_count_key, 0) if target_id == str(bot.session.userId): msg = aleabot.config.get('error_arrow_self') elif arrow_sender_count >= aleabot.config.get('arrow_sender_limit'): msg = aleabot.config.get('error_arrow_sender_limit') else: # Limits not reached yet. Fire! Report.info('bot', 'Firing arrow at player: ' + target_name) arrowreq = CursePlayerRequest(bot.session, target_id, ITEM_ID_ARROW) arrowreq.doRequest() if target_id == user_id: msg = aleabot.config.get('arrowtext_self') else: msg = aleabot.config.get('arrowtext') # Increase limit counters state[arrow_sender_count_key] = arrow_sender_count + 1 bot.writeState('rollover') except Error.Error as err: if err.code == Error.ITEM_NOT_FOUND: msg = aleabot.config.get('error_arrow_no_arrows') elif err.code == Error.USER_NOT_FOUND: msg = aleabot.config.get('error_arrow_player_not_found') elif err.code == Error.USER_IN_HARDCORE_RONIN: msg = aleabot.config.get('error_arrow_ronin') elif err.code == Error.ALREADY_COMPLETED: msg = aleabot.config.get('error_arrow_already_hit') else: msg = aleabot.config.get('error_arrow_generic') elif request[0] == 'uneffectrequest': # Handle an uneffect request uneffectable = request[1] if uneffectable.inputname() == '': msg = aleabot.config.get('error_uneffect_no_effect_given') elif uneffectable.count() == 0: msg = aleabot.config.get('error_uneffect_no_match') elif uneffectable.count() >= 2: msg = aleabot.config.get('error_uneffect_too_many_matches') else: # Exactly one effect matched effect_id = uneffectable.effect_ids()[0] print str(effect_id) uneffectreq = UneffectRequest(bot.session, effect_id) try: uneffectreq.doRequest() msg = aleabot.config.get('uneffecttext') except Error.Error as err: if err.code == Error.EFFECT_NOT_FOUND: msg = aleabot.config.get('error_uneffect_not_cursed') elif err.code == Error.ITEM_NOT_FOUND: msg = aleabot.config.get('error_uneffect_no_sgeea') else: msg = aleabot.config.get('error_uneffect_generic') elif request[0] == 'dontwangmerequest': # Handle a dontwangme request key = 'dontwangme_' + user_id bot.states['global'][key] = True bot.writeState('global') msg = aleabot.config.get('dontwangmetext') elif request[0] == 'allowwangrequest': # Handle an allowwang request key = 'dontwangme_' + user_id bot.states['global'].pop(key, None) bot.writeState('global') msg = aleabot.config.get('allowwangtext') except GenericAleabotError: msg = aleabot.config.get('error_generic') except ChannelDisallowedError: msg = aleabot.config.get('error_channel_disallowed') except ClanlessPlayerError: msg = aleabot.config.get('error_clanless_player') except NeedWhitelistError: msg = aleabot.config.get('error_need_whitelist') except alea.clan.ClanRequestError: msg = aleabot.config.get('error_clan_request') except alea.rolllimiter.PrivatePerPlayerRollLimitError: msg = aleabot.config.get('error_private_perplayer_limit') except alea.rolllimiter.PublicPerPlayerRollLimitError: msg = aleabot.config.get('error_public_perplayer_limit') except alea.rolllimiter.PublicPerChannelRollLimitError: msg = aleabot.config.get('error_public_perchannel_limit') except alea.expr.ResultCountExceededError: msg = aleabot.config.get('error_too_many_results') except alea.expr.DiceCountExceededError: msg = aleabot.config.get('error_expression_too_many_dice') except alea.expr.DicelessDisallowedError: msg = aleabot.config.get('error_diceless') except alea.expr.D1DisallowedError: msg = aleabot.config.get('error_d1') except alea.expr.AleabotEvalError: msg = aleabot.config.get('error_expression_eval') except alea.parser.AleabotSyntaxError: msg = aleabot.config.get('error_bad_syntax') # If not explicitly chatting to a public channel or a private # conversation, make sure we /msg the user who is talking to us if msg != '' and msg[0] != '/': msg = '/msg %p ' + msg # Format reply message msg = format_reply(msg, user_name=user_name, user_id=user_id, current_time=current_time, exprlist=exprlist, exprresults=exprresults, channel=channel, clan=clan, target_name=target_name, target_id=target_id, uneffectable=uneffectable) # Chat! if msg != '': response = bot.sendChatMessage(msg) response_text = "\n".join(x['text'] for x in response) # Handle chat errors if 'You cannot access that channel' in response_text: Report.warning('bot', 'Received error while chatting: ' + response_text) msg = aleabot.config.get('error_channel_inaccessible') msg = '/msg ' + user_id + ' ' + msg bot.sendChatMessage(msg) returnCode = FilterManager.FINISHED elif chat['type'] in ['notification:kmail']: Report.info('bot', 'Kmail notification received.') # Make sure to check for new kmails next cycle # (see botEndCycle handler) aleabot.kmail_check_timer = aleabot.config.get('time_to_sleep_kmail') elif chat['type'] in ['unknown']: # Handle some chat messages of type 'unknown' # Such as: whitelist changes, clan acceptance / rejection aleabot.clanstate.set_session(bot.session) if aleabot.clanstate.read_unknown_chat_message(chat['text']): Report.info('bot', 'Clan state is no longer valid, need to reload.') return returnCode
def botProcessKmail(context, **kwargs): returnCode = FilterManager.CONTINUE message = kwargs['kmail'] bot = kwargs['bot'] user_name = str(message['userName']) user_id = str(message['userId']) current_time = time.time() cmd = BotUtils.getKmailCommand(message) meat = message['meat'] items = message['items'] # Our response response = '' # Should items and meat be sent back? return_goodies = True # Should a candy heart be sent? send_heart = False # if 1 arrow was sent and the kmail is empty, interpret it as "arrow" if cmd == "" and len(items) == 1 and items[0]['id'] == ITEM_ID_ARROW and items[0]['quantity'] == 1 and meat == 0: cmd = 'arrow' if cmd == 'arrow': # Handle arrow request if len(items) == 1 and items[0]['id'] == ITEM_ID_ARROW and items[0]['quantity'] == 1 and meat == 0: # Everything is okay try: Report.info('bot', 'Firing arrow at player: ' + user_name) arrowreq = CursePlayerRequest(bot.session, user_id, ITEM_ID_ARROW) arrowreq.doRequest() return_goodies = False except Error.Error as err: if err.code == Error.ITEM_NOT_FOUND: response = aleabot.config.get('error_arrow_no_arrows') elif err.code == Error.USER_NOT_FOUND: response = aleabot.config.get('error_arrow_player_not_found') elif err.code == Error.USER_IN_HARDCORE_RONIN: response = aleabot.config.get('error_arrow_ronin') elif err.code == Error.ALREADY_COMPLETED: response = aleabot.config.get('error_arrow_already_hit') else: response = aleabot.config.get('error_arrow_generic') elif len(items) == 0 and meat == 0: Report.warning('bot', 'Arrow request without arrow from ' + user_name) response = aleabot.config.get('kmailtext_arrow_notattached') else: Report.warning('bot', 'Arrow request with extra items or meat from ' + user_name) response = aleabot.config.get('kmailtext_arrow_extraattached') elif cmd == 'donate' or cmd == 'donation': # Handle donation if len(items) == 0 and meat == 0: # Empty donation kmail? Report.warning('bot', 'Empty donation received from ' + user_name) response = aleabot.config.get('kmailtext_donate_empty') else: Report.info('bot', 'Donation received from ' + user_name) response = aleabot.config.get('kmailtext_donate_thanks') return_goodies = False send_heart = True else: # Handle unknown command Report.warning('bot', 'Unknown kmail command: ' + cmd) response = aleabot.config.get('kmailtext_unknown') # Send our response if response != '' or (return_goodies and (len(items) != 0 or meat != 0)): Report.info('bot', 'Responding to kmail') response_kmail = {} response_kmail['userId'] = message['userId'] response_kmail['text'] = format_reply(response + '\n\n' + aleabot.config.get('kmailtext_quote'), user_name=user_name, user_id=user_id, current_time=current_time) + '\n' + quote_kmail(message) if return_goodies: response_kmail['items'] = items response_kmail['meat'] = meat try: bot.sendKmail(response_kmail) except Error.Error as err: if err.code == Error.USER_IN_HARDCORE_RONIN: Report.error('bot', 'Tried to send items and meat back, but user is in Hardcore or Ronin!') response_kmail2 = {} response_kmail2['userId'] = message['userId'] response_kmail2['text'] = format_reply(response + '\n\n' + aleabot.config.get('kmailtext_quote_ronin'), user_name=user_name, user_id=user_id, curent_time=current_time) + '\n' + quote_kmail(message) try: bot.sendKmail(response_kmail2) except Error.Error as err2: Report.error('bot', 'Unexpected error while sending response_kmail2: ' + str(err2)) else: Report.error('bot', 'Unexpected error while sending response_kmail: ' + str(err)) # Send a candy heart if send_heart: try: Report.info('bot', 'Sending candy heart to player: ' + user_name) heartreq = CursePlayerRequest(bot.session, user_id, ITEM_ID_CANDYHEART) heartreq.requestData['texta'] = 'THANK' heartreq.requestData['textb'] = 'YOU' heartreq.doRequest() except Error.Error as err: Report.error('bot', 'Couldn\'t send candy heart: ' + str(err)) returnCode = FilterManager.FINISHED return returnCode
def process(s, c, counter): chats = None try: chats = c.getNewChatMessages() except: chats = c.getNewChatMessages() for chat in chats: # handle PMs if chat["type"] == "private" and chat['userId'] not in Data.playerBlacklist: incrementCounter(chat, counter) u = UserProfileRequest(s, chat["userId"]) # allow use in RU only if u.doRequest()["clanName"] == "Reddit United": if re.match(Data.wang, chat['text']): player = db.GqlQuery("SELECT * FROM Player WHERE userName='******'" % chat['userName'].lower()).get() if player is None: player = Player(userName=chat['userName'].lower(), gotPackage=False, wangsUsed=0, arrowUsed=False) if player.wangsUsed < Data.WANG_LIMIT: logging.debug("hitting %s with a wang" % chat['userName']) wang = CursePlayerRequest(s, chat["userId"], 625) try: wang.doRequest() player.wangsUsed += 1 player.put() c.sendChatMessage("/msg %s You have been slapped with a wang." % chat["userId"]) except: c.sendChatMessage("/msg %s An error occurred. Please try again later." % chat["userId"]) else: logging.warn("%s has hit limit for wang" % chat['userName']) c.sendChatMessage("/msg %s You have used all 5 wangs for the day." % chat['userId']) elif re.match(Data.rigRoll, chat['text']): if chat['userId'] == 2434890: if re.match(Data.rigRoll, chat['text']).group(5) != "k" and re.match(Data.rigRoll, chat['text']).group(5) != "m": logging.debug("Rolling normally RIGGED") c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % (str(re.match(Data.rigRoll, chat['text']).group(1)), chat["userName"], re.match(Data.rigRoll, chat['text']).group(8))) elif re.match(Data.rigRoll, chat['text']).group(5) == "k" or re.match(Data.rigRoll, chat['text']).group(5) == "K": logging.debug("Rolling x1000 RIGGED") c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % ((str(re.match(Data.rigRoll, chat['text']).group(1)) + str(re.match(Data.rigRoll, chat['text']).group(5))), chat["userName"], re.match(Data.rigRoll, chat['text']).group(8))) elif re.match(Data.rigRoll, chat['text']).group(5) == "m" or re.match(Data.rigRoll, chat['text']).group(5) == "M": logging.debug("Rolling x1m RIGGED") c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % ((str(re.match(Data.rigRoll, chat['text']).group(1)) + str(re.match(Data.rigRoll, chat['text']).group(5))), chat["userName"], re.match(Data.rigRoll, chat['text']).group(8))) elif re.match(Data.diceRoll, chat['text']): logging.debug(re.match(Data.diceRoll, chat['text']).group(5)) # TODO: take out this part after raffles. if chat['userId'] in [2413861, 1481327] and re.match(Data.diceRoll, chat['text']).group(1) == 10: if db.GqlQuery("SELECT * FROM Player WHERE userName='******'").get().baleeted is False: c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % (str(re.match(Data.diceRoll, chat['text']).group(1)), chat["userName"], 4)) player = db.GqlQuery("SELECT * FROM Player WHERE userName='******'").get() player.baleeted = True player.put() else: c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % (str(re.match(Data.diceRoll, chat['text']).group(1)), chat["userName"], random.randint(1, int(re.match(Data.diceRoll, chat['text']).group(1))))) # roll! group 2 = #, group 5 = k or m, group 7 = channel elif re.match(Data.diceRoll, chat['text']).group(5) != "k" and re.match(Data.diceRoll, chat['text']).group(5) != "m": logging.debug("Rolling normally") c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % (str(re.match(Data.diceRoll, chat['text']).group(1)), chat["userName"], random.randint(1, int(re.match(Data.diceRoll, chat['text']).group(1))))) elif re.match(Data.diceRoll, chat['text']).group(5) == "k" or re.match(Data.diceRoll, chat['text']).group(5) == "K": logging.debug("Rolling x1000") c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % ((str(re.match(Data.diceRoll, chat['text']).group(1)) + str(re.match(Data.diceRoll, chat['text']).group(5))), chat["userName"], random.randint(1, int(re.match(Data.diceRoll, chat['text']).group(1)) * 1000))) elif re.match(Data.diceRoll, chat['text']).group(5) == "m" or re.match(Data.diceRoll, chat['text']).group(5) == "M": logging.debug("Rolling x1m") c.sendChatMessage("/clan Rolling 1D%s for %s gives %s" % ((str(re.match(Data.diceRoll, chat['text']).group(1)) + str(re.match(Data.diceRoll, chat['text']).group(5))), chat["userName"], random.randint(1, int(re.match(Data.diceRoll, chat['text']).group(1)) * 1000000))) elif re.match(Data.wangOther, chat['text']): logging.debug("slapping %s with a wang. request by %s" % (re.match(Data.wangOther, chat['text']).group(2), chat['userName'])) player = db.GqlQuery("SELECT * FROM Player WHERE userName='******'" % chat['userName'].lower()).get() if player is None: player = Player(userName=chat['userName'].lower(), gotPackage=False, wangsUsed=0, arrowUsed=False) if player.wangsUsed < Data.WANG_LIMIT: wang = CursePlayerRequest(s, re.match(Data.wangOther, chat['text']).group(2), 625) try: wang.doRequest() player.wangsUsed += 1 player.put() c.sendChatMessage("/msg %s %s has been slapped with a wang." % (chat["userId"], re.match(Data.wangOther, chat['text']).group(2))) except: c.sendChatMessage("/msg %s An error occurred. Please try again later." % chat["userId"]) else: logging.warn("%s has hit limit for wang" % chat['userName']) c.sendChatMessage("/msg %s You have used all 5 wangs for the day." % chat['userId']) # elif re.match(Data.loveMe, chat['text']): # logging.debug("sending love back at %s" % chat['userName']) # c.sendChatMessage("/msg %s Awww... I love you back!" % chat["userId"]) elif re.match(Data.arrow, chat['text']): if chat['userId'] not in [1589628]: logging.debug("hitting %s with a time's arrow" % chat['userId']) player = db.GqlQuery("SELECT * FROM Player WHERE userName = '******'" % chat['userName'].lower()).get() if player is None: player = Player(userName=chat['userName'].lower(), gotPackage=False, wangsUsed=0, arrowsUsed=False) if not player.arrowsUsed: arrow = CursePlayerRequest(s, chat["userId"], 4939) try: arrow.doRequest() player.arrowsUsed = True player.put() c.sendChatMessage("/msg %s Hitting you with a time's arrow, straight to the knee." % chat["userId"]) except: logging.error("Out of arrows/error!") c.sendChatMessage("/msg %s Oops, looks like I'm out of arrows :'( (Or you're in Ronin/HC, or you've been hit already by someone else)" % chat["userId"]) else: logging.warn("%s hit limit for time's arrow" % chat['userName']) c.sendChatMessage("/msg %s You have used your arrow for the day." % chat['userId']) else: logging.warn("%s is blacklisted from arrows" % chat['userName']) c.sendChatMessage("/msg %s You have been blacklisted from using time's arrows." % chat['userId']) elif re.match(Data.arrowOther, chat['text']): if chat['userId'] not in [1589628]: player = db.GqlQuery("SELECT * FROM Player WHERE userName = '******'" % chat['userName'].lower()).get() if player is None: player = Player(userName=chat['userName'].lower(), gotPackage=False, wangsUsed=0, arrowsUsed=False) if not player.arrowsUsed: logging.debug("hitting %s with a time's arrow. request by %s" % (re.match(Data.arrowOther, chat['text']).group(2), chat['userName'])) arrow = CursePlayerRequest(s, re.match(Data.arrowOther, chat['text']).group(2), 4939) try: arrow.doRequest() player.arrowsUsed = True player.put() c.sendChatMessage("/msg %s %s has been hit with an arrow." % (chat["userId"], re.match(Data.arrowOther, chat['text']).group(2))) except: c.sendChatMessage("/msg %s An error occurred. Please try again later." % chat["userId"]) else: logging.warn("%s hit limit for time's arrow" % chat['userName']) c.sendChatMessage("/msg %s You have used your arrow for the day." % chat['userId']) else: logging.warn("%s is blacklisted from arrows" % chat['userName']) c.sendChatMessage("/msg %s You have been blacklisted from using time's arrows." % chat['userId']) elif re.match(Data.upgradeStatus, chat['text']): c.sendChatMessage("/msg %s Rank upgrades have been moved to RedditRankBot. Please PM him instead." % chat['userId']) # # TODO: rewrite to use FindWhitelistRequest in order to not accidentally demote a player # e = EditPlayerRankRequest(s, chat['userId'], 6) # if e.doRequest()["success"]: # logging.debug("Promoted %s to a Lurker" % chat['userName']) # AddClannieToClanWhitelistRequest(s, chat['userId']).doRequest() # c.sendChatMessage("/msg %s You have been promoted to Lurker." % chat["userId"]) # c.sendChatMessage("/clan %s (#%s) has been promoted to a Lurker." % (chat["userName"], chat["userId"])) # else: # c.sendChatMessage("/msg %s Sorry, I've failed to automatically promote you. Please see a mod." % chat['userId']) elif re.match(Data.sendCarePackage, chat['text']): if chat['userId'] in Data.karmanautPlus: logging.info("Attempting to send care package to %s request by %s" % (re.match(Data.sendCarePackage, chat['text']).group(1), chat['userName'])) newbieName = re.match(Data.sendCarePackage, chat['text']).group(1) if newbieName.isdigit(): newbieName = UserProfileRequest(s, re.match(Data.sendCarePackage, chat['text']).group(1)).doRequest()["userName"] playerSearch = db.GqlQuery("SELECT * FROM Player WHERE userName = '******'" % newbieName.lower()).get() msgBody = { "userId": re.match(Data.sendCarePackage, chat['text']).group(1), "text": "Welcome to KoL and Reddit United! Here's some stuff to help you out.\n\nThis newbie package was requested by %s for you" % chat["userName"], "items": [{"id": 143, "quantity": 1}, {"id": 591, "quantity": 1}, {"id": 1450, "quantity": 1}, {"id": 196, "quantity": 3}, {"id": 2402, "quantity": 10}, {"id": 7071, "quantity": 10}, {"id": 7072, "quantity": 10}], "meat": 1000 } if playerSearch is None: # send a package, update the datastore c.sendChatMessage("/w %s Sending a care package..." % chat["userId"]) try: SendMessageRequest(s, msgBody).doRequest() Player(userName=newbieName.lower(), gotPackage=True, wangsUsed=0, arrowsUsed=False).put() c.sendChatMessage("/w %s %s has been sent a care package." % (chat['userId'], newbieName)) except: c.sendChatMessage("/w %s Failed to send. Username may be too long and KoL chat made a space between it. Please send one manually. (This is a general fail message, this could also mean one ingredient of the package is missing)" % chat['userName']) else: if playerSearch.gotPackage is False: c.sendChatMessage("/w %s Sending a care package..." % chat["userId"]) try: SendMessageRequest(s, msgBody).doRequest() playerSearch.gotPackage = True playerSearch.put() c.sendChatMessage("/w %s %s has been sent a care package." % (chat['userId'], newbieName)) logging.info("%s has been sent a care package" % newbieName) except: c.sendChatMessage("/w %s Failed to send. Username may be too long and KoL chat made a space between it. Please send one manually" % chat['userName']) logging.error("Failed to send package to %s" % newbieName) else: logging.warn("Failed to send package to %s, player has been sent one already" % newbieName) c.sendChatMessage("/w %s %s has already been sent a care package" % (chat['userId'], newbieName)) else: logging.warn("Unauthorized attempt to send care package by %s" % chat["userName"]) c.sendChatMessage("/w %s You are not authorized to send care packages. This incident will be reported." % chat['userId']) else: # No matching command was found, inform the player incrementCounter(chat, counter) c.sendChatMessage("/msg %s Oops, I didn't recognize what you wanted. Try again, or type !help in clan chat to receive a list of commands to use." % chat["userId"]) else: # If FaxBot, then acknowledge the fax completion. if chat["userId"] == 2194132: if " has copied a" in chat['text']: logging.debug("A %s has been copied in." % re.match(Data.parseFax, chat['text']).group(1)) c.sendChatMessage("Your fax request has been completed. A %s has been copied in." % re.match(Data.parseFax, chat['text']).group(1)) elif "I do not understand your request." in chat['text'] or "just delivered a fax to your clan" in chat['text']: c.sendChatMessage("/clan There was a problem in faxing. Please try again.") else: # handle of other players c.sendChatMessage("/msg %s Sorry, you must be in the clan \"Reddit United\" to use this bot." % chat['userId']) else: if "channel" in chat and chat["channel"] == "clan" and chat["userId"] not in Data.playerBlacklist: if re.match(Data.fax, chat['text']): incrementCounter(chat, counter) c.sendChatMessage("/clan Faxing a %s..." % re.match(Data.fax, chat['text']).group(1)) logging.debug("faxing a %s. requested by %s" % (re.match(Data.fax, chat['text']).group(1), chat['userName'])) c.sendChatMessage("/w FaxBot %s" % re.match(Data.fax, chat['text']).group(1)) # elif re.match(Data.clanMemberBack, chat['text']): # incrementCounter(chat, counter) # logging.debug("w/b to %s" % chat['userName']) # c.sendChatMessage("/clan Welcome back, %s!" % chat["userName"]) # elif re.match(Data.clanMemberHi, chat['text']): # incrementCounter(chat, counter) # logging.debug("hello to %s" % chat['userName']) # c.sendChatMessage("/clan Hello, %s!" % chat["userName"]) # elif re.match(Data.clanMemberLeave, chat['text']): # incrementCounter(chat, counter) # logging.debug("goodbye to %s" % chat['userName']) # c.sendChatMessage("/clan Goodbye, %s!" % chat["userName"]) elif re.match(Data.snack, chat['text']): incrementCounter(chat, counter) logging.debug("munching on a snack from %s" % chat['userName']) c.sendChatMessage("/clan /me munches on the snack happily") elif re.match(Data.smack, chat['text']): incrementCounter(chat, counter) logging.debug("smacked by %s" % chat['userName']) c.sendChatMessage("/clan /me smacks %s back twice as hard" % chat['userName']) elif re.match(Data.ignoreMe, chat['text']): logging.debug("ignoring %s by own request" % chat['userName']) c.sendChatMessage("/clan You have been ignored by RedditBot. Note that this has permanently locked you out of all of RedditBot's features.") c.sendChatMessage("/baleet %s" % chat['userId']) player = db.GqlQuery("SELECT * FROM Player WHERE userName='******'" % chat['userName']).get() if player is None: Player(userName=chat['userName'].lower(), gotPackage=False, baleeted=True, wangsUsed=0, arrowsUsed=False).put() else: player.baleeted = True player.put() elif re.match(Data.executeCommand, chat['text']): # perm type: SU only if chat['userId'] in Data.superUser: logging.info("execute %s" % re.match(Data.executeCommand, chat['text']).group(1)) c.sendChatMessage(re.match(Data.executeCommand, chat['text']).group(1)) else: logging.warn("unauthorized executeCommand by %s" % chat['userName']) c.sendChatMessage("/clan You are not authorized to use that command.") elif re.match(Data.setRank, chat['text']): # perm type: mod+ if chat['userId'] in Data.modPlus: logging.info("setting rank for %s to %s" % (re.match(Data.setRank, chat['text']).group(1), re.match(Data.setRank, chat['text']).group(2))) resp = {} if re.match(Data.setRank, chat['text']).group(2).isdigit(): resp = EditPlayerRankRequest(s, re.match(Data.setRank, chat['text']).group(1), re.match(Data.setRank, chat['text']).group(2)).doRequest() else: resp = EditPlayerRankRequest(s, re.match(Data.setRank, chat['text']).group(1), EditPlayerRankRequest.ranks[re.match(Data.setRank, chat['text']).group(2).lower()]).doRequest() if resp['success']: c.sendChatMessage("/clan Rank has been set.") else: c.sendChatMessage("/clan Failed to set rank.") else: logging.warn("unauthorized setRank by %s" % chat['userName']) c.sendChatMessage("/clan You are not authorized to use that command.") elif re.match(Data.optimal, chat['text']): incrementCounter(chat, counter) logging.debug("acknowledge optimal by %s" % chat['userName']) if chat['userName'].lower() not in ["kevzho", "basbryan", "sweeepss", "hikaru yami"]: c.sendChatMessage("/clan No, %s, you are not optimal enough for Kev" % chat['userName']) else: c.sendChatMessage("/clan Yes, %s, you are optimal." % chat["userName"]) # elif re.match(Data.sharknado, chat['text']): # incrementCounter(chat, counter) # c.sendChatMessage("/clan Sharknado was a horrible movie. Just... no.") elif re.match(Data.helpMe, chat['text']): incrementCounter(chat, counter) msg = SendMessageRequest(s, {"userId": chat["userId"], "text": Data.helpText}) msg.doRequest() # elif re.match(Data.kill, chat['text']): # incrementCounter(chat, counter) # if re.match(Data.kill, chat['text']).group(1).lower() not in ["kevzho", "redditbot", "jick"]: # c.sendChatMessage("/clan Commencing the killing of %s" % re.match(Data.kill, chat['text']).group(1)) # else: # c.sendChatMessage("/clan I cannot kill that player.") # elif re.match(Data.iq, chat['text']): # incrementCounter(chat, counter) # if chat['username'].lower() != "kevzho": # c.sendChatMessage("/clan My IQ is higher than yours, %s" % chat['userName']) # else: # c.sendChatMessage("/clan How can I be smarter than my creator? Don't be silly, %s" % chat["userName"]) elif re.match(Data.setFlag, chat['text']): # perm type: SU only if chat['userId'] in Data.superUser: c.sendChatMessage("/clan Setting '%s' flag for %s to %s" % (re.match(Data.setFlag, chat['text']).group(1), re.match(Data.setFlag, chat['text']).group(2), re.match(Data.setFlag, chat['text']).group(3))) logging.info("Setting '%s' flag for %s to %s" % (re.match(Data.setFlag, chat['text']).group(1), re.match(Data.setFlag, chat['text']).group(2), re.match(Data.setFlag, chat['text']).group(3))) playerFlag = db.GqlQuery("SELECT * FROM Player WHERE userName='******'" % re.match(Data.setFlag, chat['text']).group(1)).get() if re.match(Data.setFlag, chat['text']).group(3) in ["False", "True"]: if re.match(Data.setFlag, chat['text']).group(3) == "False": setattr(playerFlag, re.match(Data.setFlag, chat['text']).group(2), False) playerFlag.put() c.sendChatMessage("/clan Flag set.") else: setattr(playerFlag, re.match(Data.setFlag, chat['text']).group(2), True) playerFlag.put() c.sendChatMessage("/clan Flag set.") elif re.match(Data.setFlag, chat['text']).group(3).isdigit(): setattr(playerFlag, re.match(Data.setFlag, chat['text']).group(2), int(re.match(Data.setFlag, chat['text']).group(3))) playerFlag.put() c.sendChatMessage("/clan Flag set.") else: setattr(playerFlag, re.match(Data.setFlag, chat['text']).group(2), re.match(Data.setFlag, chat['text']).group(3)) playerFlag.put() c.sendChatMessage("/clan Flag set.") else: c.sendChatMessage("/clan Unauthorized attempt to setFlag") logging.warn("%s attempted to setFlag" % chat["userName"]) elif re.match(Data.getFlag, chat['text']): # perm type: SU only/admin? if chat['userId'] in Data.adminPlus: logging.info("Getting %s flag of %s" % (re.match(Data.getFlag, chat['text']).group(1), re.match(Data.getFlag, chat['text']).group(2))) playerGql = db.GqlQuery("SELECT * FROM Player WHERE userName='******'" % re.match(Data.getFlag, chat['text']).group(1)).get() if playerGql: c.sendChatMessage("/clan Flag %s for %s gives: %s" % (re.match(Data.getFlag, chat['text']).group(2), re.match(Data.getFlag, chat['text']).group(1), getattr(playerGql, re.match(Data.getFlag, chat['text']).group(2)))) else: c.sendChatMessage("/clan Player not found!") else: c.sendChatMessage("/clan Unauthorized attempt to getFlag") logging.warn("%s attempted to getFlag" % chat["userName"]) elif re.match(Data.whitelist, chat['text']): if chat['userId'] in Data.karmanautPlus: logging.info("adding %s to whitelist requested by %s" % (re.match(Data.whitelist, chat['text']).group(1), chat['userName'])) AddClannieToClanWhitelistRequest(s, re.match(Data.whitelist, chat['text']).group(1)).doRequest() c.sendChatMessage("/clan Player added to whitelist.") else: c.sendChatMessage("/clan Unauthorized attempt to whitelist.") logging.warn("%s attempted to whitelist" % chat['userName']) elif re.match(Data.points, chat['text']): # logging.info("Clan points by %s" % chat['userName']) # c.sendChatMessage("/clan %s has %s clan points" % (re.match(Data.points, chat['text']).group(1), random.randint(0, 9000))) c.sendChatMessage("/clan Clan points are currently unavailable.") # elif re.match(Data.trigger, chat['text']): # incrementCounter(chat, counter) # c.sendChatMessage("/clan Do you really expect that to be a trigger?") elif re.match("^!version", chat['text']): incrementCounter(chat, counter) c.sendChatMessage("Version %s" % Data.version) elif re.match("^!([^ ]+)(.*)?$", chat['text']): incrementCounter(chat, counter) if re.match("^!([^ ]+)(.*)?$", chat['text']).group(1).lower() in Data.customTriggers: c.sendChatMessage(Data.customTriggers[re.match("^!([^ ]+)(.*)?$", chat['text']).group(1).lower()]) else: c.sendChatMessage("/clan %s" % random.choice(Data.noTriggers).format(chat['userName'], re.match("^!([^ ]+)(.*)?$", chat['text']).group(1), ordinal(random.randint(1, 100)))) if len(chat['text']) < (200 - len(chat['userName']) - 2): c.sendChatMessage("/talkie %s: %s" % (chat['userName'], chat["text"])) else: # break it up here, stopped the bug for now by just not sending messages if they are longer than 200 chars. a more long term solution would require changes to the pykol api itself. pass if "channel" in chat and chat["channel"] == "talkie" and chat["userId"] not in Data.playerBlacklist: c.sendChatMessage("/clan %s: %s" % (chat['userName'], chat["text"]))