def command_sum(args): """Send the sum of the arguments to IRC.""" try: irc.send_message(CHAN, "{} = {}".format(" + ".join(args), sum([int(a) for a in args]))) except ValueError: return irc.send_message(CHAN, "")
def announce_winner(irc, channel, blackjack, wager): if blackjack.stalemate: irc.send_message(channel, "Draw!") else: irc.send_message( channel, blackjack.winner.name + " wins!" + " +" + str(wager) + " added to " + blackjack.winner.name + "'s wallet")
def submit_new(conf, cache): ''' Handle processing for a new paste. ''' paste_data = { 'code': bottle.request.POST.get('code', ''), 'name': bottle.request.POST.get('name', '').strip(), 'phone': bottle.request.POST.get('phone', '').strip(), 'private': bottle.request.POST.get('private', '0').strip(), 'syntax': bottle.request.POST.get('syntax', '').strip(), 'forked_from': bottle.request.POST.get('forked_from', '').strip(), 'webform': bottle.request.POST.get('webform', '').strip(), 'origin_addr': bottle.request.environ.get('REMOTE_ADDR', 'undef').strip(), 'recaptcha_answer': bottle.request.POST.get('g-recaptcha-response', '').strip()} cli_post = True if paste_data['webform'] == '' else False # Handle file uploads if type(paste_data['code']) == bottle.FileUpload: paste_data['code'] = '# FileUpload: {}\n{}'.format( paste_data['code'].filename, paste_data['code'].file.getvalue()) # Validate data (valid, err) = sanity.validate_data(conf, paste_data) if not valid: return bottle.jinja2_template('error.html', code=200, message=err) # Check recapcha answer if not cli post if utils.str2bool(conf.get('bottle', 'check_spam')) and not cli_post: if not sanity.check_captcha( conf.get('bottle', 'recaptcha_secret'), paste_data['recaptcha_answer']): return bottle.jinja2_template('error.html', code=200, message='Invalid captcha verification. ERR:677') # Check address against blacklist if sanity.address_blacklisted(cache, paste_data['origin_addr']): return bottle.jinja2_template('error.html', code=200, message='Address blacklisted. ERR:840') # Stick paste into cache paste_id = _write_paste(cache, paste_data) # Set cookie for user bottle.response.set_cookie( 'dat', json.dumps({ 'name': str(paste_data['name']), 'syntax': str(paste_data['syntax']), 'private': str(paste_data['private'])})) # Send user to page, or a link to page if cli_post: scheme = bottle.request.environ.get('REQUEST_SCHEME') host = bottle.request.get_header('host') return '{}://{}/{}\n'.format(scheme, host, paste_id) else: # Relay message to IRC if utils.str2bool(conf.get('bottle', 'relay_enabled')) and not sanity.address_greylisted(cache, paste_data['origin_addr']): irc.send_message(conf, cache, paste_data, paste_id) bottle.redirect('/' + paste_id)
def execute(connection, channel, sender, message, mod): if mod: channel_id = twitch.get_channel_id(config.channel) title = message.replace('!title ', '') print(f'Changing stream title to "{title}"') twitch.set_stream_title(channel_id, title) irc.send_message(connection, channel, f'Set stream title to "{title}"')
def run_bot(state): try: state.network = network.init(state.settings.irc) irc.hello(state.network, state.settings.irc, state.irc) while True: try: message = irc.get_message(state.network, state.settings.irc, state.irc) state.behaviour.nick = state.irc.nick if message: # TODO: Temporary until we know more about how admin # commands are going to work if is_admin(state.settings, message.user): if message.text == 'reconfigure': state.settings = load_settings() old = state.settings msgs = irc.settings_changed(old.irc, state.settings.irc) for msg in msgs: irc.send_message(state.network, msg) if message.text == 'reload': reload_modules() continue if message.text == 'restart': return 'restart' responses = behaviour.handle(message, state.settings, state.behaviour) for response in filter(bool, responses): irc.send_message(state.network, response) except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, ConnectionRefusedError): raise except Exception as e: logger.exception(e) except Exception as e: # Gotta catch 'em all because if we don't catch it by now, fire and # explosions will ensue logger.exception(e) # If anything is thrown and caught here, there's no point in trying to # do anything about it because we've already exited the connection # maintenance loop, so we just wait a bit and try to reconnect again. sleep(30) finally: network.close(state.network) # Clear the IRC connection specific state when the connection as been # killed state.irc = State()
def show_user_stats(irc, channel, user_tracker, username): if user_tracker.is_in_userlist(username) is not True: irc.send_message(channel, "No such user") return user_stats = user_tracker.get_user_stats(username) string = "" string += str(user_stats.name) + ":" string += " Games Won: " + str(user_stats.games_won) string += " Games Lost: " + str(user_stats.games_lost) string += " Games Tied: " + str(user_stats.games_tied) string += " Wallet: " + str(user_stats.wallet) string += " Highscore: " + str(user_stats.highscore) irc.send_message(channel, string)
def display_cards(irc, channel, blackjack): cardlist = "" for card in blackjack.guest_player.cards: cardlist += "[" + card.name + " of " + card.color + "] " irc.send_message( channel, blackjack.guest_player.name + "'s " + "cards - " + cardlist) cardlist = "" if blackjack.winner == None and blackjack.stalemate == False: cardlist += "[" + blackjack.dealer.cards[ 0].name + " of " + blackjack.dealer.cards[0].color + "] " else: for card in blackjack.dealer.cards: cardlist += "[" + card.name + " of " + card.color + "] " irc.send_message(channel, "Dealer's cards - " + cardlist)
def execute(connection, channel, sender, message, mod): character = message.split()[0].lstrip('!') # If "!quote", pick a totally random quote if character == 'quote': quote_list = [quotes.quotes[key] for key in quotes.quotes] quote_list = [ quote for char_quotes in quote_list for quote in char_quotes ] quote = random.choice(quote_list) print('Quoting random character') else: quote = random.choice(quotes.quotes[character]) print(f'Quoting "{character}"') irc.send_message(connection, channel, quote)
def run(self): # Get initial list of follower ids from channel id self.followers = twitch.get_follower_ids(self.channel_id) while True: # Get current list of channel followers current_followers = twitch.get_follower_ids(self.channel_id) # Iterate through current followers for follower in current_followers: # If the current follower wasn't already in the list of followers from before if follower not in self.followers: # Get follower's display name from their id follower_name = twitch.get_username_by_id(follower) print(f'New follower: {follower_name}') # Welcome new follower in chat irc.send_message(self.connection, '#' + config.channel, f'Welcome {follower_name}! <3') # Save current followers to check against self.followers = current_followers time.sleep(5)
def execute(connection, channel, sender, message, mod): if mod: message = message.split() if len(message) >= 3: user = message[1] balance = message[2] games.set_balance(user, balance) irc.send_message(connection, channel, f'Set {user}\'s balance to {balance}') else: irc.send_message( connection, channel, f'{sender}: this command requires additional arguments') else: irc.send_message(connection, channel, f'{sender}: this command is mod only')
def command_test(args): """Send test to IRC.""" irc.send_message(CHAN, "testing some stuff")
def execute(connection, channel, sender, message, mod): irc.send_message(connection, channel, f'Commands: {get_names()}')
def command_derp(args): """Send derp to IRC.""" irc.send_message(CHAN, "derp yourself")
def execute(connection, channel, sender, message, mod): irc.send_message(connection, channel, f'Hi {sender}! <3')
def run(self): # Ask the IRC server for a list of channel mods self.connection.send('CAP REQ :twitch.tv/commands\r\n'.encode()) irc.send_message(self.connection, '#ibunnib', '.mods') data = '' while True: try: # Get new data data = data + self.connection.recv(1024).decode() # Split data to get only new data data_split = re.split(r'[\r\n]+', data) data = data_split.pop() # For each line in the new data for line in data_split: # Split line line = line.split() # If data is of type NOTICE if line[1] == 'NOTICE': msg = irc.get_message(line) # If the notice is the moderator list if 'The moderators of this room are:' in msg: # Store the list of mods print('Reading moderator list...') users = msg.split(':')[1] users = users.split(',') self.mods = [user.lstrip() for user in users] # Add the channel owner to list of mods self.mods.append(config.channel) # Print list of mods mod_names = ' '.join(self.mods) print(f'Moderators: {mod_names}') # If data is a regular chat message if line[1] == 'PRIVMSG': # Get message details sender = irc.get_sender(line) msg = irc.get_message(line) channel = line[2] # Determine if sender is mod in channel mod_status = sender in self.mods # If sender is a moderator if mod_status: print(f'> [M] {sender}: {msg}') else: print(f'> {sender}: {msg}') # Use first word as command cmd = msg.split()[0] # Iterate through each command for command in self.command_list: # If the command's trigger word matches the first word in the message if cmd in command[1]: # Execute the matching command command[0].execute(self.connection, channel, sender, msg, mod_status) except socket.error: print('SOCKET ERROR') except socket.timeout: print('SOCKET TIMEOUT')
def execute(connection, channel, sender, message, mod): # Get credit balance for user balance = games.balance(sender) irc.send_message(connection, channel, f'{sender}\'s balance: {balance}')
def execute(connection, channel, sender, message, mod): messages = games.spin_slots(sender) for message in messages: irc.send_message(connection, channel, message)
if irc.message_queue == []: break for message in irc.message_queue: print(message.suffix) if message.type == "PRIVMSG": if message.suffix.startswith("!play") and blackjack == None: if message.sender in [ banned_user.nick for banned_user in bantracker.banlist ]: irc.send_message(bot_channel, "Cooldown is still in effect") continue parameter = message.get_parameter("!play") if parameter == "": parameter = 0 try: if parameter != "max": wager = int(parameter) except: irc.send_message(bot_channel, "Invalid wager parameter") continue blackjack = Blackjack(Player(message.sender)) init_user_stats(user_tracker, message.sender)
imme.send_computer_name('IRC_TEST',[7,4,4,8]) elif message[0]=='LOGIN_ATTEMPT': if message[1]['pass']==message[1]['user']: imme.allow_login(message[1]['msgid'],[1,2,3,4],message[1]['key']) else: imme.disallow_login(message[1]['msgid'],message[1]['key'],True) elif message[0]=='FRIEND_LIST_REQ': friends=[([4,5,3,6],'IRCtest')] imme.send_friend_list(message[1]['msgid'],message[1]['connection_id'],message[1]['contact_id'],friends) connected=1 connection_id=message[1]['connection_id'] elif message[0]=='LOGGED_IN_FRIENDS_REQ': imme.send_online_list(message[1]['msgid'],message[1]['connection_id'],message[1]['contact_id'],[4,5,3,6]) elif message[0]=='MSG_IN': imme.acknowledge_message(message[1]['msgid'],message[1]['connection_id'],message[1]['contact_id'],message[1]['text_id']) irc.send_message(message[1]['text']) elif message[0]=='MSG_OUT_ACK': print message elif message[0]=='CONVO_END_REQ': mme.end_conversation(message[1]['msgid'],message[1]['connection_id'],message[1]['contact_id'],message[1]['text_id']) elif message[0]=='DISSCONNECT_REQ': imme.close_connection(message[1]['msgid'],message[1]['connection_id'],message[1]['contact_id']) for i in range(len(irc_thread.irc_messages)): if connected==1: irc_message=irc_thread.irc_messages.pop(0) if len(irc_message)<=80: imme.send_message(connection_id,[1,2,3,4],[4,5,3,6],irc_message) else: for i in range(len(irc_message)/80): imme.send_message(connection_id,[1,2,3,4],[4,5,3,6],irc_message)