Shinhati2023 commited on
Commit
877fc1f
·
verified ·
1 Parent(s): dfaa743

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +176 -60
bot.py CHANGED
@@ -1,89 +1,205 @@
1
  import os
2
  import re
 
 
3
  from collections import defaultdict
4
  from telegram import Update
5
- from telegram.ext import ApplicationBuilder, MessageHandler, CommandHandler, filters, ContextTypes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Abusive words list
8
  ABUSIVE_WORDS = [
9
- "fuck", "shit", "bitch", "asshole", "cunt", "motherfucker",
10
  "dick", "pussy", "slut", "whore", "bastard",
11
- "mumu", "ode", "werey", "weyre", "olodo", "ashawo", "oloshi",
12
- "agbaya", "oloriburuku", "shege", "dan iska", "apoda",
13
  "obun", "didirin", "ewu", "ndisime"
14
  ]
15
 
16
- pattern = r'(?i)\b(' + '|'.join(re.escape(word) for word in ABUSIVE_WORDS) + r')\b'
17
- abusive_regex = re.compile(pattern)
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- # Dictionary to keep track of user warnings: {user_id: warning_count}
20
- user_warnings = defaultdict(int)
21
 
22
- async def check_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 
 
 
 
 
 
23
  message = update.message
24
  if not message or not message.text:
25
  return
26
-
27
- if abusive_regex.search(message.text):
28
- user = message.from_user
29
- chat_id = message.chat_id
30
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  try:
32
- await message.delete()
33
-
34
- # Increment the user's warning count
35
- user_warnings[user.id] += 1
36
- warnings = user_warnings[user.id]
37
-
38
- if warnings == 1:
39
- await context.bot.send_message(chat_id, f"⚠️ {user.first_name}, this is your 1st warning. Please do not use abusive language.")
40
- elif warnings == 2:
41
- await context.bot.send_message(chat_id, f"⚠️ {user.first_name}, this is your 2nd and FINAL warning. If it happens again, you will be removed.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  else:
43
- # 3rd strike: Ban the user
44
- await context.bot.send_message(chat_id, f"🚫 {user.first_name} has been removed from the group for repeated abusive language.")
45
- await context.bot.ban_chat_member(chat_id, user.id)
46
- # Reset their warnings after banning
47
- user_warnings[user.id] = 0
48
-
49
  except Exception as e:
50
- print(f"Could not process warning/ban. Error: {e}")
 
 
 
 
51
 
52
- async def daily_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 
 
53
  message = update.message
54
-
55
- # Check if the command is sent in a group
56
- if message.chat.type in ['group', 'supergroup']:
57
- # Verify the person sending the command is an admin
58
- user_status = await context.bot.get_chat_member(message.chat_id, message.from_user.id)
59
- if user_status.status not in ['administrator', 'creator']:
60
- return # Silently ignore if a regular user tries to use it
61
-
62
- # Check if there is text after the /daily command
63
  if not context.args:
64
  await message.reply_text("Usage: /daily Your message here")
65
  return
66
-
67
- # Combine the arguments into a single string
68
- bot_message = " ".join(context.args)
69
-
70
  try:
71
- # Delete the admin's original command message
72
  await message.delete()
73
- # Send the message as the bot
74
- await context.bot.send_message(chat_id=message.chat_id, text=f"📢 **Daily Update**\n\n{bot_message}", parse_mode='Markdown')
75
- except Exception as e:
76
- print(f"Error sending broadcast: {e}")
 
 
 
 
 
 
 
 
77
 
78
- if __name__ == '__main__':
79
- TOKEN = os.environ.get("BOT_TOKEN", "YOUR_TOKEN_HERE")
80
  app = ApplicationBuilder().token(TOKEN).build()
81
-
82
- # Listen for the /daily command
83
  app.add_handler(CommandHandler("daily", daily_broadcast))
84
-
85
- # Listen to all other text messages for abuse
86
- app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, check_message))
87
-
88
- print("Bot is running with warning system and daily broadcast...")
89
  app.run_polling()
 
 
 
 
1
  import os
2
  import re
3
+ import json
4
+ import logging
5
  from collections import defaultdict
6
  from telegram import Update
7
+ from telegram.ext import (
8
+ ApplicationBuilder,
9
+ MessageHandler,
10
+ CommandHandler,
11
+ ContextTypes,
12
+ filters,
13
+ )
14
+
15
+ # ------------------ CONFIG ------------------
16
+
17
+ TOKEN = os.getenv("BOT_TOKEN") # Set this in your environment
18
+ DATA_FILE = "bot_data.json"
19
+
20
+ logging.basicConfig(
21
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
22
+ level=logging.INFO,
23
+ )
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # ------------------ ABUSIVE WORD FILTER ------------------
27
 
 
28
  ABUSIVE_WORDS = [
29
+ "fuck", "shit", "bitch", "asshole", "cunt", "motherfucker",
30
  "dick", "pussy", "slut", "whore", "bastard",
31
+ "mumu", "ode", "werey", "weyre", "olodo", "ashawo", "oloshi",
32
+ "agbaya", "oloriburuku", "shege", "dan iska", "apoda",
33
  "obun", "didirin", "ewu", "ndisime"
34
  ]
35
 
36
+ abusive_regex = re.compile(
37
+ r"(?i)\b(" + "|".join(re.escape(word) for word in ABUSIVE_WORDS) + r")\b"
38
+ )
39
+
40
+ # ------------------ PERSISTENT STORAGE ------------------
41
+
42
+ def load_data():
43
+ if not os.path.exists(DATA_FILE):
44
+ return {"groups": [], "warnings": {}}
45
+ with open(DATA_FILE, "r") as f:
46
+ return json.load(f)
47
+
48
+ def save_data(data):
49
+ with open(DATA_FILE, "w") as f:
50
+ json.dump(data, f)
51
 
