Python AttributeError: 'str' object has no attribute 'append' (Specific)

2k views Asked by At

Currently having an issue with my Twitch chat bot, this error occurs when the bot picks up JTV sending a flag to op somebody in the channel (Giving them mod permissions).

The problem I'm having is that this error sometimes occurs and sometime doesn't. Due to this, I cannot have a stable process of this running on my VPS. Any help?

message = ' '.join(line)
x = re.findall('^:jtv MODE (.*?) \+o (.*)$', message) # Find the message
if (len(x) > 0):
    channel = x[0][0]
    if (channel not in mods): # If the channel isn't already in the list
        mods[channel] = []
    list = mods.get(channel)
    list.append(x[0][1])
    print(mods) # Print updated list with new mods

Here is where I remove them as well, Not sure if this might incur an error or not. But I will post it nonetheless...

# Removing mods
y = re.findall('^:jtv MODE (.*?) \-o (.*)$', message)
if (len(y) > 0):
    channel = y[0][0]
    if (channel in mods):
        mods.get(channel).remove(y[0][1])
        print(mods) 
3

There are 3 answers

1
Christopher Ian  Stern On BEST ANSWER

From what I can see here the 'list' list.append(x[0][1]) must sometimes be a string, not a list. So maybe mods.get(channel) sometimes returns a string. One solution might be to check if you got a string this time, type(list) == str and don't do the append. Unfortunately that's all I can tell you. Maybe look inside mods.get() and see why it would do that.

0
TigerhawkT3 On

First, call the list something like my_list. Second, whenever channel is not in mods, mods[channel] will not be assigned a new list. The fact that it says it's a str means that you're assigning a string into that somewhere in your code. You should probably look into that. But you can try to sidestep all that by asking for forgiveness rather than permission:

try:
    my_list.append(x[0][1])
except AttributeError:
    pass # ideally, you shouldn't let errors pass silently

Also, instead of if (len(x) > 0):, you can do if x:. Give x a more descriptive variable name like message or something while you're at it.

0
Dken On

You should use logging to debug your code. After that issue occurred, you can check the log and find out what happened.

BTW, Don't use list as a variable name. It's very confusing.

For example:

import logging

try:
    list.append(x[0][1])
except:
    logging.error(type(x))
    logging.error(x)