Jésus Christophe
Jésus Christophe

Reputation: 67

TypeError: getattr(): attribute name must be string

I need to organize the ouput as a button in a telegram bot. I create, for example, a dictionary and I need to infer the key and the object from it, to form it as string and place it in a button that will go through the for loop. But instead of the correct result I see only this error: TypeError: getattr(): attribute name must be string. Here's my code:

def choose_language(update, conext):
    chat = update.effective_chat
    land = {
        'Eng':'en',
        'Rus':'ru'
    }
    b = []
    for k,v in land.items():
        a = k, v
        b.append(a)
    flatten = [str(item) for sub in b for item in sub]
    for key in flatten:
        button = [InlineKeyboardButton(f"{key}", callback_data='{key}')]

    #for key in land:
        #button = InlineKeyboardButton(str(land[key]).capitalize(), callback_data=str(key))
    reply_markup = InlineKeyboardMarkup(button)
    update.message.reply_text('Choose target language:', reply_markup=reply_markup)

Upvotes: 2

Views: 6133

Answers (2)

Jésus Christophe
Jésus Christophe

Reputation: 67

So I've done it. The problem was that I made the button as a list when it raises an AttributeError: the list object has no to_dict attribute. Then I ditched the dict.attributes and decided to short the flatten to get only string objects.

d = {
    'Eng':'en',
    'Rus':'ru',
    'Ger':'ge'
}
    button_demo = []
    b = []
    bb = []
    for k, v in d.items():
        a = k
        b.append(a)
        s = v
        bb.append(s)
    flatten = [str(sub) for sub in b]
    flatten1 = [str(sub) for sub in bb]
    for ix in range(len(flatten)):
        button = [InlineKeyboardButton(f"{flatten[ix]}", callback_data=f'{flatten1[ix]}')]
        button_demo.append(button)
reply_markup = InlineKeyboardMarkup(button_demo)
update.message.reply_text('Choose target language:', reply_markup=reply_markup)

Upvotes: 0

CallMeStag
CallMeStag

Reputation: 7050

The argument for InlineKeyboardMarkup must be a list of lists - you're passing a simple list instead.

Upvotes: 3

Related Questions