Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python Help with pythom code from telegram

cassimir

New Coder
Hello everyone, i'm new on programming. My groups on telegram are being attacked by silent bots (I belive they join the group and automatically report or silence joining/leaving (don't know if its possible). In order to monitorate i'm doing a script to save all joining/leaving users in a .db file hosted on my PC. However, my script is not saving to my .db file when i join a testgroup that i've created. The group is public, the bot has admin rights. Can someone help me to solve this script or help me to get a better solution for my problem? Here is part of my script:
Code:
import requests, re, random, datetime, pytz, sqlite3, os

from dotenv import load_dotenv
from telegram import ChatMemberUpdated
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters, ChatMemberHandler
from datetime import datetime
from pytz import timezone

# Configurações
load_dotenv()
TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
if not TOKEN:
    raise ValueError("Token não encontrado! Verifique seu arquivo .env")
CMC_API_KEY = os.getenv('CMC_API_KEY')
username_admin = ["XXXX"]
DB_FILE = os.getenv('DB_FILE')

##DBASE FILE init connection
def init_db():
    conn = sqlite3.connect(http://telegram.com/
        'grupo_cripto_logs.db',
        detect_types=sqlite3.PARSE_DECLTYPES
    )
    cursor = conn.cursor()
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS user_activity (
        user_id INTEGER,
        username TEXT,
        first_name TEXT,
        last_name TEXT,
        action TEXT,  -- "join" ou "leave"
        timestamp datetime
    )
    ''')
    conn.commit()
    conn.close()

##TRACK MEMBERS FUNCTION 


async def track_members(update: ChatMemberUpdated, context: ContextTypes.DEFAULT_TYPE):
    try:
        print(f"\n🔔 Novo evento de membro: {update}")
        
        user = update.new_chat_member.user if update.new_chat_member else update.old_chat_member.user
        print(f"Usuário envolvido: ID={user.id}, Nome={user.full_name}")
        
        if update.new_chat_member and update.new_chat_member.status == 'member':
            action = "join"
            print("🟢 Ação: Entrada no grupo")
        elif update.old_chat_member and update.old_chat_member.status in ['left', 'kicked']:
            action = "leave"
            print("🔴 Ação: Saída do grupo")
        else:
            print("🟡 Outra mudança de status não tratada")
            return

        with sqlite3.connect('grupo_cripto_logs.db', detect_types=sqlite3.PARSE_DECLTYPES) as conn:
            cursor = conn.cursor()
            cursor.execute('''
            INSERT INTO user_activity VALUES (?, ?, ?, ?, ?, ?)
            ''', (
                user.id,
                user.username,
                user.first_name,
                user.last_name,
                action,
                datetime.now()
            ))
            conn.commit()
            print(f"✅ Dados salvos: {user.full_name} ({action})")
            
    except Exception as e:
        print(f"🚨 ERRO: {str(e)}")
        await context.bot.send_message(
            chat_id=chat_ids_alertas[0],
            text=f"Erro no tracking: {str(e)}"
        )
##Handler
if __name__ == '__main__':
    init_db()
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(ChatMemberHandler(track_members, ChatMemberHandler.CHAT_MEMBER))
```
`

I'm trying to save the log from users who join and leave my group. Check for a pattern of IDs that can be associated with those bots and ban them from my group.
 
I see that you probably have some unused imports, as well as redundant/duplicate imports.
I would recommend using Timezone instead of Pytz.
Just a proposal:

Python:
# Standard library imports
import os
import sqlite3
from datetime import datetime, timezone  # timezone is better than pytz for Python 3.9+

# Third-party imports
from dotenv import load_dotenv
from telegram import ChatMemberUpdated
from telegram.ext import (
    ApplicationBuilder,
    ContextTypes,
    ChatMemberHandler
)

A major problem regarding your issue could be the URL of your database connection:

Python:
def init_db():
    conn = sqlite3.connect(http://telegram.com/
        'grupo_cripto_logs.db',
        detect_types=sqlite3.PARSE_DECLTYPES
    )

Invalid URL as Python Code:
  • (http://telegram.com/) is not valid Python syntax
  • In Python, URLs need to be strings (in quotes) to be valid
  • Without quotes, Python tries to interpret it as code
Broken Multi-line Statement

You might try:

Python:
# Configurações
load_dotenv()
TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
if not TOKEN:
    raise ValueError("Token não encontrado! Verifique seu arquivo .env")
DB_FILE = os.getenv('DB_FILE', 'grupo_cripto_logs.db')  # Default filename if not specified

# Initialize database
def init_db():
    conn = sqlite3.connect(DB_FILE, detect_types=sqlite3.PARSE_DECLTYPES)
...
 
Last edited:
Back
Top Bottom