forked from SignoreOscuro/telegram-forward-bot
-
Notifications
You must be signed in to change notification settings - Fork 4
/
bot.py
executable file
·297 lines (239 loc) · 10.3 KB
/
bot.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import sys
import telepot
import time
import logging
import re
from logging.config import fileConfig
from telepot.loop import MessageLoop
from telepot.exception import TelegramError
chats = {}
chat_config = {}
TOKEN = ""
PASSWORD = "changeme"
def load_from_files():
global chats
global chat_config
if not os.path.isfile('chats.json'):
save_status({})
if not os.path.isfile('chat_config.json'):
save_chat_config({})
with open('chats.json', 'r') as f:
chats = json.load(f)
with open('chat_config.json', 'r') as f:
chat_config = json.load(f)
def save_data(name, obj):
if os.path.isfile(name +".bak"):
os.remove(name +".bak")
os.rename(os.path.realpath(name), os.path.realpath(name)+".bak")
with open(name, 'w') as f:
f.write(json.dumps(obj, indent =4, sort_keys=True))
def save_chat_config(obj):
save_data('chat_config.json', obj)
def save_status(obj):
save_data('chats.json',obj)
def get_chat_config_data(id, key, default):
if not str(id) in chat_config:
return default
if not key in chat_config[str(id)]:
return default
return chat_config[str(id)][key]
def chat_config_update(id, data, name):
if not str(id) in chat_config:
chat_config[str(id)] = {}
chat_config[str(id)].update(data)
chat_config[str(id)].update({ 'name' : name})
save_chat_config(chat_config)
def is_allowed(msg):
if msg['chat']['type'] == 'channel':
return True #all channel admins are allowed to use the bot (channels don't have sender info)
if 'from' in msg:
return get_chat_config_data(msg['from']['id'], 'allowed', False)
return False
def get_name(msg):
if msg['chat']['type'] == "private":
return "Personal chat with " + msg['chat']['first_name'] + ((" " + msg['chat']['last_name']) if 'last_name' in msg['chat'] else "")
else:
return msg['chat']['title']
def delete_source_message(chat_id,msg):
keep = msg['chat']['type'] == 'private' or get_chat_config_data(chat_id, 'keepMessages', False)
if not keep:
try:
bot.deleteMessage(telepot.message_identifier(msg))
except TelegramError as ex:
logging.error("Unable to delete source message : " + str(ex) + " " + str(msg))
if 'from' in msg:
try:
bot.sendMessage(msg['from']['id'], "Unable to delete source message : " + str(ex) + " " + str(msg))
except TelegramError as ex1:
# If user does not have started a conversation with bot the sendMessage will fail
pass
def cmd_addme(chat_id, msg, txt):
if msg['chat']['type'] != 'private':
bot.sendMessage(chat_id, "This command is meant to be used only on personal chats.")
delete_source_message(chat_id,msg)
else:
used_password = " ".join(txt.strip().split(" ")[1:])
if used_password == PASSWORD:
chat_config_update(msg['from']['id'], { 'allowed' : True } , get_name(msg) )
bot.sendMessage(chat_id, msg['from']['first_name'] + ", you have been registered " +
"as an authorized user of this bot.")
else:
logging.error("Wrong password : " + str(msg))
bot.sendMessage(chat_id, "Wrong password.")
def cmd_add_tag(chat_id, msg, txt):
txt_split = txt.strip().split(" ")
if len(txt_split) == 2 and "#" == txt_split[1][0]:
tag = txt_split[1].lower()
name = get_name(msg)
chats[tag] = {'id': chat_id, 'name' : name}
bot.sendMessage(chat_id, name + " added with tag " + tag)
save_status(chats)
delete_source_message(chat_id,msg)
else:
bot.sendMessage(chat_id, "Incorrect format. It should be _/add #{tag}_", parse_mode="Markdown")
def cmd_rm_tag(chat_id, msg, txt):
txt_split = txt.strip().split(" ")
if len(txt_split) == 2 and "#" == txt_split[1][0]:
tag = txt_split[1].lower()
if tag in chats:
if chats[tag]['id'] == chat_id:
del chats[tag]
bot.sendMessage(chat_id, "Tag "+tag+" deleted from taglist.")
save_status(chats)
else:
bot.sendMessage(chat_id, "You can't delete a chat's tag from a different chat.")
else:
bot.sendMessage(chat_id, "Tag doesn't exist on TagList")
else:
bot.sendMessage(chat_id, "Incorrect format. It should be _/rm #{tag}_", parse_mode="Markdown")
def do_forward(chat_id, msg, txt, fwd_tags):
txt_split = re.split("[ \n\r\t]", txt)
i = 0
while i < len(txt_split) and (len(txt_split[i]) == 0 or txt_split[i][0] == "#"):
if (len(txt_split[i]) > 0):
tag = txt_split[i]
fwd_tags.append(tag.lower())
if txt.startswith(tag):
txt = txt[len(tag):].strip(" \n\r\t")
else:
txt = txt.strip(" \n\r\t")
i+=1
if len(txt) > 0 or 'reply_to_message' in msg:
approved = []
rejected = []
caption = get_chat_config_data(chat_id, "caption", "")
for tag in fwd_tags:
if tag in chats:
if chats[tag]['id'] != chat_id:
approved.append(chats[tag]['name'])
if caption != "":
bot.sendMessage(chats[tag]['id'], caption)
if not 'reply_to_message' in msg or len(txt) > 0:
bot.forwardMessage(chats[tag]['id'], chat_id, msg['message_id'])
if 'reply_to_message' in msg:
bot.forwardMessage(chats[tag]['id'], chat_id, msg['reply_to_message']['message_id'])
if len(txt) == 0:
delete_source_message(chat_id, msg)
else:
rejected.append(tag)
if len(rejected) > 0:
bot.sendMessage(chat_id, "Failed to send messages to tags <i>" + ", ".join(rejected) + "</i>", parse_mode="HTML")
else:
# Send Failed message to user to don't flood the group
if 'from' in msg:
bot.sendMessage(msg['from']['id'], "Failed to send a message only with tags which is not a reply to another message : " + txt)
else:
bot.sendMessage(chat_id, "Failed to send a message only with tags which is not a reply to another message" )
def handle(msg):
logging.debug("Message: " + str(msg))
# Add person as allowed
content_type, chat_type, chat_id = telepot.glance(msg)
txt = ""
if 'text' in msg:
txt = txt + msg['text'].strip(" \n\r\t")
elif 'caption' in msg:
txt = txt + msg['caption'].strip(" \n\r\t")
# Commands that are valid only on groups and personal chats.
if msg['chat']['type'] != 'channel':
if "/addme" == txt[:6]:
cmd_addme(chat_id, msg, txt)
return
elif is_allowed(msg):
if "/rmme" == txt[:5]:
chat_config_update(msg['from']['id'], { 'allowed' : False } , get_name(msg) )
bot.sendMessage(chat_id, "Your permission for using the bot was removed successfully.")
return
elif "/chatlist" == txt:
response = "<b>Chat List</b>"
for id in chat_config.keys():
config = chat_config[id]
response = response + "\n<b>" + str(id) + "</b>: <i>" + str(config) + "</i>"
bot.sendMessage(chat_id, response, parse_mode="HTML")
return
elif "/taglist" == txt:
tags_names = []
for tag, chat in chats.items():
tags_names.append( (tag, chat['name']))
response = "<b>TagList</b>"
for (tag, name) in sorted(tags_names):
response = response + "\n<b>" + tag + "</b>: <i>" + name + "</i>"
bot.sendMessage(chat_id, response, parse_mode="HTML")
return
elif "/reload" == txt:
load_from_files()
return
if is_allowed(msg) and txt != "":
fwd_tags = []
if str(chat_id) in chat_config:
if 'autofwd' in chat_config[str(chat_id)]:
autofwd = chat_config[str(chat_id)]["autofwd"].split(" ")
fwd_tags.extend(autofwd)
if "/add " == txt[:5]:
cmd_add_tag(chat_id, msg, txt)
delete_source_message(chat_id, msg)
elif "/rm " == txt[:4]:
cmd_rm_tag(chat_id, msg, txt)
delete_source_message(chat_id, msg)
elif "/fwdcaption" == txt[:11]:
caption = txt[11:].strip(" \n\r\t")
chat_config_update(chat_id, { 'caption' : caption }, get_name(msg))
delete_source_message(chat_id, msg)
elif "/autofwd" == txt:
chat_config_update(chat_id, { 'autofwd' : "" }, get_name(msg))
delete_source_message(chat_id, msg)
elif "/autofwd" == txt[:9]:
txt_split = txt[9:].strip(" \n\r\t").lower().split(" ")
chat_config_update(chat_id, { 'autofwd' : " ".join(txt_split).strip() }, get_name(msg))
delete_source_message(chat_id, msg)
elif "#" == txt[0] or len(fwd_tags) > 0:
do_forward(chat_id, msg, txt, fwd_tags)
def handle_with_try(msg):
try:
handle(msg)
except Exception as ex:
logging.exception("Error")
fileConfig('bot_logging.ini')
load_from_files()
if os.path.isfile('config.json'):
with open('config.json', 'r') as f:
config = json.load(f)
if config['token'] == "":
sys.exit("No token defined. Define it in a file called config.json.")
if config['password'] == "":
logging.warning("Empty Password for registering to use the bot." +
" It could be dangerous, because anybody could use this bot" +
" and forward messages to the channels associated to it")
TOKEN = config['token']
PASSWORD = config['password']
else:
sys.exit("No config file found. Remember changing the name of config-sample.json to config.json")
bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle_with_try).run_as_thread()
logging.info('Listening ...')
# Keep the program running.
while 1:
time.sleep(10)