52
+ data_store = load_data()
 
53
 
54
+ # Structure:
55
+ # data_store["groups"] = [group_ids]
56
+ # data_store["warnings"] = { "chat_id:user_id": warning_count }
57
+
58
+ # ------------------ ABUSE HANDLER ------------------
59
+
60
+ async def track_groups_and_check_abuse(update: Update, context: ContextTypes.DEFAULT_TYPE):
61
  message = update.message
62
  if not message or not message.text:
63
  return
64
+
65
+ chat = message.chat
66
+
67
+ # Track groups
68
+ if chat.type in ["group", "supergroup"]:
69
+ if chat.id not in data_store["groups"]:
70
+ data_store["groups"].append(chat.id)
71
+ save_data(data_store)
72
+
73
+ # Check abuse
74
+ if not abusive_regex.search(message.text):
75
+ return
76
+
77
+ user = message.from_user
78
+ key = f"{chat.id}:{user.id}"
79
+
80
+ try:
81
+ await message.delete()
82
+ except Exception as e:
83
+ logger.warning(f"Failed to delete message: {e}")
84
+
85
+ # Increase warning count
86
+ data_store["warnings"][key] = data_store["warnings"].get(key, 0) + 1
87
+ warnings = data_store["warnings"][key]
88
+ save_data(data_store)
89
+
90
+ if warnings == 1:
91
+ await chat.send_message(
92
+ f"⚠️ {user.first_name}, first warning. Do not use abusive language."
93
+ )
94
+ elif warnings == 2:
95
+ await chat.send_message(
96
+ f"⚠️ {user.first_name}, FINAL warning. Next time you will be removed."
97
+ )
98
+ else:
99
+ await chat.send_message(
100
+ f"🚫 {user.first_name} has been removed for repeated abusive language."
101
+ )
102
  try:
103
+ await context.bot.ban_chat_member(chat.id, user.id)
104
+ except Exception as e:
105
+ logger.error(f"Failed to ban user: {e}")
106
+
107
+ data_store["warnings"][key] = 0
108
+ save_data(data_store)
109
+
110
+ # ------------------ PRIVATE BROADCAST ------------------
111
+
112
+ async def vikingkull_omega(update: Update, context: ContextTypes.DEFAULT_TYPE):
113
+ message = update.message
114
+
115
+ if message.chat.type != "private":
116
+ return
117
+
118
+ if not data_store["groups"]:
119
+ await message.reply_text("No groups stored yet.")
120
+ return
121
+
122
+ post_text = ""
123
+ photo_id = None
124
+
125
+ if message.photo:
126
+ photo_id = message.photo[-1].file_id
127
+ post_text = (message.caption or "").replace("/vikingkull_omega", "").strip()
128
+ elif message.text:
129
+ post_text = message.text.replace("/vikingkull_omega", "").strip()
130
+
131
+ if not post_text and not photo_id:
132
+ await message.reply_text(
133
+ "Usage:\n"
134
+ "/vikingkull_omega your message\n"
135
+ "OR send photo with caption."
136
+ )
137
+ return
138
+
139
+ success = 0
140
+
141
+ for group_id in list(data_store["groups"]):
142
+ try:
143
+ if photo_id:
144
+ await context.bot.send_photo(
145
+ chat_id=group_id,
146
+ photo=photo_id,
147
+ caption=post_text
148
+ )
149
  else:
150
+ await context.bot.send_message(
151
+ chat_id=group_id,
152
+ text=post_text
153
+ )
154
+ success += 1
 
155
  except Exception as e:
156
+ logger.warning(f"Removing invalid group {group_id}: {e}")
157
+ data_store["groups"].remove(group_id)
158
+ save_data(data_store)
159
+
160
+ await message.reply_text(f"✅ Broadcast sent to {success} group(s).")
161
 
162
+ # ------------------ DAILY COMMAND ------------------
163
+
164
+ async def daily_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
165
  message = update.message
166
+ chat = message.chat
167
+
168
+ # Admin-only in groups
169
+ if chat.type in ["group", "supergroup"]:
170
+ member = await context.bot.get_chat_member(chat.id, message.from_user.id)
171
+ if member.status not in ["administrator", "creator"]:
172
+ return
173
+
 
174
  if not context.args:
175
  await message.reply_text("Usage: /daily Your message here")
176
  return
177
+
178
+ text = " ".join(context.args)
179
+
 
180
  try:
 
181
  await message.delete()
182
+ except:
183
+ pass
184
+
185
+ await chat.send_message(
186
+ f"📢 Daily Update\n\n{text}"
187
+ )
188
+
189
+ # ------------------ MAIN ------------------
190
+
191
+ def main():
192
+ if not TOKEN:
193
+ raise ValueError("BOT_TOKEN environment variable not set.")
194
 
 
 
195
  app = ApplicationBuilder().token(TOKEN).build()
196
+
 
197
  app.add_handler(CommandHandler("daily", daily_broadcast))
198
+ app.add_handler(CommandHandler("vikingkull_omega", vikingkull_omega))
199
+ app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, track_groups_and_check_abuse))
200
+
201
+ logger.info("Bot is running...")
 
202
  app.run_polling()
203
+
204
+ if __name__ == "__main__":
205
+ main()