[Python] Issue with int while trying to access a b

Discussão em 'Python' iniciado por Stack, Maio 10, 2025.

  1. Stack

    Stack Membro Participativo

    Good evening everyone. I'm quite new in programming I'm making a bot for my Telegram group and I'm having an error at the very end of the code. Could someone help me, please? A brief background: When entering my group, the person is muted and receives a message from the bot to click on the "verify" button to prove that they are human. When clicking verify, a private message opens with the bot and they answer 3 silly questions. After that, the bot grants access. The problem is that when clicking verify, I receive the error message. The error is on line 295, in verify_user chat_id = usuarios_nao_verificados[user_id]["chat_id"] TypeError: 'int' object is not subscriptable

    It occurs when I try to access usuarios_nao_verificados[user_id]["chat_id"]. I've checked the code where I add data to usuarios_nao_verificados, and it should be a dictionary. From what I understand, usuarios_nao_verificados[user_id] is a dictionary. I need to access the "chat_id" which is an integer and is inside the dictionary. How can I proceed in this case?

    async def verificar_usuario(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Processa o token de verificação"""
    user_id = update.effective_user.id
    token = update.message.text.split()[1] if len(update.message.text.split()) > 1 else None
    if not token or token not in tokens_verificacao:
    await update.message.reply_text("❌ Token inválido ou expirado. Peça um novo link no grupo.")
    return
    dados_token = tokens_verificacao[token]
    if datetime.now() > dados_token["expira"]:
    await update.message.reply_text("⌛ Token expirado. Peça um novo link no grupo.")
    tokens_verificacao.pop(token, None)
    return
    if dados_token["user_id"] != user_id:
    await update.message.reply_text("⚠️ Este token não é para você.")
    return
    # Verificação bem-sucedida
    if user_id in usuarios_nao_verificados:
    chat_id = usuarios_nao_verificados[user_id]["chat_id"]
    nome = usuarios_nao_verificados[user_id]["nome"]
    await context.bot.send_message(
    chat_id=chat_id,
    text=f"✅ {nome} verificou-se com sucesso! Bem-vindo(a)!",
    parse_mode='HTML'
    )
    usuarios_nao_verificados.pop(user_id, None)
    tokens_verificacao.pop(token, None)
    await update.message.reply_text(" Verificação concluída! Agora você pode participar do grupo.")
    else:
    await update.message.reply_text("⚠️ Você já está verificado ou não está mais no grupo.")


    And i'm defining the dictionary in another async function here

    async def receber_novo_membro(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handler para novos membros no grupo"""
    for novo_membro in update.message.new_chat_members:

    chat_id_grupo = update.effective_chat.id
    user_id_novo_membro = novo_membro.id
    nome_novo_membro = escape_markdown(novo_membro.full_name, version=2)

    # Adiciona à lista de não verificados
    usuarios_nao_verificados[user_id_novo_membro] = {
    "chat_id": chat_id_grupo,
    "nome": nome_novo_membro,
    "entrada": datetime.now()
    }

    try:
    # Silenciar o novo membro
    permissions = telegram.ChatPermissions(can_send_messages=False, can_send_other_messages=False, can_add_web_page_previews=False)
    await context.bot.restrict_chat_member(chat_id=chat_id_grupo, user_id=user_id_novo_membro, permissions=permissions)
    logger.info(f"Usuário {user_id_novo_membro} silenciado ao entrar.")
    except Exception as e:
    logger.error(f"Erro ao silenciar usuário {user_id_novo_membro}: {e}")

    # Cria botão de verificação
    link_verificacao = gerar_link_verificacao(user_id_novo_membro)
    logger.info(f"Link de verificação gerado para {user_id_novo_membro}: {link_verificacao}")
    keyboard = InlineKeyboardMarkup([
    [InlineKeyboardButton("✅ Verificar Agora", url=link_verificacao)]
    ])

    usuarios_nao_verificados[user_id_novo_membro] = chat_id_grupo

    mensagem = (
    f" Olá {nome_novo_membro}! Para ter acesso completo ao grupo, por favor, clique no botão abaixo para verificar sua identidade:\n\n"
    f"[Verificar Agora](https://t.me/Betinaabot?start={secrets.token_urlsafe(8)})" # Removendo o link markdown, o botão fará o trabalho
    )

    try:
    await context.bot.send_message(
    chat_id=chat_id_grupo,
    text=f" Olá {nome_novo_membro}! Para ter acesso completo ao grupo, por favor, clique no botão abaixo para verificar sua identidade:",
    reply_markup=keyboard
    )

    except Exception as e:
    logger.error(f"Erro ao enviar mensagem para {user_id_novo_membro}: {e}")

    Continue reading...

Compartilhe esta Página