Twitch bot !create and !remove command functions - Code execution skipping issue

I’m working on a Twitch chat bot and having trouble with !create and !remove command functionality. The weird thing is that nearly identical code works for one command but not the other. When I add debug prints and breakpoints, it seems like the program just skips over certain lines completely.

The problematic line that gets skipped is:

if protectedcommands.has_key(cmdtoremove):
    transmitMessage(socket, chatroom, username + " you cannot remove a protected command " + '"!' + cmdtoremove + '" !!!')
    break

Here’s my complete bot code:

import string
import json
from Connection import createSocket, transmitMessage
from Setup import enterChannel
from Parser import extractUser, extractMessage, extractChannel, first_word, remaining_words

socket = createSocket()
enterChannel(socket)
buffer = ""
socket.send("CAP REQ :twitch.tv/membership\r\n")
socket.send("CAP REQ :twitch.tv/commands\r\n")

try:
    with file("botcommands.json","r") as cmdfile:
        botcommands = json.load(cmdfile)
except IOError:
    botcommands = {}
    with file("botcommands.json","w") as cmdfile:
        json.dump(botcommands, cmdfile)

protectedcommands = {"create": True, "remove": True, "ban": True}

while True:
    buffer = buffer + socket.recv(1024)
    lines = string.split(buffer, "\n")
    buffer = lines.pop()

    for currentline in lines:
        print (currentline)
        
        if currentline.startswith('PING'):
            socket.send('PONG ' + currentline.split( ) [ 1 ] + '\r\n')
            print "PONG SENT"
            break
            
        username = extractUser(currentline)
        message = extractMessage(currentline)
        chatroom = extractChannel(currentline)
        if chatroom == None or username == None or message == None:
            break
            
        space = " "
        empty = ""
        print chatroom + ": " + username + " > " + message

        if message.startswith("!create "):
            if message.count(space) >= 2:
                try:
                    newcmd = first_word(message)
                    response = remaining_words(message)
                except IndexError:
                    transmitMessage(socket, chatroom, username + " usage: !create !<cmd_name> <cmd_response>")
                    break
                if protectedcommands.has_key(newcmd):
                    transmitMessage(socket, chatroom, username + " you cannot create a command named " + '"!' + newcmd + '" !!!')
                    break
                try:
                    botcommands[newcmd]
                except KeyError:
                    botcommands[newcmd] = response
                    transmitMessage(socket, chatroom, username + " command !" + newcmd + " created successfully!!!")
                    with file("botcommands.json","w") as cmdfile:
                        json.dump(botcommands, cmdfile)
                    break
                transmitMessage(socket, chatroom, username + " that command already exists!!!")
                break
            transmitMessage(socket, chatroom, username + " usage: !create !<cmd_name> <cmd_response>")
            break

        if message.startswith("!remove "):
            if message.count(space) == 1:
                try:
                    cmdtoremove = first_word(message)
                except IndexError:
                    transmitMessage(socket, chatroom, username + " usage: !remove !<cmd_name>")
                    break
                if protectedcommands.has_key(cmdtoremove):
                    transmitMessage(socket, chatroom, username + " you cannot remove a protected command " + '"!' + cmdtoremove + '" !!!')
                    break
                try:
                    botcommands[cmdtoremove]
                except KeyError:
                    transmitMessage(socket, chatroom, username + " command does not exist!!!")
                    break
                del botcommands[cmdtoremove]
                transmitMessage(socket, chatroom, username + " command !" + cmdtoremove + " removed successfully!!!")
                with file("botcommands.json","w") as cmdfile:
                    json.dump(botcommands, cmdfile)
                break
            transmitMessage(socket, chatroom, username + " usage: !remove !<cmd_name>")
            break

Any ideas why this specific check gets bypassed? The logic looks identical to the working version but behaves completely different.

Yeah, parsing issue for sure. Your first_word() function is grabbing the wrong part of the message string. Print cmdtoremove right before that protected check - I bet it’s not what you expect. !create works because it follows different logic, but !remove breaks because of how you’re pulling the command name from the input.

The problem’s in your parsing logic, but there’s more to it. You’re using first_word(message) for both create and remove commands, even though they have different formats. Create uses !create !cmdname response while remove uses !remove !cmdname. Your first_word() function works fine for create since it grabs the second word, but with remove it’s returning the command name with the exclamation mark still attached. That breaks the lookup in your protectedcommands dictionary because those keys don’t have exclamation marks. Either strip the exclamation mark from cmdtoremove before checking, or fix your parsing to handle both formats the same way.

Your first_word() function is the problem. When you run !remove commandname, it’s grabbing “!remove” instead of “commandname”. The parsing logic isn’t handling the command structure right.

I ran into the same thing with my bot - I thought first_word() would pull the first argument after the command, but it was actually pulling the command itself.

Two ways to fix this: either use message.split()[1] directly for the remove command instead of first_word(), or fix your first_word() function to properly extract arguments. The create command probably works because it’s got different parsing with that space count check.

your first_word() function might be returning the cmd with the exclamation mark, but ur protectedcommands dict doesn’t have those marks. print what cmdtoremove actually contains before the check – i bet it’s “!remove” instead of just “remove”

Your first_word() function is the problem. When you call first_word(message) on “!remove commandname”, it’s grabbing “!remove” instead of “commandname”. Check that first_word() actually parses the command name after the initial command word. Add a debug print right before the protected commands check - see what cmdtoremove actually contains. I bet your parsing logic is pulling the wrong word from the message, so the protection check never fires.