forked from JamezQ/u413lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
u413lib.py
196 lines (188 loc) · 6.49 KB
/
u413lib.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# u413lib.py
#
# Copyright 2011 James McClain <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
# TODO #######################
#
# Emotes in chat return extra spaces, fix that
#
# Make a __action__ method, adding channels, users, or so on.
# Make client.login() automatically append client.channels if True
# Make client.joinchat() append to client.chatters[]
# Make a log() method to write all chat to a file
#
# client.joinchat() gets userlist in that chat.
# Crases on /users and /help
#
# Make joinchat join a chat if client.channels does contain the joinchat
# channel.
#
# Make all client.joinchat() just a link to client.chatters[]
# Make chat.get (without ()) equal the last chat.get()
#
# Find out char limits for post/title/reply/chat and embed those limits in u413lib
###############################
import urllib2
import json
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
class createclient(object):
"""create a client, with a cookiejar"""
def __init__(self,user=False,password=False):
self.o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( self.o )
self.loggedin = False
if user and password:
self.login(user,password)
def login(self,username,password):
"""Attempt to login, return True if succesful, False otherwise"""
data = self.sendRawCommand('login '+username+' '+password)
data = json.loads(data)
data = data['DisplayArray'][0]['Text']
if "You are already" in data:
self.loggedin = True
return True
elif "You are now" in data:
self.loggedin = True
return True
else:
self.loggedin = False
return False
def sendRawCommand(self,command):
"""Send a raw command and get raw json back"""
req = urllib2.Request("http://u413.com/Terminal/ExecuteCommand",
headers = {
"Content-Type": "application/json",
"Accept": "*/*",
"User-Agent": "my-python-app/1",
},
data = '''{"CommandString":"'''+command+'''"}''')
a = self.o.open(req)
return a.read()
def getRawChat(self,channel):
"""Get raw json back from a chat update"""
channel = channel.upper()
req = urllib2.Request("http://u413.com/Terminal/MainUpdate",
headers = {
"Content-Type": "application/json",
"Accept": "*/*",
"User-Agent": "my-python-app/1",
},
data = '''[{"Channel": "'''+channel+'''","Minimized": false}]''')
a = self.o.open(req)
return a.read()
def joinchat(self,channel):
"""Create a chatter object"""
channel = channel.upper()
return self.__joinchat__(channel,self)
class __joinchat__(object):
def __init__(self,channel,me):
self.channel = channel
self.me = me
def get(self):
"""Return parsed updated chat, if no updates, return false"""
chat = parse_chat(self.me.getRawChat(self.channel))
if chat:
return chat[self.channel]
else:
return False
def send(self,chatstring):
"""Send string to chat chatter is in"""
chatstring = unicode(chatstring)
chatstring = make_send_safe(chatstring)
cmd = "channel "
cmd += self.channel
cmd += ' '
cmd += chatstring
cmd = cmd.encode('utf-8')
self.me.sendRawCommand(cmd)
def parse_chat(parsedata):
"""Parse chat data, put in dictionary"""
parsedata = json.loads(parsedata)
parsed_chat_data = {}
for channel in parsedata['ChannelDisplayArray']:
messagelist = []
for Text in parsedata['ChannelDisplayArray'][channel]:
messagelist.append(Text['Text'])
for message in range(len(messagelist)):
messagelist[message] = BeautifulSoup(messagelist[message])
i = 0
for message in messagelist:
message_dict = {}
# Get Message Type
if message.contents[0] == "-= ":
message_dict['Type'] = u"Announcement"
elif message.contents[0] == "<":
message_dict['Type'] = u"Message"
else:
message_dict['Type'] = u"Emote"
# Get username
if message_dict['Type'] is u"Message":
message_dict['User'] = message.contents[1].contents[0]
elif message_dict['Type'] is u"Emote":
message_dict['User'] = message.contents[0].contents[1].\
contents[0]
elif message_dict['Type'] is u"Announcement":
message_dict['User'] = message.contents[1].contents[0]
# Get Message
message_dict['Msg'] = ''
if message_dict['Type'] is u"Message":
for text in message.contents[2:-1]:
try:
message_dict['Msg'] += text.contents[0]
except AttributeError:
message_dict['Msg'] += text
except IndexError:
if str(text) == "<br />":
message_dict['Msg'] += '\n'
else:
raise
message_dict['Msg'] = message_dict['Msg'][5:-1]
if message_dict['Msg'][-1] == " ":
message_dict['Msg'] = message_dict['Msg'][:-1]
elif message_dict['Type'] is u"Emote":
for text in message.contents[1:-1]:
try:
message_dict['Msg'] += text.contents[0]
except AttributeError:
message_dict['Msg'] += text
except IndexError:
if str(text) == "<br />":
message_dict['Msg'] += '\n'
else:
raise
if message_dict['Msg'][-1] == " ":
message_dict['Msg'] = message_dict['Msg'][:-1]
elif message_dict['Type'] is u"Announcement":
message_dict['Msg'] += message.contents[2][1:-4]
#Get Timestamps
message_dict['Timestamp'] = message.contents[-1].contents[0]
message_dict['Msg'] = unicode(BeautifulStoneSoup(message_dict['Msg'],convertEntities=BeautifulStoneSoup.HTML_ENTITIES ))
message_dict['User'] = unicode(BeautifulStoneSoup(message_dict['User'],convertEntities=BeautifulStoneSoup.HTML_ENTITIES ))
message_dict['Msg'] = message_dict['Msg'].replace("U413.com","www.U413.com")
messagelist[i] = message_dict
i += 1
parsed_chat_data[channel] = messagelist
return parsed_chat_data
def make_send_safe(text):
"""Make text safe to send to u413"""
text = text.replace('\\',"\\\\")
text = text.replace('"','''\\"''')
return text