-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathbanwords.py
More file actions
278 lines (246 loc) · 12.7 KB
/
banwords.py
File metadata and controls
278 lines (246 loc) · 12.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# -*- coding: utf-8 -*-
# Module author: @Fl1yd
import requests
from telethon.tl.functions.channels import EditBannedRequest as eb
from telethon.tl.types import ChatBannedRights as cb
from .. import loader, utils
@loader.tds
class BanWordsMod(loader.Module):
"""Плохие слова."""
strings = {"name": "Ban Words"}
async def client_ready(self, client, db):
self.db = db
async def addbwcmd(self, message):
"""Добавить слово в список "Плохих слов". Используй: .addbw <слово>."""
if not message.is_private:
chat = await message.get_chat()
if not chat.admin_rights and not chat.creator:
return await message.edit("<b>Я не админ здесь.</b>")
else:
if not chat.admin_rights.delete_messages:
return await message.edit("<b>У меня нет нужных прав.</b>")
words = self.db.get("BanWords", "bws", {})
args = utils.get_args_raw(message).lower()
if not args:
return await message.edit("<b>[BanWords]</b> Нет аргументов.")
chat_id = str(message.chat_id)
if chat_id not in words:
words.setdefault(chat_id, [])
if "stats" not in words:
words.update(
{"stats": {chat_id: {"action": "none", "antimat": False, "limit": 5}}}
)
if args not in words[chat_id]:
if ", " in args:
args = args.split(", ")
words[chat_id].extend(args)
self.db.set("BanWords", "bws", words)
await message.edit(
f"<b>[BanWords]</b> В список чата добавлены слова - \"<code>{'; '.join(args)}</code>\"."
)
else:
words[chat_id].append(args)
self.db.set("BanWords", "bws", words)
await message.edit(
f'<b>[BanWords]</b> В список чата добавлено слово - "<code>{args}</code>".'
)
else:
return await message.edit(
"<b>[BanWords]</b> Такое слово уже есть в списке слов чата."
)
async def rmbwcmd(self, message):
"""Удалить слово из список "Плохих слов". Используй: .rmbw <слово или all/clearall (по желанию)>.\nall - удаляет все слова из списка.\nclearall - удаляет все сохраненные данные модуля."""
words = self.db.get("BanWords", "bws", {})
args = utils.get_args_raw(message)
if not args:
return await message.edit("<b>[BanWords]</b> Нет аргументов.")
chat_id = str(message.chat_id)
try:
if args == "all":
words.pop(chat_id)
words["stats"].pop(chat_id)
self.db.set("BanWords", "bws", words)
return await message.edit(
"<b>[BanWords]</b> Из списка чата удалены все слова."
)
if args == "clearall":
self.db.set("BanWords", "bws", {})
return await message.edit(
"<b>[BanWords]</b> Все списки из всех чатов были удалены."
)
words[chat_id].remove(args)
if len(words[chat_id]) == 0:
words.pop(chat_id)
self.db.set("BanWords", "bws", words)
await message.edit(
f'<b>[BanWords]</b> Из списка чата удалено слово - "<code>{args}</code>".'
)
except (KeyError, ValueError):
return await message.edit(
"<b>[BanWords]</b> Этого слова нет в словаре этого чата."
)
async def bwscmd(self, message):
"""Посмотреть список "Плохих слов". Используй: .bws."""
words = self.db.get("BanWords", "bws", {})
chat_id = str(message.chat_id)
try:
ls = words[chat_id]
if len(ls) == 0:
raise KeyError
except KeyError:
return await message.edit("<b>[BanWords]</b> В этом чате нет списка слов.")
word = "".join(f"• <code>{_}</code>\n" for _ in ls)
await message.edit(f"<b>[BanWords]</b> Список слов в этом чате:\n\n{word}")
async def bwstatscmd(self, message):
"""Статистика "Плохих слов". Используй: .bwstats <clear* (по желанию)>.\n* - сбросить настройки чата."""
words = self.db.get("BanWords", "bws", {})
chat_id = str(message.chat_id)
args = utils.get_args_raw(message)
if args == "clear":
try:
words["stats"].pop(chat_id)
words["stats"].update(
{chat_id: {"antimat": False, "action": "none", "limit": 5}}
)
self.db.set("BanWords", "bws", words)
return await message.edit("<b>[BanWords]</b> Настройки чата сброшены.")
except KeyError:
return await message.edit(
"<b>[BanWords]</b> Нет статистики пользователей."
)
try:
w = ""
for _ in words["stats"][chat_id]:
if (
_ not in ["action", "antimat", "limit"]
and words["stats"][chat_id][_] != 0
):
user = await message.client.get_entity(int(_))
w += f'• <a href="tg://user?id={int(_)}">{user.first_name}</a>: <code>{words["stats"][chat_id][_]}</code>\n'
return await message.edit(
f"<b>[BanWords]</b> Кто использовал спец.слова:\n\n{w}"
)
except KeyError:
return await message.edit(
"<b>[BanWords]</b> В этом чате нет тех, кто использовал спец.слова."
)
async def swbwcmd(self, message):
"""Переключить режим "Плохих слов". Используй: .swbw <режим(antimat/kick/ban/mute/none)>, или .swbw limit <кол-во:int>."""
if not message.is_private:
chat = await message.get_chat()
if chat.admin_rights or chat.creator:
if chat.admin_rights.delete_messages is False:
return await message.edit("<b>У меня нет нужных прав.</b>")
else:
return await message.edit("<b>Я не админ здесь.</b>")
words = self.db.get("BanWords", "bws", {})
args = utils.get_args_raw(message)
chat_id = str(message.chat_id)
if chat_id not in words:
words.setdefault(chat_id, [])
if "stats" not in words:
words.update(
{"stats": {chat_id: {"action": "none", "antimat": False, "limit": 5}}}
)
if not args:
return await message.edit(
f"<b>[BanWords]</b> Настройки чата:\n\n"
f"<b>Лимит спец.слов:</b> {words['stats'][chat_id]['limit']}\n"
f"<b>При достижении лимита спец.слов будет выполняться действие:</b> {words['stats'][chat_id]['action']}\n"
f"<b>Статус режима \"антимат\":</b> {words['stats'][chat_id]['antimat']}"
)
if "limit" in args:
try:
limit = int(utils.get_args_raw(message).split(" ", 1)[1])
words["stats"][chat_id].update({"limit": limit})
self.db.set("BanWords", "bws", words)
return await message.edit(
f"<b>[BanWords]</b> Лимит спец.слов был установлен на {words['stats'][chat_id]['limit']}."
)
except (IndexError, ValueError):
return await message.edit(
f"<b>[BanWords]</b> Лимит спец.слов в этом чате - {words['stats'][chat_id]['limit']}\n"
f"Установить новый можно командой .bwsw limit <кол-во:int>."
)
if args == "antimat":
if words["stats"][chat_id]["antimat"]:
words["stats"][chat_id]["antimat"] = False
self.db.set("BanWords", "bws", words)
return await message.edit('<b>[BanWords]</b> Режим "антимат" выключен.')
else:
words["stats"][chat_id]["antimat"] = True
self.db.set("BanWords", "bws", words)
return await message.edit('<b>[BanWords]</b> Режим "антимат" включен.')
else:
if args == "kick":
words["stats"][chat_id].update({"action": "kick"})
elif args == "ban":
words["stats"][chat_id].update({"action": "ban"})
elif args == "mute":
words["stats"][chat_id].update({"action": "mute"})
elif args == "none":
words["stats"][chat_id].update({"action": "none"})
else:
return await message.edit(
"<b>[BanWords]</b> Такого режима нет в списке. Есть: kick/ban/mute/none."
)
self.db.set("BanWords", "bws", words)
return await message.edit(
f"<b>[BanWords]</b> Теперь при достижении лимита спец.слов будет выполняться действие: {words['stats'][chat_id]['action']}."
)
async def watcher(self, message):
"""Обновление от 19.03: Фикс говнокода."""
try:
if message.sender_id == (await message.client.get_me()).id:
return
words = self.db.get("BanWords", "bws", {})
chat_id = str(message.chat_id)
user_id = str(message.sender_id)
user = await message.client.get_entity(int(user_id))
if chat_id not in str(words):
return
action = words["stats"][chat_id]["action"]
if words["stats"][chat_id]["antimat"] is True:
r = requests.get("https://api.fl1yd.ml/badwords")
ls = r.text.split(", ")
else:
ls = words[chat_id]
for _ in ls:
if _.lower() in message.raw_text.lower().split():
if user_id not in words["stats"][chat_id]:
words["stats"][chat_id].setdefault(user_id, 0)
count = words["stats"][chat_id][user_id]
words["stats"][chat_id].update({user_id: count + 1})
self.db.set("BanWords", "bws", words)
if count == words["stats"][chat_id]["limit"]:
try:
if action == "kick":
await message.client.kick_participant(
int(chat_id), int(user_id)
)
elif action == "ban":
await message.client(
eb(
int(chat_id),
user_id,
cb(until_date=None, view_messages=True),
)
)
elif action == "mute":
await message.client(
eb(
int(chat_id),
user.id,
cb(until_date=True, send_messages=True),
)
)
words["stats"][chat_id].pop(user_id)
self.db.set("BanWords", "bws", words)
await message.respond(
f"<b>[BanWords]</b> {user.first_name} достиг лимит ({words['stats'][chat_id]['limit']}) спец.слова, и был ограничен в чате."
)
except:
pass
await message.client.delete_messages(message.chat_id, message.id)
except:
pass