-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
174 lines (145 loc) · 6.7 KB
/
bot.py
File metadata and controls
174 lines (145 loc) · 6.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from telegram.error import BadRequest # Import BadRequest
from config import BOT_TOKEN, WEBHOOK_URL, WEBHOOK_PORT, ADMIN_IDS, GROUP_IDS
from database import Database
# Set up logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Initialize database
db = Database()
# Initialize application globally
application = None
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a message when the command /start is issued."""
logger.info(f"'/start' command received from user {update.effective_user.id} in chat {update.effective_chat.id}")
try:
await update.message.reply_text('Hi! I am your group moderation bot.')
logger.info(f"Successfully replied to '/start' from user {update.effective_user.id}")
except Exception as e:
logger.error(f"Error replying to /start: {e}", exc_info=True)
async def store_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Store every message in the database."""
if update.message:
chat_id = update.message.chat_id
message_id = update.message.message_id
user_id = update.message.from_user.id
# Store message in database
db.store_message(chat_id, message_id, user_id)
async def get_user_id(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Get user ID by replying to their message."""
if not update.message.reply_to_message:
await update.message.reply_text("Please reply to a user's message to get their ID.")
return
target_user = update.message.reply_to_message.from_user
response = (
f"User Information:\n"
f"Name: {target_user.full_name}\n"
f"Username: @{target_user.username if target_user.username else 'N/A'}\n"
f"ID: {target_user.id}\n"
f"Language: {target_user.language_code if target_user.language_code else 'N/A'}"
)
try:
await update.message.reply_text(response)
except BadRequest as e:
if "Message to be replied not found" in str(e):
logger.warning(f"Failed to reply for /user_id: Original message likely deleted. Error: {e}")
await update.message.reply_text("Couldn't reply. The message you replied to might have been deleted.")
else:
logger.error(f"Error in /user_id reply: {e}", exc_info=True)
await update.message.reply_text("An error occurred while trying to get user info.")
except Exception as e:
logger.error(f"Unexpected error in /user_id: {e}", exc_info=True)
await update.message.reply_text("An unexpected error occurred.")
async def check_user_groups(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Check which groups a user has joined."""
if update.effective_user.id not in ADMIN_IDS:
return
if not update.message.reply_to_message:
await update.message.reply_text("Please reply to a user's message to check their group memberships.")
return
target_user = update.message.reply_to_message.from_user
target_id = target_user.id
# Get all messages for this user to determine which groups they're in
messages = db.get_user_messages(target_id)
user_groups = set(chat_id for chat_id, _ in messages)
response = [f"User {target_user.full_name} (ID: {target_id}) is in the following groups:"]
for group_id in user_groups:
try:
chat = await context.bot.get_chat(group_id)
response.append(f"- {chat.title} (ID: {group_id})")
except Exception as e:
logger.error(f"Error getting chat info for {group_id}: {e}")
response.append(f"- Unknown Group (ID: {group_id})")
if not user_groups:
response = [f"User {target_user.full_name} (ID: {target_id}) is not found in any groups."]
await update.message.reply_text("\n".join(response))
async def ban_all(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Ban a user from all groups and delete their messages."""
if update.effective_user.id not in ADMIN_IDS:
return
if not update.message.reply_to_message:
await update.message.reply_text("Please reply to a user's message to ban them.")
return
target_user = update.message.reply_to_message.from_user
target_id = target_user.id
# Prevent banning an admin
if target_id in ADMIN_IDS:
await update.message.reply_text("You cannot ban another admin.")
return
# Get all messages for this user
messages = db.get_user_messages(target_id)
# Batch delete messages
delete_tasks = []
for chat_id, message_id in messages:
delete_tasks.append(
context.bot.delete_message(
chat_id=chat_id,
message_id=message_id
)
)
# Process in batches of 20
for i in range(0, len(delete_tasks), 20):
await asyncio.gather(*delete_tasks[i:i+20], return_exceptions=True)
await asyncio.sleep(1) # Rate limiting
# Ban user from all groups
for group_id in GROUP_IDS:
try:
await context.bot.ban_chat_member(
chat_id=group_id,
user_id=target_id,
revoke_messages=True
)
except Exception as e:
logger.error(f"Error banning user in group {group_id}: {e}")
# Delete stored messages from database
db.delete_user_messages(target_id)
await update.message.reply_text(
f"User {target_user.full_name} (ID: {target_id}) has been banned from all groups "
"and their messages have been deleted."
)
# Build the application instance - SINGLE SOURCE OF TRUTH
application = Application.builder().token(BOT_TOKEN).build()
# Add handlers directly
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("banall", ban_all))
application.add_handler(CommandHandler("user_id", get_user_id))
application.add_handler(CommandHandler("user_is_join", check_user_groups))
# Remove this entire block:
# if WEBHOOK_URL:
# # Proper webhook configuration
# application.run_webhook(
# listen="0.0.0.0",
# port=WEBHOOK_PORT,
# webhook_url=f"{WEBHOOK_URL}/webhook", # Fixed endpoint
# secret_token='YOUR_SECRET_TOKEN', # Add this for security
# drop_pending_updates=True
# )
# else:
# application.run_polling()
# Just keep the handler registration:
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), store_message))