-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
201 lines (161 loc) · 5.54 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
#!/usr/bin/python
###################################################################
# HexBot - a heavily modified version of asdofindia's telegram bot#
# #
# Author: Firaenix, Hexane #
###################################################################
from threading import Thread
import time
import sys
import traceback
import subprocess
import os
from multiprocessing.pool import ThreadPool
# SDK and bot related modules
from sdk import msg
import pluginComponent
# global variables
_pathtotg = '../tg/bin/' #include trailing slash. I don't know if '~' notation works
etcDir = "plugin/etc/"
pool = ThreadPool(processes=100)
_proc = None
tgin = None
lastmessage = ''
globalGroup = ""
#this function checks for spam by comparing current message to last message
def mymessage(message):
global lastmessage
if (message == lastmessage):
return True
else:
return False
def AI(group,peer,message):
messagelist = message.split(" ");
if "!" in messagelist[0]:
messagelist[0] = messagelist[0].lower()
message = " ".join(messagelist)
try:
if mymessage(message):
return None
replyrequired = False
reply = None
if group is None:
replyrequired = True
tgin = _proc.stdin
reply = pluginComponent.callmodule(message, [tgin, group, peer])
if reply is not None:
tgin = _proc.stdin
submit_msg(group,peer,reply, tgin)
except:
err = traceback.print_exc()
tgin = _proc.stdin
submit_msg(group, peer, err, tgin)
def spam(message):
if (message == lastmessage):
return True
else:
return False
#Returns the message back to the group.
def submit_msg(group,peer,message, tgin):
global lastmessage
tgin = _proc.stdin
lastmessage = msg.send_msg(group, peer, message, tgin)
#Reading all input, reads colours of text to determine where message is sent from.
def bot():
COLOR_RED = "\033[0;31m"
COLOR_REDB = "\033[1;31m"
COLOR_NORMAL = "\033[0m"
COLOR_GREEN = "\033[32;1m"
COLOR_GREY = "\033[37;1m"
COLOR_YELLOW = "\033[33;1m"
COLOR_BLUE = "\033[34;1m"
COLOR_MAGENTA = "\033[35;1m"
COLOR_CYAN = "\033[36;1m"
COLOR_LCYAN = "\033[0;36m"
COLOR_INVERSE = "\033[7m"
global _proc
global _tgin
_proc = subprocess.Popen([_pathtotg+'telegram-cli','-k',_pathtotg+'../tg-server.pub'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
tgin = _proc.stdin
lastmessage = None
multiline = False
for line in iter(_proc.stdout.readline,''):
if multiline and line != None and message != None:
message += line
message = message.decode("UTF-8")
if line.endswith('[0m\n'):
message = message.rstrip('[0m\n')
multiline = False
else:
if ((COLOR_YELLOW+" is now online" in line) or (COLOR_YELLOW+" is now offline" in line) or (COLOR_YELLOW+": 0 unread" in line)):
pass
#Outputs all text chat
#NECESSARY FOR PROCESSING COMMANDS, ETC.
print line.rstrip()
group = None
peer = None
message = None
try:
#Checks the colour of the stdout line
if ((COLOR_BLUE+" >>>" in line) and (COLOR_BLUE+"[" in line) and ("!" in line)):
peer = line.split(COLOR_RED)[1].split(COLOR_NORMAL)[0]
message = line.split(COLOR_BLUE+" >>> ")[1].split("\033")[0]
if not line.endswith("[0m\n"):
multiline = True
if ((COLOR_GREEN+" >>>" in line) and ("!" in line)):
group = line.split(COLOR_MAGENTA)[2].split(COLOR_NORMAL)[0]
peer = line.split(COLOR_RED)[1].split(COLOR_NORMAL)[0]
message = line.split(COLOR_GREEN+" >>> ")[1].strip(COLOR_NORMAL).split("\033")[0]
if not line.endswith("[0m\n"):
multiline = True
if ((COLOR_BLUE+" >>>" in line) and (COLOR_MAGENTA+"[" in line)):
group=line.split(COLOR_MAGENTA)[2].split(COLOR_NORMAL)[0]
globalGroup = group
#Splits the line to display the user name.
#The username is displayed after the group name, separated my the letter 'm' Always,
#Then strip the " [0" Which is displayed after the username.
#rstrip() to remove final whitespace
peer = line.split(group)[1].split('m')[2].strip('[0').rstrip()
message = line.split(COLOR_BLUE+" >>> ")[1].strip(COLOR_NORMAL).split("\033")[0]
if not line.endswith("[0m\n"):
multiline = True
if COLOR_GREY in line and "*** Lost connection to server..." in line:
print "Detected connection to server loss, restarting bot..."
#If the bot loses connection, restart the bot.
subprocess.call('killall python2.7; killall telegram-cli; python bot.py')
except IndexError:
print "Error: Change colour levels"
#Calls the AI function to read the input, from there, calls the plugins
if( ((group is not None) or (peer is not None)) and (message is not None)):
#adds the command to a new thread
pool.apply_async(AI, (group, peer, message,))
#Cleans up the root dir on startup of all logs.
def cleanupFiles():
#clean up downloads directory
folder = etcDir+'downloads/'
if not os.path.exists(folder):
os.makedirs(folder)
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
print file_path
try:
if os.path.isfile(file_path):
print 'deleting'
os.remove(file_path)
except Exception, e:
print e
def main():
#cleans up the files on every run
cleanupFiles()
botthread = Thread(target = bot)
botthread.start()
#Writes current unix time to file
unixtime = str(int(time.time()))
f = open(etcDir+"unixfile","w")
f.write(unixtime)
f.close()
#Pass in True as this is only called on First Run
pluginComponent.getPlugins(True)
botthread.join()
if __name__ == "__main__":
main()