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:
```
`
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.
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.