forked from mehdiirh/telegram-copy-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
404 lines (292 loc) · 11.1 KB
/
main.py
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!venv/bin/python
"""
Forwarder bot v1.1.2
Written by: https://github.com/mehdiirh
1) Create an isolated virtual environment using: `python -m venv venv`
2) Install requirements using: `pip install -r requirements.txt`
3) add your API_ID and API_HASH to Login.py
4) add API_ID, API_HASH and sudo to :: plugins/jsons/config.json
5) run this file ( main.py )
6) Enter your credential and login
"""
from Login import get_client
from plugins.utils import Entities, Filters, Config, Messages
from telethon.sync import events
from Types import *
from time import sleep
import re
import logging
# ==================
entities_manager = Entities()
filters_manager = Filters()
config_manager = Config()
message_manager = Messages()
client = get_client()
logging.basicConfig(
format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
level=logging.WARNING
)
client.start()
print("FORWARDER BOT STARTED ;)")
# ==================
@client.on(events.NewMessage(incoming=True))
async def status(message: Message):
if config_manager.bot_enabled:
return
if await message.get_sender() == await client.get_me() or message.sender_id in config_manager.sudo:
return
else:
raise events.StopPropagation
@client.on(events.NewMessage())
async def forwarder(message: Message):
try:
chat_id = message.chat.id
except AttributeError:
chat_id = message.chat_id
if chat_id not in entities_manager.entities:
return
target_entities = entities_manager.get_target_entities(chat_id)
if message.poll:
for target in target_entities:
await message.forward_to(target)
return
if config_manager.get('filter_words'):
for word in filters_manager.words:
message.text = re.sub(r'(?i){0}'.format(word[0]), word[1], message.text)
if config_manager.get('add_signature'):
if config_manager.sign:
message.text = message.text + f'\n\n{config_manager.sign}'
replied_message = None
reply_to = None
if message.is_reply:
replied_message: Message = await message.get_reply_message()
replied_message = replied_message.id
for target in target_entities:
if replied_message is not None:
try:
reply_to = message_manager.get(chat_id, replied_message)
except ValueError:
message.text = f'[ Replied to message id: {replied_message} ]\n\n' + message.text
if reply_to:
for i in reply_to:
if i[0] == target:
reply_to = i[1]
sent_message = await client.send_message(target, message.message, reply_to=reply_to)
message_manager.add(chat_id, message.id, target, sent_message.id)
sleep(0.5)
@client.on(events.NewMessage(incoming=True))
async def forbid_non_sudo_commands(message: Message):
if await message.get_sender() == await client.get_me() or message.sender_id in config_manager.sudo:
return
else:
raise events.StopPropagation
@client.on(events.NewMessage(pattern=r'^[Ss]ync$'))
async def add_config(message: Message):
replied_message: Message = await message.respond('Syncing dialogs...')
try:
dialogs = await client.get_dialogs()
except Exception as e:
await message.edit(f'❗️ Error in syncing chats:\n {e}')
raise events.StopPropagation
await replied_message.edit(f"✅ Successfully synced {len(dialogs)} chats")
raise events.StopPropagation
@client.on(events.NewMessage(
pattern=r'^[Ll]ink @?(-?[1-9a-zA-Z][a-zA-Z0-9_]{4,}) to @?(-?[1-9a-zA-Z][a-zA-Z0-9_]{4,})$'))
async def add_config(message: Message):
msg: str = message.raw_text
msg = msg.replace('@', '')
pattern = re.compile(r'^[Ll]ink @?(-?[1-9a-zA-Z][a-zA-Z0-9_]{4,}) to @?(-?[1-9a-zA-Z][a-zA-Z0-9_]{4,})$')
match = pattern.match(msg)
if not match:
return
processing: Message = await message.reply('Processing...')
base_entity = match.group(1).lower()
target_entity = match.group(2).lower()
try:
base_entity = int(base_entity)
except ValueError:
pass
try:
target_entity = int(target_entity)
except ValueError:
pass
try:
base_entity = await client.get_entity(base_entity)
except:
await processing.edit('❗️ Base entity does not exists')
return
try:
target_entity = await client.get_entity(target_entity)
except:
await processing.edit('❗️ Target entity does not exists')
return
try:
entities_manager.add_config(base_entity.id, target_entity.id)
except ValueError as e:
await processing.edit(f'❗️ {e.args[0]}')
return
try:
base_entity_title = base_entity.title
except AttributeError:
base_entity_title = base_entity.first_name
if base_entity.last_name:
base_entity_title += base_entity.last_name
try:
target_entity_title = target_entity.title
except AttributeError:
target_entity_title = target_entity.first_name
if target_entity.last_name:
target_entity_title += target_entity.last_name
await processing.edit(f"✅ [ `{base_entity_title}` ] linked to [ `{target_entity_title}` ]")
@client.on(events.NewMessage(pattern=r'^[Uu]nlink @?(-?[1-9a-zA-Z][a-zA-Z0-9_]{4,})$'))
async def remove_config(message: Message):
msg: str = message.raw_text
msg = msg.replace('@', '')
pattern = re.compile(r'^[Uu]nlink @?([1-9a-zA-Z][a-zA-Z0-9_]{4,})$')
match = pattern.match(msg)
if not match:
return
processing: Message = await message.reply('Processing...')
base_entity = match.group(1).lower()
try:
base_entity = int(base_entity)
except ValueError:
pass
try:
base_entity = await client.get_entity(base_entity)
except:
await processing.edit('❗️ Base entity does not exists')
return
try:
base_entity_title = base_entity.title
except AttributeError:
base_entity_title = base_entity.first_name
if base_entity.last_name:
base_entity_title += base_entity.last_name
try:
count = entities_manager.remove_config(base_entity.id)
except ValueError as e:
await processing.edit(f'❗️ {e.args[0]}')
return
await processing.edit(f"✅ [ `{base_entity_title}` ] unlinked from {count} entities")
@client.on(events.NewMessage(pattern=r'^[Aa]dd filter \"(.+)\" to \"(.+)\"$'))
async def add_filter(message: Message):
msg: str = message.raw_text
pattern = re.compile(r'^[Aa]dd filter \"(.+)\" to \"(.+)\"$')
match = pattern.match(msg)
if not match:
return
from_word = match.group(1)
to_word = match.group(2)
try:
filters_manager.add_filter(from_word, to_word)
except ValueError as e:
await message.reply(f"❗️ {e.args[0]}")
return
await message.reply(f"✅ **{from_word}** will be edited to **{to_word}** (case insensitive)")
@client.on(events.NewMessage(pattern=r'^[Rr]emove filter \"(.+)\"$'))
async def remove_filter(message: Message):
msg: str = message.raw_text
pattern = re.compile(r'^[Rr]emove filter \"(.+)\"$')
match = pattern.match(msg)
if not match:
return
from_word = match.group(1)
try:
filters_manager.remove_filter(from_word)
except ValueError as e:
await message.reply(f"❗️ {e.args[0]}")
return
await message.reply(f"✅ **{from_word}** filters erased.")
@client.on(events.NewMessage(pattern=r'^[Ff]ilters$'))
async def get_filters(message: Message):
filters = filters_manager.words
if not filters:
await message.reply("❗️ No filters submitted.")
return
text = "📁 Filter list: \n\n"
for key, value in filters:
text += f"**{key}** ➡️ **{value}**"
text += '\n'
await message.reply(text)
@client.on(events.NewMessage(pattern=r'^[Ss]ettings'))
async def get_settings(message: Message):
text = "⚙️ Settings: \n\n"
text += f"`Bot status ` ➡ **{'On' if config_manager.bot_enabled else 'Off'}**\n"
text += f"`Filter words ` ➡ **{'Enabled' if config_manager.get('filter_words') else 'Disabled'}**\n"
text += f"`Add signature` ➡ **{'Enabled' if config_manager.get('add_signature') else 'Disabled'}**\n"
if config_manager.sign:
text += f"`Signature ` ⬇️ \n**{config_manager.sign}**"
else:
text += f"`Signature ` ➡ **Not defined**"
await message.reply(text)
@client.on(events.NewMessage(pattern=r'^[Ll]inks'))
async def get_linked_entities(message: Message):
entities = entities_manager.configs
if not entities:
await message.reply("❗️ There is no linked entities.")
return
text = "🖇 Linked entities: \n\n"
for key, value in entities:
text += f"**{key}** ➡️ **{value}**"
text += '\n'
await message.reply(text)
@client.on(events.NewMessage(pattern=r'^[Oo](:?n|ff)$'))
async def change_bot_status(message: Message):
command = message.raw_text.lower()
if command == 'on':
config_manager.change('bot_enabled', True)
await message.reply('👀 Bot turned on')
return
elif command == 'off':
config_manager.change('bot_enabled', False)
await message.reply('😴 Bot turned off')
return
@client.on(events.NewMessage(pattern=r'^[Ff]ilters [Oo](:?n|ff)$'))
async def change_filters_status(message: Message):
msg: str = message.raw_text
pattern = re.compile(r'^[Ff]ilters ([Oo](:?n|ff))$')
match = pattern.match(msg)
if not match:
return
command = match.group(1).lower()
if command == 'on':
config_manager.change('filter_words', True)
await message.reply('✅ Filter words enabled')
return
elif command == 'off':
config_manager.change('filter_words', False)
await message.reply('✅ Filter words disabled')
return
@client.on(events.NewMessage(pattern=r'^[Ss]ign [Oo](:?n|ff)$'))
async def change_signature_status(message: Message):
msg: str = message.raw_text
pattern = re.compile(r'^[Ss]ign ([Oo](:?n|ff))$')
match = pattern.match(msg)
if not match:
return
command = match.group(1).lower()
if command == 'on':
config_manager.change('add_signature', True)
await message.reply('✅ Adding signature enabled')
return
elif command == 'off':
config_manager.change('add_signature', False)
await message.reply('✅ Adding signature disabled')
return
@client.on(events.NewMessage(pattern=r'^[Ss]ign text (.+)$'))
async def change_signature_text(message: Message):
msg: str = message.raw_text
pattern = re.compile(r'^[Ss]ign text (.+)$')
match = pattern.match(msg)
if not match:
return
signature = match.group(1).lower()
config_manager.change('signature', signature)
await message.reply(f'✅ Signature updated:\n{signature}')
@client.on(events.NewMessage(pattern=r'^[Hh]elp$'))
async def get_help(message: Message):
with open('help.txt', 'r') as f:
await message.reply(f.read(), parse_mode='html')
return
client.run_until_disconnected()