Use unicode string literals
This commit is contained in:
parent
4093568234
commit
fae4c648ee
|
@ -262,7 +262,6 @@ class SpectrumBackend:
|
|||
|
||||
def handleConvMessagePayload(self, data):
|
||||
payload = protocol_pb2.ConversationMessage()
|
||||
self.logger.error("handleConvMessagePayload")
|
||||
if (payload.ParseFromString(data) == False):
|
||||
#TODO: ERROR
|
||||
return
|
||||
|
|
40
bot.py
40
bot.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -30,30 +30,30 @@ import os
|
|||
import utils
|
||||
|
||||
class Bot():
|
||||
def __init__(self, session, name = "Bot"):
|
||||
def __init__(self, session, name = u"Bot"):
|
||||
self.session = session
|
||||
self.name = name
|
||||
|
||||
self.commands = {
|
||||
"help": self._help,
|
||||
"prune": self._prune,
|
||||
"groups": self._groups,
|
||||
"getgroups": self._getgroups
|
||||
u"help": self._help,
|
||||
u"prune": self._prune,
|
||||
u"groups": self._groups,
|
||||
u"getgroups": self._getgroups
|
||||
}
|
||||
|
||||
def parse(self, message):
|
||||
args = message.split(" ")
|
||||
args = message.split(u" ")
|
||||
cmd = args.pop(0)
|
||||
|
||||
if cmd[0] == '\\':
|
||||
if cmd[0] == u'\\':
|
||||
try:
|
||||
self.call(cmd[1:], args)
|
||||
except KeyError:
|
||||
self.send("invalid command")
|
||||
self.send(u"invalid command")
|
||||
except TypeError:
|
||||
self.send("invalid syntax")
|
||||
self.send(u"invalid syntax")
|
||||
else:
|
||||
self.send("a valid command starts with a backslash")
|
||||
self.send(u"a valid command starts with a backslash")
|
||||
|
||||
def call(self, cmd, args = []):
|
||||
func = self.commands[cmd]
|
||||
|
@ -71,7 +71,7 @@ class Bot():
|
|||
|
||||
# commands
|
||||
def _help(self):
|
||||
self.send("""following bot commands are available:
|
||||
self.send(u"""following bot commands are available:
|
||||
\\help show this message
|
||||
\\prune clear your buddylist
|
||||
|
||||
|
@ -86,7 +86,7 @@ following group commands are available
|
|||
def _prune(self):
|
||||
self.session.buddies.prune()
|
||||
self.session.updateRoster()
|
||||
self.send("buddy list cleared")
|
||||
self.send(u"buddy list cleared")
|
||||
|
||||
def _groups(self):
|
||||
for group in self.session.groups:
|
||||
|
@ -96,9 +96,9 @@ following group commands are available
|
|||
except KeyError:
|
||||
nick = buddy
|
||||
|
||||
self.send(self.session.groups[group].id + "@" + self.session.backend.spectrum_jid + " " + self.session.groups[group].subject + " Owner: " + nick )
|
||||
self.send(self.session.groups[group].id + u"@" + self.session.backend.spectrum_jid + u" " + self.session.groups[group].subject + u" Owner: " + nick )
|
||||
|
||||
def _getgroups(self):
|
||||
#self.session.call("group_getGroups", ("participating",))
|
||||
#self.session.call(u"group_getGroups", (u"participating",))
|
||||
self.session.requestGroupsList(self.session._updateGroups)
|
||||
|
||||
|
|
48
buddy.py
48
buddy.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -33,7 +33,7 @@ class Buddy():
|
|||
self.owner = owner
|
||||
self.number = number
|
||||
self.groups = groups
|
||||
self.image_hash = image_hash if image_hash is not None else ""
|
||||
self.image_hash = image_hash if image_hash is not None else u""
|
||||
self.statusMsg = u""
|
||||
self.lastseen = 0
|
||||
self.presence = 0
|
||||
|
@ -46,7 +46,7 @@ class Buddy():
|
|||
self.image_hash = image_hash
|
||||
|
||||
def __str__(self):
|
||||
return "%s (nick=%s)" % (self.number, self.nick)
|
||||
return u"%s (nick=%s)" % (self.number, self.nick)
|
||||
|
||||
class BuddyList(dict):
|
||||
|
||||
|
@ -62,20 +62,20 @@ class BuddyList(dict):
|
|||
for buddy in buddies:
|
||||
number = buddy.buddyName
|
||||
nick = buddy.alias
|
||||
statusMsg = buddy.statusMessage.decode('utf-8')
|
||||
statusMsg = buddy.statusMessage.decode(u'utf-8')
|
||||
groups = [g for g in buddy.group]
|
||||
image_hash = buddy.iconHash
|
||||
self[number] = Buddy(self.owner, number, nick, statusMsg,
|
||||
groups, image_hash)
|
||||
|
||||
self.logger.debug("Update roster")
|
||||
self.logger.debug(u"Update roster")
|
||||
|
||||
# old = self.buddies.keys()
|
||||
# self.buddies.load()
|
||||
# new = self.buddies.keys()
|
||||
# contacts = new
|
||||
contacts = self.keys()
|
||||
contacts.remove('bot')
|
||||
contacts.remove(u'bot')
|
||||
|
||||
if self.synced == False:
|
||||
self.session.sendSync(contacts, delta = False, interactive = True)
|
||||
|
@ -84,11 +84,11 @@ class BuddyList(dict):
|
|||
# add = set(new) - set(old)
|
||||
# remove = set(old) - set(new)
|
||||
|
||||
# self.logger.debug("Roster remove: %s", str(list(remove)))
|
||||
self.logger.debug("Roster add: %s", str(list(contacts)))
|
||||
# self.logger.debug(u"Roster remove: %s", str(list(remove)))
|
||||
self.logger.debug(u"Roster add: %s", str(list(contacts)))
|
||||
|
||||
# for number in remove:
|
||||
# self.backend.handleBuddyChanged(self.user, number, "", [],
|
||||
# self.backend.handleBuddyChanged(self.user, number, u"", [],
|
||||
# protocol_pb2.STATUS_NONE)
|
||||
# self.backend.handleBuddyRemoved(self.user, number)
|
||||
# self.unsubscribePresence(number)
|
||||
|
@ -97,16 +97,16 @@ class BuddyList(dict):
|
|||
buddy = self[number]
|
||||
self.backend.handleBuddyChanged(self.user, number, buddy.nick,
|
||||
buddy.groups, protocol_pb2.STATUS_NONE,
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else "")
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else u"")
|
||||
self.session.subscribePresence(number)
|
||||
self.logger.debug("%s is requesting statuses of: %s", self.user, contacts)
|
||||
self.logger.debug(u"%s is requesting statuses of: %s", self.user, contacts)
|
||||
self.session.requestStatuses(contacts, success = self.onStatus)
|
||||
|
||||
def onStatus(self, contacts):
|
||||
self.logger.debug("%s received statuses of: %s", self.user, contacts)
|
||||
self.logger.debug(u"%s received statuses of: %s", self.user, contacts)
|
||||
for number, (status, time) in contacts.iteritems():
|
||||
buddy = self[number]
|
||||
buddy.statusMsg = status.decode('utf-8')
|
||||
buddy.statusMsg = status.decode(u'utf-8')
|
||||
self.updateSpectrum(buddy)
|
||||
|
||||
|
||||
|
@ -124,9 +124,9 @@ class BuddyList(dict):
|
|||
self.session.sendSync([number], delta = True, interactive = True)
|
||||
self.session.subscribePresence(number)
|
||||
self.session.requestStatuses([number], success = self.onStatus)
|
||||
buddy = Buddy(self.owner, number, nick, "", groups, image_hash)
|
||||
buddy = Buddy(self.owner, number, nick, u"", groups, image_hash)
|
||||
self[number] = buddy
|
||||
self.logger.debug("Roster add: %s", buddy)
|
||||
self.logger.debug(u"Roster add: %s", buddy)
|
||||
|
||||
self.updateSpectrum(buddy)
|
||||
return buddy
|
||||
|
@ -134,7 +134,7 @@ class BuddyList(dict):
|
|||
def updateSpectrum(self, buddy):
|
||||
if buddy.presence == 0:
|
||||
status = protocol_pb2.STATUS_NONE
|
||||
elif buddy.presence == 'unavailable':
|
||||
elif buddy.presence == u'unavailable':
|
||||
status = protocol_pb2.STATUS_AWAY
|
||||
else:
|
||||
status = protocol_pb2.STATUS_ONLINE
|
||||
|
@ -142,18 +142,18 @@ class BuddyList(dict):
|
|||
statusmsg = buddy.statusMsg
|
||||
if buddy.lastseen != 0:
|
||||
timestamp = time.localtime(buddy.lastseen)
|
||||
statusmsg += time.strftime("\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp)
|
||||
statusmsg += time.strftime(u"\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp)
|
||||
|
||||
self.backend.handleBuddyChanged(self.user, buddy.number, buddy.nick,
|
||||
buddy.groups, status, statusMessage = statusmsg,
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else "")
|
||||
iconHash = buddy.image_hash if buddy.image_hash is not None else u"")
|
||||
|
||||
|
||||
def remove(self, number):
|
||||
try:
|
||||
buddy = self[number]
|
||||
del self[number]
|
||||
self.backend.handleBuddyChanged(self.user, number, "", [],
|
||||
self.backend.handleBuddyChanged(self.user, number, u"", [],
|
||||
protocol_pb2.STATUS_NONE)
|
||||
self.backend.handleBuddyRemoved(self.user, number)
|
||||
self.session.unsubscribePresence(number)
|
||||
|
|
24
group.py
24
group.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -34,12 +34,12 @@ class Group():
|
|||
self.backend = backend
|
||||
self.user = user
|
||||
|
||||
self.nick = "me"
|
||||
self.nick = u"me"
|
||||
# Participants is a number -> nickname dict
|
||||
self.participants = {}
|
||||
|
||||
def addParticipants(self, participants, buddies, yourNumber):
|
||||
"""
|
||||
u"""
|
||||
Adds participants to the group.
|
||||
|
||||
Args:
|
||||
|
@ -48,14 +48,14 @@ class Group():
|
|||
- yourNumber: The number you are using
|
||||
"""
|
||||
for jid in participants:
|
||||
number = jid.split('@')[0]
|
||||
number = jid.split(u'@')[0]
|
||||
try:
|
||||
nick = buddies[number].nick
|
||||
except KeyError:
|
||||
nick = number
|
||||
if number == yourNumber:
|
||||
nick = self.nick
|
||||
if nick == "":
|
||||
if nick == u"":
|
||||
nick = number
|
||||
self.participants[number] = nick
|
||||
|
||||
|
@ -72,7 +72,7 @@ class Group():
|
|||
|
||||
def removeParticipants(self, participants):
|
||||
for jid in participants:
|
||||
number = jid.split('@')[0]
|
||||
number = jid.split(u'@')[0]
|
||||
nick = self.participants[number]
|
||||
flags = protocol_pb2.PARTICIPANT_FLAG_NONE
|
||||
self._updateParticipant(number, flags, protocol_pb2.STATUS_NONE)
|
||||
|
@ -88,7 +88,7 @@ class Group():
|
|||
self._updateParticipant(number, flags, protocol_pb2.STATUS_ONLINE, new_nick)
|
||||
self.participants[number] = new_nick
|
||||
|
||||
def _updateParticipant(self, number, flags, status, newNick = ""):
|
||||
def _updateParticipant(self, number, flags, status, newNick = u""):
|
||||
nick = self.participants[number]
|
||||
# Notice the status message is the buddy's number
|
||||
if self.joined:
|
||||
|
|
20
reader.py
20
reader.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -24,19 +24,19 @@ __email__ = "post@steffenvogel.de"
|
|||
import time
|
||||
|
||||
def get_token(number, timeout = 30):
|
||||
file = open('tokens')
|
||||
file = open(u'tokens')
|
||||
file.seek(-1, 2)
|
||||
|
||||
count = 0
|
||||
while count < timeout:
|
||||
line = file.readline()
|
||||
|
||||
if line in ["", "\n"]:
|
||||
if line in [u"", u"\n"]:
|
||||
time.sleep(1)
|
||||
count += 1
|
||||
continue
|
||||
else:
|
||||
t, n, tk = line[:-1].split("\t")
|
||||
t, n, tk = line[:-1].split(u"\t")
|
||||
|
||||
if (n == number):
|
||||
file.close()
|
||||
|
@ -45,4 +45,4 @@ def get_token(number, timeout = 30):
|
|||
file.close()
|
||||
|
||||
|
||||
print get_token("4917696978528")
|
||||
print get_token(u"4917696978528")
|
||||
|
|
418
session.py
418
session.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -56,14 +56,14 @@ class Session(YowsupApp):
|
|||
def __init__(self, backend, user, legacyName, extra):
|
||||
super(Session, self).__init__()
|
||||
self.logger = logging.getLogger(self.__class__.__name__)
|
||||
self.logger.info("Created: %s", legacyName)
|
||||
self.logger.info(u"Created: %s", legacyName)
|
||||
|
||||
self.backend = backend
|
||||
self.user = user
|
||||
self.legacyName = legacyName
|
||||
|
||||
self.status = protocol_pb2.STATUS_NONE
|
||||
self.statusMessage = ''
|
||||
self.statusMessage = u''
|
||||
|
||||
self.groups = {}
|
||||
self.gotGroupList = False
|
||||
|
@ -86,21 +86,21 @@ class Session(YowsupApp):
|
|||
self.bot = Bot(self)
|
||||
|
||||
self.imgMsgId = None
|
||||
self.imgPath = ""
|
||||
self.imgPath = u""
|
||||
self.imgBuddy = None
|
||||
self.imgType = ""
|
||||
self.imgType = u""
|
||||
|
||||
|
||||
def __del__(self): # handleLogoutRequest
|
||||
self.logout()
|
||||
|
||||
def logout(self):
|
||||
self.logger.info("%s logged out", self.user)
|
||||
self.logger.info(u"%s logged out", self.user)
|
||||
super(Session, self).logout()
|
||||
self.loggedIn = False
|
||||
|
||||
def login(self, password):
|
||||
self.logger.info("%s attempting login", self.user)
|
||||
self.logger.info(u"%s attempting login", self.user)
|
||||
self.password = password
|
||||
self.shouldBeConncted = True
|
||||
super(Session, self).login(self.legacyName, self.password)
|
||||
|
@ -108,33 +108,33 @@ class Session(YowsupApp):
|
|||
def _shortenGroupId(self, gid):
|
||||
# FIXME: might have problems if number begins with 0
|
||||
return gid
|
||||
# return '-'.join(hex(int(s))[2:] for s in gid.split('-'))
|
||||
# return u'-'.join(hex(int(s))[2:] for s in gid.split(u'-'))
|
||||
|
||||
def _lengthenGroupId(self, gid):
|
||||
return gid
|
||||
# FIXME: might have problems if number begins with 0
|
||||
# return '-'.join(str(int(s, 16)) for s in gid.split('-'))
|
||||
# return u'-'.join(str(int(s, 16)) for s in gid.split(u'-'))
|
||||
|
||||
def updateRoomList(self):
|
||||
rooms = []
|
||||
text = []
|
||||
for room, group in self.groups.iteritems():
|
||||
rooms.append([self._shortenGroupId(room), group.subject])
|
||||
text.append(self._shortenGroupId(room) + '@' + self.backend.spectrum_jid + ' :' + group.subject)
|
||||
text.append(self._shortenGroupId(room) + u'@' + self.backend.spectrum_jid + u' :' + group.subject)
|
||||
|
||||
self.logger.debug("Got rooms: %s", rooms)
|
||||
self.logger.debug(u"Got rooms: %s", rooms)
|
||||
self.backend.handleRoomList(rooms)
|
||||
message = "Note, you are a participant of the following groups:\n" +\
|
||||
'\n'.join(text) + '\nIf you do not join them you will lose messages'
|
||||
message = u"Note, you are a participant of the following groups:\n" +\
|
||||
u'\n'.join(text) + u'\nIf you do not join them you will lose messages'
|
||||
#self.bot.send(message)
|
||||
|
||||
def _updateGroups(self, response, request):
|
||||
self.logger.debug('Received groups list %s', response)
|
||||
self.logger.debug(u'Received groups list %s', response)
|
||||
groups = response.getGroups()
|
||||
for group in groups:
|
||||
room = group.getId()
|
||||
owner = group.getOwner().split('@')[0]
|
||||
subjectOwner = group.getSubjectOwner().split('@')[0]
|
||||
owner = group.getOwner().split(u'@')[0]
|
||||
subjectOwner = group.getSubjectOwner().split(u'@')[0]
|
||||
subject = utils.softToUni(group.getSubject())
|
||||
|
||||
if room in self.groups:
|
||||
|
@ -144,7 +144,7 @@ class Session(YowsupApp):
|
|||
oroom.subject = subject
|
||||
else:
|
||||
self.groups[room] = Group(room, owner, subject, subjectOwner, self.backend, self.user)
|
||||
# self.joinRoom(self._shortenGroupId(room), self.user.split("@")[0])
|
||||
# self.joinRoom(self._shortenGroupId(room), self.user.split(u"@")[0])
|
||||
self.groups[room].addParticipants(group.getParticipants().keys(),
|
||||
self.buddies, self.legacyName)
|
||||
|
||||
|
@ -154,8 +154,8 @@ class Session(YowsupApp):
|
|||
while self.groupOfflineQueue[room]:
|
||||
msg = self.groupOfflineQueue[room].pop(0)
|
||||
self.backend.handleMessage(self.user, room, msg[1],
|
||||
msg[0], "", msg[2])
|
||||
self.logger.debug("Send queued group message to: %s %s %s",
|
||||
msg[0], u"", msg[2])
|
||||
self.logger.debug(u"Send queued group message to: %s %s %s",
|
||||
msg[0],msg[1], msg[2])
|
||||
self.gotGroupList = True
|
||||
for room, nick in self.joinRoomQueue:
|
||||
|
@ -169,7 +169,7 @@ class Session(YowsupApp):
|
|||
return
|
||||
room = self._lengthenGroupId(room)
|
||||
if room in self.groups:
|
||||
self.logger.info("Joining room: %s room=%s, nick=%s",
|
||||
self.logger.info(u"Joining room: %s room=%s, nick=%s",
|
||||
self.legacyName, room, nick)
|
||||
|
||||
group = self.groups[room]
|
||||
|
@ -184,24 +184,24 @@ class Session(YowsupApp):
|
|||
group.sendParticipantsToSpectrum(self.legacyName)
|
||||
self.backend.handleSubject(self.user, self._shortenGroupId(room),
|
||||
group.subject, ownerNick)
|
||||
self.logger.debug("Room subject: room=%s, subject=%s",
|
||||
self.logger.debug(u"Room subject: room=%s, subject=%s",
|
||||
room, group.subject)
|
||||
self.backend.handleRoomNicknameChanged(
|
||||
self.user, self._shortenGroupId(room), group.subject
|
||||
)
|
||||
else:
|
||||
self.logger.warn("Room doesn't exist: %s", room)
|
||||
self.logger.warn(u"Room doesn't exist: %s", room)
|
||||
|
||||
def leaveRoom(self, room):
|
||||
if room in self.groups:
|
||||
self.logger.info("Leaving room: %s room=%s", self.legacyName, room)
|
||||
self.logger.info(u"Leaving room: %s room=%s", self.legacyName, room)
|
||||
group = self.groups[room]
|
||||
group.joined = False
|
||||
else:
|
||||
self.logger.warn("Room doesn't exist: %s. Unable to leave.", room)
|
||||
self.logger.warn(u"Room doesn't exist: %s. Unable to leave.", room)
|
||||
|
||||
def _lastSeen(self, number, seconds):
|
||||
self.logger.debug("Last seen %s at %s seconds" % (number, str(seconds)))
|
||||
self.logger.debug(u"Last seen %s at %s seconds" % (number, str(seconds)))
|
||||
if seconds < 60:
|
||||
self.onPresenceAvailable(number)
|
||||
else:
|
||||
|
@ -210,43 +210,43 @@ class Session(YowsupApp):
|
|||
# Called by superclass
|
||||
def onAuthSuccess(self, status, kind, creation,
|
||||
expiration, props, nonce, t):
|
||||
self.logger.info("Auth success: %s", self.user)
|
||||
self.logger.info(u"Auth success: %s", self.user)
|
||||
|
||||
self.backend.handleConnected(self.user)
|
||||
self.backend.handleBuddyChanged(self.user, "bot", self.bot.name,
|
||||
["Admin"], protocol_pb2.STATUS_ONLINE)
|
||||
self.backend.handleBuddyChanged(self.user, u"bot", self.bot.name,
|
||||
[u"Admin"], protocol_pb2.STATUS_ONLINE)
|
||||
if self.initialized == False:
|
||||
self.sendOfflineMessages()
|
||||
#self.bot.call("welcome")
|
||||
#self.bot.call(u"welcome")
|
||||
self.initialized = True
|
||||
self.sendPresence(True)
|
||||
for func in self.loginQueue:
|
||||
func()
|
||||
|
||||
self.logger.debug('Requesting groups list')
|
||||
self.logger.debug(u'Requesting groups list')
|
||||
self.requestGroupsList(self._updateGroups)
|
||||
self.loggedIn = True
|
||||
|
||||
# Called by superclass
|
||||
def onAuthFailed(self, reason):
|
||||
self.logger.info("Auth failed: %s (%s)", self.user, reason)
|
||||
self.logger.info(u"Auth failed: %s (%s)", self.user, reason)
|
||||
self.backend.handleDisconnected(self.user, 0, reason)
|
||||
self.password = None
|
||||
self.loggedIn = False
|
||||
|
||||
# Called by superclass
|
||||
def onDisconnect(self):
|
||||
self.logger.debug('Disconnected')
|
||||
self.backend.handleDisconnected(self.user, 0, 'Disconnected for unknown reasons')
|
||||
self.logger.debug(u'Disconnected')
|
||||
self.backend.handleDisconnected(self.user, 0, u'Disconnected for unknown reasons')
|
||||
|
||||
# Called by superclass
|
||||
def onReceipt(self, _id, _from, timestamp, type, participant, offline, items):
|
||||
self.logger.debug("received receipt, sending ack: " +
|
||||
' '.join(map(str, [_id, _from, timestamp,
|
||||
self.logger.debug(u"received receipt, sending ack: " +
|
||||
u' '.join(map(str, [_id, _from, timestamp,
|
||||
type, participant, offline, items]))
|
||||
)
|
||||
try:
|
||||
buddy = self.buddies[_from.split('@')[0]]
|
||||
buddy = self.buddies[_from.split(u'@')[0]]
|
||||
#self.backend.handleBuddyChanged(self.user, buddy.number.number,
|
||||
# buddy.nick, buddy.groups, protocol_pb2.STATUS_ONLINE)
|
||||
self.backend.handleMessageAck(self.user, buddy.number, self.msgIDs[_id].xmppId)
|
||||
|
@ -259,47 +259,47 @@ class Session(YowsupApp):
|
|||
|
||||
# Called by superclass
|
||||
def onAck(self, _id, _class, _from, timestamp):
|
||||
self.logger.debug('received ack ' +
|
||||
' '.join(map(str, [_id, _class, _from,timestamp,]))
|
||||
self.logger.debug(u'received ack ' +
|
||||
u' '.join(map(str, [_id, _class, _from,timestamp,]))
|
||||
)
|
||||
|
||||
# Called by superclass
|
||||
def onTextMessage(self, _id, _from, to, notify, timestamp, participant,
|
||||
offline, retry, body):
|
||||
self.logger.debug('received TextMessage' +
|
||||
' '.join(map(str, [
|
||||
self.logger.debug(u'received TextMessage' +
|
||||
u' '.join(map(str, [
|
||||
_id, _from, to, notify, timestamp,
|
||||
participant, offline, retry, body
|
||||
]))
|
||||
)
|
||||
buddy = _from.split('@')[0]
|
||||
buddy = _from.split(u'@')[0]
|
||||
messageContent = utils.softToUni(body)
|
||||
self.sendReceipt(_id, _from, None, participant)
|
||||
self.logger.info("Message received from %s to %s: %s (at ts=%s)",
|
||||
self.logger.info(u"Message received from %s to %s: %s (at ts=%s)",
|
||||
buddy, self.legacyName, messageContent, timestamp)
|
||||
if participant is not None: # Group message
|
||||
partname = participant.split('@')[0]
|
||||
partname = participant.split(u'@')[0]
|
||||
self.sendGroupMessageToXMPP(buddy, partname, messageContent,
|
||||
timestamp)
|
||||
else:
|
||||
self.sendMessageToXMPP(buddy, messageContent, timestamp)
|
||||
# isBroadcast always returns false, I'm not sure how to get a broadcast
|
||||
# isBroadcast always returns false, Iu'm not sure how to get a broadcast
|
||||
# message.
|
||||
#if messageEntity.isBroadcast():
|
||||
# self.logger.info("Broadcast received from %s to %s: %s (at ts=%s)",\
|
||||
# self.logger.info(u"Broadcast received from %s to %s: %s (at ts=%s)",\
|
||||
# buddy, self.legacyName, messageContent, timestamp)
|
||||
# messageContent = "[Broadcast] " + messageContent
|
||||
# messageContent = u"[Broadcast] " + messageContent
|
||||
|
||||
# Called by superclass
|
||||
def onImage(self, image):
|
||||
self.logger.debug('Received image message %s', str(image))
|
||||
buddy = image._from.split('@')[0]
|
||||
self.logger.debug('Received image message %su', str(image))
|
||||
buddy = image._from.split('@u')[0]
|
||||
participant = image.participant
|
||||
if image.caption is None:
|
||||
image.caption = ''
|
||||
message = image.url + ' ' + image.caption
|
||||
image.caption = 'u'
|
||||
message = image.url + ' u' + image.caption
|
||||
if participant is not None: # Group message
|
||||
partname = participant.split('@')[0]
|
||||
partname = participant.split('@u')[0]
|
||||
self.sendGroupMessageToXMPP(buddy, partname, message, image.timestamp)
|
||||
else:
|
||||
|
||||
|
@ -308,12 +308,12 @@ class Session(YowsupApp):
|
|||
|
||||
# Called by superclass
|
||||
def onAudio(self, audio):
|
||||
self.logger.debug('Received audio message %s', str(audio))
|
||||
buddy = audio._from.split('@')[0]
|
||||
self.logger.debug('Received audio message %su', str(audio))
|
||||
buddy = audio._from.split('@u')[0]
|
||||
participant = audio.participant
|
||||
message = audio.url
|
||||
if participant is not None: # Group message
|
||||
partname = participant.split('@')[0]
|
||||
partname = participant.split('@u')[0]
|
||||
self.sendGroupMessageToXMPP(buddy, partname, message, audio.timestamp)
|
||||
else:
|
||||
|
||||
|
@ -322,13 +322,13 @@ class Session(YowsupApp):
|
|||
|
||||
# Called by superclass
|
||||
def onVideo(self, video):
|
||||
self.logger.debug('Received video message %s', str(video))
|
||||
buddy = video._from.split('@')[0]
|
||||
self.logger.debug('Received video message %su', str(video))
|
||||
buddy = video._from.split('@u')[0]
|
||||
participant = video.participant
|
||||
|
||||
message = video.url
|
||||
if participant is not None: # Group message
|
||||
partname = participant.split('@')[0]
|
||||
partname = participant.split('@u')[0]
|
||||
self.sendGroupMessageToXMPP(buddy, partname, message, video.timestamp)
|
||||
else:
|
||||
|
||||
|
@ -336,57 +336,57 @@ class Session(YowsupApp):
|
|||
self.sendReceipt(video._id, video._from, None, video.participant)
|
||||
|
||||
def onLocation(self, location):
|
||||
buddy = location._from.split('@')[0]
|
||||
buddy = location._from.split('@u')[0]
|
||||
latitude = location.getLatitude()
|
||||
longitude = location.getLongitude()
|
||||
url = location.getLocationUrl()
|
||||
participant = location.participant
|
||||
|
||||
self.logger.debug("Location received from %s: %s, %s",
|
||||
self.logger.debug(u"Location received from %s: %s, %s",
|
||||
buddy, latitude, longitude)
|
||||
|
||||
if participant is not None: # Group message
|
||||
partname = participant.split('@')[0]
|
||||
partname = participant.split('@u')[0]
|
||||
self.sendGroupMessageToXMPP(buddy, partname, url, location.timestamp)
|
||||
self.sendGroupMessageToXMPP(buddy, partname, 'geo:' + latitude + ',' + longitude,
|
||||
self.sendGroupMessageToXMPP(buddy, partname, 'geo:u' + latitude + ',u' + longitude,
|
||||
location.timestamp)
|
||||
else:
|
||||
|
||||
self.sendMessageToXMPP(buddy, url, location.timestamp)
|
||||
self.sendMessageToXMPP(buddy, 'geo:' + latitude + ',' + longitude,
|
||||
self.sendMessageToXMPP(buddy, 'geo:u' + latitude + ',u' + longitude,
|
||||
location.timestamp)
|
||||
self.sendReceipt(location._id, location._from, None, location.participant, location.timestamp)
|
||||
|
||||
|
||||
# Called by superclass
|
||||
def onVCard(self, _id, _from, name, card_data, to, notify, timestamp, participant):
|
||||
self.logger.debug('received VCard' +
|
||||
' '.join(map(str, [
|
||||
self.logger.debug('received VCardu' +
|
||||
' u'.join(map(str, [
|
||||
_id, _from, name, card_data, to, notify, timestamp, participant
|
||||
]))
|
||||
)
|
||||
buddy = _from.split("@")[0]
|
||||
buddy = _from.split(u"@")[0]
|
||||
if participant is not None: # Group message
|
||||
partname = participant.split('@')[0]
|
||||
self.sendGroupMessageToXMPP(buddy, partname, "Received VCard (not implemented yet)", timestamp)
|
||||
partname = participant.split('@u')[0]
|
||||
self.sendGroupMessageToXMPP(buddy, partname, u"Received VCard (not implemented yet)", timestamp)
|
||||
else:
|
||||
|
||||
self.sendMessageToXMPP(buddy, "Received VCard (not implemented yet)")
|
||||
self.sendMessageToXMPP(buddy, u"Received VCard (not implemented yet)")
|
||||
# self.sendMessageToXMPP(buddy, card_data)
|
||||
#self.transferFile(buddy, str(name), card_data)
|
||||
self.sendReceipt(_id, _from, None, participant)
|
||||
|
||||
def transferFile(self, buddy, name, data):
|
||||
# Not working
|
||||
self.logger.debug('transfering file %s', name)
|
||||
self.logger.debug('transfering file %su', name)
|
||||
self.backend.handleFTStart(self.user, buddy, name, len(data))
|
||||
self.backend.handleFTData(0, data)
|
||||
self.backend.handleFTFinish(self.user, buddy, name, len(data), 0)
|
||||
|
||||
# Called by superclass
|
||||
def onContactTyping(self, buddy):
|
||||
self.logger.info("Started typing: %s", buddy)
|
||||
if buddy != 'bot':
|
||||
self.logger.info(u"Started typing: %s", buddy)
|
||||
if buddy != 'botu':
|
||||
self.sendPresence(True)
|
||||
self.backend.handleBuddyTyping(self.user, buddy)
|
||||
|
||||
|
@ -395,15 +395,15 @@ class Session(YowsupApp):
|
|||
|
||||
# Called by superclass
|
||||
def onContactPaused(self, buddy):
|
||||
self.logger.info("Paused typing: %s", buddy)
|
||||
if buddy != 'bot':
|
||||
self.logger.info(u"Paused typing: %s", buddy)
|
||||
if buddy != 'botu':
|
||||
self.backend.handleBuddyTyped(self.user, buddy)
|
||||
self.timer = Timer(3, self.backend.handleBuddyStoppedTyping,
|
||||
(self.user, buddy)).start()
|
||||
|
||||
# Called by superclass
|
||||
def onAddedToGroup(self, group):
|
||||
self.logger.debug("Added to group: %s", group)
|
||||
self.logger.debug(u"Added to group: %s", group)
|
||||
room = group.getGroupId()
|
||||
owner = group.getCreatorJid(full = False)
|
||||
subjectOwner = group.getSubjectOwnerJid(full = False)
|
||||
|
@ -411,42 +411,42 @@ class Session(YowsupApp):
|
|||
|
||||
self.groups[room] = Group(room, owner, subject, subjectOwner, self.backend, self.user)
|
||||
self.groups[room].addParticipants(group.getParticipants, self.buddies, self.legacyName)
|
||||
self.bot.send("You have been added to group: %s@%s (%s)"
|
||||
self.bot.send(u"You have been added to group: %s@%s (%s)"
|
||||
% (self._shortenGroupId(room), subject, self.backend.spectrum_jid))
|
||||
|
||||
# Called by superclass
|
||||
def onParticipantsAddedToGroup(self, group):
|
||||
self.logger.debug("Participants added to group: %s", group)
|
||||
room = group.getGroupId().split('@')[0]
|
||||
self.logger.debug(u"Participants added to group: %s", group)
|
||||
room = group.getGroupId().split('@u')[0]
|
||||
self.groups[room].addParticipants(group.getParticipants(), self.buddies, self.legacyName)
|
||||
self.groups[room].sendParticipantsToSpectrum(self.legacyName)
|
||||
|
||||
# Called by superclass
|
||||
def onParticipantsRemovedFromGroup(self, room, participants):
|
||||
self.logger.debug("Participants removed from group: %s, %s",
|
||||
self.logger.debug(u"Participants removed from group: %s, %s",
|
||||
room, participants)
|
||||
self.groups[room].removeParticipants(participants)
|
||||
|
||||
def onPresenceReceived(self, _type, name, jid, lastseen):
|
||||
self.logger.info("Presence received: %s %s %s %s", _type, name, jid, lastseen)
|
||||
buddy = jid.split("@")[0]
|
||||
self.logger.info(u"Presence received: %s %s %s %s", _type, name, jid, lastseen)
|
||||
buddy = jid.split(u"@")[0]
|
||||
try:
|
||||
buddy = self.buddies[buddy]
|
||||
except KeyError:
|
||||
self.logger.error("Buddy not found: %s", buddy)
|
||||
self.logger.error(u"Buddy not found: %s", buddy)
|
||||
return
|
||||
|
||||
if (lastseen == str(buddy.lastseen)) and (_type == buddy.presence):
|
||||
return
|
||||
|
||||
if ((lastseen != "deny") and (lastseen != None) and (lastseen != "none")):
|
||||
if ((lastseen != u"deny") and (lastseen != None) and (lastseen != u"none")):
|
||||
buddy.lastseen = int(lastseen)
|
||||
if (_type == None):
|
||||
buddy.lastseen = time.time()
|
||||
|
||||
buddy.presence = _type
|
||||
|
||||
if _type == "unavailable":
|
||||
if _type == u"unavailable":
|
||||
self.onPresenceUnavailable(buddy)
|
||||
else:
|
||||
self.onPresenceAvailable(buddy)
|
||||
|
@ -454,17 +454,17 @@ class Session(YowsupApp):
|
|||
|
||||
|
||||
def onPresenceAvailable(self, buddy):
|
||||
self.logger.info("Is available: %s", buddy)
|
||||
self.logger.info(u"Is available: %s", buddy)
|
||||
self.buddies.updateSpectrum(buddy)
|
||||
|
||||
def onPresenceUnavailable(self, buddy):
|
||||
self.logger.info("Is unavailable: %s", buddy)
|
||||
self.logger.info(u"Is unavailable: %s", buddy)
|
||||
self.buddies.updateSpectrum(buddy)
|
||||
|
||||
# spectrum RequestMethods
|
||||
def sendTypingStarted(self, buddy):
|
||||
if buddy != "bot":
|
||||
self.logger.info("Started typing: %s to %s", self.legacyName, buddy)
|
||||
if buddy != u"bot":
|
||||
self.logger.info(u"Started typing: %s to %s", self.legacyName, buddy)
|
||||
self.sendTyping(buddy, True)
|
||||
# If he is typing he is present
|
||||
# I really don't know where else to put this.
|
||||
|
@ -472,26 +472,26 @@ class Session(YowsupApp):
|
|||
self.sendPresence(True)
|
||||
|
||||
def sendTypingStopped(self, buddy):
|
||||
if buddy != "bot":
|
||||
self.logger.info("Stopped typing: %s to %s", self.legacyName, buddy)
|
||||
if buddy != u"bot":
|
||||
self.logger.info(u"Stopped typing: %s to %s", self.legacyName, buddy)
|
||||
self.sendTyping(buddy, False)
|
||||
|
||||
def sendMessageToWA(self, sender, message, ID):
|
||||
self.logger.info("Message sent from %s to %s: %s",
|
||||
self.logger.info(u"Message sent from %s to %s: %s",
|
||||
self.legacyName, sender, message)
|
||||
|
||||
message = message.encode("utf-8")
|
||||
message = message.encode(u"utf-8")
|
||||
# FIXME: Fragile, should pass this in to onDlerror
|
||||
self.dlerror_message = message
|
||||
self.dlerror_sender = sender
|
||||
self.dlerror_ID = ID
|
||||
# End Fragile
|
||||
|
||||
if sender == "bot":
|
||||
if sender == u"bot":
|
||||
self.bot.parse(message)
|
||||
elif "-" in sender: # group msg
|
||||
if "/" in sender: # directed at single user
|
||||
room, nick = sender.split("/")
|
||||
elif u"-" in sender: # group msg
|
||||
if u"/" in sender: # directed at single user
|
||||
room, nick = sender.split(u"/")
|
||||
group = self.groups[room]
|
||||
number = None
|
||||
for othernumber, othernick in group.participants.iteritems():
|
||||
|
@ -499,99 +499,99 @@ class Session(YowsupApp):
|
|||
number = othernumber
|
||||
break
|
||||
if number is not None:
|
||||
self.logger.debug("Private message sent from %s to %s", self.legacyName, number)
|
||||
waId = self.sendTextMessage(number + '@s.whatsapp.net', message)
|
||||
self.logger.debug(u"Private message sent from %s to %s", self.legacyName, number)
|
||||
waId = self.sendTextMessage(number + u'@s.whatsapp.net', message)
|
||||
self.msgIDs[waId] = MsgIDs( ID, waId)
|
||||
else:
|
||||
self.logger.error("Attempted to send private message to non-existent user")
|
||||
self.logger.debug("%s to %s in %s", self.legacyName, nick, room)
|
||||
self.logger.error(u"Attempted to send private message to non-existent user")
|
||||
self.logger.debug(u"%s to %s in %s", self.legacyName, nick, room)
|
||||
else:
|
||||
room = sender
|
||||
if message[0] == '\\' and message[:1] != '\\\\':
|
||||
self.logger.debug("Executing command %s in %s", message, room)
|
||||
if message[0] == u'\\' and message[:1] != u'\\\\':
|
||||
self.logger.debug(u"Executing command %s in %s", message, room)
|
||||
self.executeCommand(message, room)
|
||||
else:
|
||||
try:
|
||||
group = self.groups[self._lengthenGroupId(room)]
|
||||
self.logger.debug("Group Message from %s to %s Groups: %s",
|
||||
self.logger.debug(u"Group Message from %s to %s Groups: %s",
|
||||
group.nick , group , self.groups)
|
||||
self.backend.handleMessage(
|
||||
self.user, room, message.decode('utf-8'), group.nick
|
||||
self.user, room, message.decode(u'utf-8'), group.nick
|
||||
)
|
||||
except KeyError:
|
||||
self.logger.error('Group not found: %s', room)
|
||||
self.logger.error(u'Group not found: %s', room)
|
||||
|
||||
if (".jpg" in message.lower()) or (".webp" in message.lower()):
|
||||
if (".jpg" in message.lower()):
|
||||
self.imgType = "jpg"
|
||||
if (".webp" in message.lower()):
|
||||
self.imgType = "webp"
|
||||
if (u".jpg" in message.lower()) or (u".webp" in message.lower()):
|
||||
if (u".jpg" in message.lower()):
|
||||
self.imgType = u"jpg"
|
||||
if (u".webp" in message.lower()):
|
||||
self.imgType = u"webp"
|
||||
self.imgMsgId = ID
|
||||
self.imgBuddy = room + "@g.us"
|
||||
self.imgBuddy = room + u"@g.us"
|
||||
|
||||
|
||||
downloader = MediaDownloader(self.onDlsuccess, self.onDlerror)
|
||||
downloader.download(message)
|
||||
#self.imgMsgId = ID
|
||||
#self.imgBuddy = room + "@g.us"
|
||||
elif "geo:" in message.lower():
|
||||
self._sendLocation(room + "@g.us", message, ID)
|
||||
#self.imgBuddy = room + u"@g.us"
|
||||
elif u"geo:" in message.lower():
|
||||
self._sendLocation(room + u"@g.us", message, ID)
|
||||
|
||||
else:
|
||||
|
||||
self.sendTextMessage(self._lengthenGroupId(room) + '@g.us', message)
|
||||
self.sendTextMessage(self._lengthenGroupId(room) + u'@g.us', message)
|
||||
else: # private msg
|
||||
buddy = sender
|
||||
# if message == "\\lastseen":
|
||||
# self.call("presence_request", buddy = (buddy + "@s.whatsapp.net",))
|
||||
# if message == u"\\lastseen":
|
||||
# self.call(u"presence_request", buddy = (buddy + u"@s.whatsapp.net",))
|
||||
# else:
|
||||
if message.split(" ").pop(0) == "\\lastseen":
|
||||
if message.split(u" ").pop(0) == u"\\lastseen":
|
||||
self.presenceRequested.append(buddy)
|
||||
#self.call("presence_request", (buddy + "@s.whatsapp.net",))
|
||||
#self.call(u"presence_request", (buddy + u"@s.whatsapp.net",))
|
||||
self._requestLastSeen(buddy)
|
||||
elif message.split(" ").pop(0) == "\\gpp":
|
||||
self.logger.info("Get Profile Picture! ")
|
||||
self.sendMessageToXMPP(buddy, "Fetching Profile Picture")
|
||||
#self.call("contact_getProfilePicture", (buddy + "@s.whatsapp.net",))
|
||||
elif message.split(u" ").pop(0) == u"\\gpp":
|
||||
self.logger.info(u"Get Profile Picture! ")
|
||||
self.sendMessageToXMPP(buddy, u"Fetching Profile Picture")
|
||||
#self.call(u"contact_getProfilePicture", (buddy + u"@s.whatsapp.net",))
|
||||
self.requestVCard(buddy)
|
||||
else:
|
||||
if (".jpg" in message.lower()) or (".webp" in message.lower()):
|
||||
#waId = self.call("message_imageSend", (buddy + "@s.whatsapp.net", message, None, 0, None))
|
||||
#waId = self.call("message_send", (buddy + "@s.whatsapp.net", message))
|
||||
if (".jpg" in message.lower()):
|
||||
self.imgType = "jpg"
|
||||
if (".webp" in message.lower()):
|
||||
self.imgType = "webp"
|
||||
if (u".jpg" in message.lower()) or (u".webp" in message.lower()):
|
||||
#waId = self.call(u"message_imageSend", (buddy + u"@s.whatsapp.net", message, None, 0, None))
|
||||
#waId = self.call(u"message_send", (buddy + u"@s.whatsapp.net", message))
|
||||
if (u".jpg" in message.lower()):
|
||||
self.imgType = u"jpg"
|
||||
if (u".webp" in message.lower()):
|
||||
self.imgType = u"webp"
|
||||
self.imgMsgId = ID
|
||||
self.imgBuddy = buddy + "@s.whatsapp.net"
|
||||
self.imgBuddy = buddy + u"@s.whatsapp.net"
|
||||
|
||||
downloader = MediaDownloader(self.onDlsuccess, self.onDlerror)
|
||||
downloader.download(message)
|
||||
#self.imgMsgId = ID
|
||||
#self.imgBuddy = buddy + "@s.whatsapp.net"
|
||||
elif "geo:" in message.lower():
|
||||
self._sendLocation(buddy + "@s.whatsapp.net", message, ID)
|
||||
#self.imgBuddy = buddy + u"@s.whatsapp.net"
|
||||
elif u"geo:" in message.lower():
|
||||
self._sendLocation(buddy + u"@s.whatsapp.net", message, ID)
|
||||
else:
|
||||
waId = self.sendTextMessage(sender + '@s.whatsapp.net', message)
|
||||
waId = self.sendTextMessage(sender + u'@s.whatsapp.net', message)
|
||||
self.msgIDs[waId] = MsgIDs( ID, waId)
|
||||
|
||||
self.logger.info("WA Message send to %s with ID %s", buddy, waId)
|
||||
#self.sendTextMessage(sender + '@s.whatsapp.net', message)
|
||||
self.logger.info(u"WA Message send to %s with ID %s", buddy, waId)
|
||||
#self.sendTextMessage(sender + u'@s.whatsapp.net', message)
|
||||
|
||||
def executeCommand(self, command, room):
|
||||
if command == '\\leave':
|
||||
self.logger.debug("Leaving room %s", room)
|
||||
if command == u'\\leave':
|
||||
self.logger.debug(u"Leaving room %s", room)
|
||||
# Leave group on whatsapp side
|
||||
self.leaveGroup(room)
|
||||
# Delete Room on spectrum side
|
||||
group = self.groups[room]
|
||||
for jid in group.participants:
|
||||
buddy = jid.split("@")[0]
|
||||
buddy = jid.split(u"@")[0]
|
||||
try:
|
||||
nick = self.buddies[buddy].nick
|
||||
except KeyError:
|
||||
nick = buddy
|
||||
if nick == "":
|
||||
if nick == u"":
|
||||
nick = buddy
|
||||
if buddy == self.legacyName:
|
||||
nick = group.nick
|
||||
|
@ -605,43 +605,43 @@ class Session(YowsupApp):
|
|||
|
||||
def onSuccess(buddy, lastseen):
|
||||
timestamp = time.localtime(time.localtime()-lastseen)
|
||||
timestring = time.strftime("%a, %d %b %Y %H:%M:%S", timestamp)
|
||||
self.sendMessageToXMPP(buddy, "%s (%s) %s" % (timestring, utils.ago(lastseen),str(lastseen)))
|
||||
timestring = time.strftime(u"%a, %d %b %Y %H:%M:%S", timestamp)
|
||||
self.sendMessageToXMPP(buddy, u"%s (%s) %s" % (timestring, utils.ago(lastseen),str(lastseen)))
|
||||
def onError(errorIqEntity, originalIqEntity):
|
||||
self.sendMessageToXMPP(errorIqEntity.getFrom(), "LastSeen Error")
|
||||
self.sendMessageToXMPP(errorIqEntity.getFrom(), u"LastSeen Error")
|
||||
|
||||
self.requestLastSeen(buddy, onSuccess, onError)
|
||||
|
||||
def _sendLocation(self, buddy, message, ID):
|
||||
#with open('/opt/transwhat/map.jpg', 'rb') as imageFile:
|
||||
#with open(u'/opt/transwhat/map.jpg', u'rb') as imageFile:
|
||||
# raw = base64.b64encode(imageFile.read())
|
||||
latitude,longitude = message.split(':')[1].split(',')
|
||||
latitude,longitude = message.split(u':')[1].split(u',')
|
||||
waId = self.sendLocation(buddy, float(latitude), float(longitude))
|
||||
self.msgIDs[waId] = MsgIDs( ID, waId)
|
||||
self.logger.info("WA Location Message send to %s with ID %s", buddy, waId)
|
||||
self.logger.info(u"WA Location Message send to %s with ID %s", buddy, waId)
|
||||
|
||||
|
||||
|
||||
def sendMessageToXMPP(self, buddy, messageContent, timestamp = "", nickname = ""):
|
||||
def sendMessageToXMPP(self, buddy, messageContent, timestamp = u"", nickname = u""):
|
||||
if timestamp:
|
||||
timestamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime(timestamp))
|
||||
timestamp = time.strftime(u"%Y%m%dT%H%M%S", time.gmtime(timestamp))
|
||||
|
||||
if self.initialized == False:
|
||||
self.logger.debug("Message queued from %s to %s: %s",
|
||||
self.logger.debug(u"Message queued from %s to %s: %s",
|
||||
buddy, self.legacyName, messageContent)
|
||||
self.offlineQueue.append((buddy, messageContent, timestamp))
|
||||
else:
|
||||
self.logger.debug("Message sent from %s to %s: %s", buddy,
|
||||
self.logger.debug(u"Message sent from %s to %s: %s", buddy,
|
||||
self.legacyName, messageContent)
|
||||
self.backend.handleMessage(self.user, buddy, messageContent, "",
|
||||
"", timestamp)
|
||||
self.backend.handleMessage(self.user, buddy, messageContent, u"",
|
||||
u"", timestamp)
|
||||
|
||||
def sendGroupMessageToXMPP(self, room, number, messageContent, timestamp = ""):
|
||||
def sendGroupMessageToXMPP(self, room, number, messageContent, timestamp = u""):
|
||||
if timestamp:
|
||||
timestamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime(timestamp))
|
||||
timestamp = time.strftime(u"%Y%m%dT%H%M%S", time.gmtime(timestamp))
|
||||
|
||||
if self.initialized == False:
|
||||
self.logger.debug("Group message queued from %s to %s: %s",
|
||||
self.logger.debug(u"Group message queued from %s to %s: %s",
|
||||
number, room, messageContent)
|
||||
|
||||
if room not in self.groupOfflineQueue:
|
||||
|
@ -651,34 +651,34 @@ class Session(YowsupApp):
|
|||
(number, messageContent, timestamp)
|
||||
)
|
||||
else:
|
||||
self.logger.debug("Group message sent from %s to %s: %s",
|
||||
self.logger.debug(u"Group message sent from %s to %s: %s",
|
||||
number, room, messageContent)
|
||||
try:
|
||||
group = self.groups[room]
|
||||
# Update nickname
|
||||
try:
|
||||
if self.buddies[number].nick != "":
|
||||
if self.buddies[number].nick != u"":
|
||||
group.changeNick(number, self.buddies[number].nick)
|
||||
except KeyError:
|
||||
pass
|
||||
nick = group.participants[number]
|
||||
if group.joined:
|
||||
self.backend.handleMessage(self.user, room, messageContent,
|
||||
nick, "", timestamp)
|
||||
nick, u"", timestamp)
|
||||
else:
|
||||
self.bot.send("You have received a message in group: %s@%s"
|
||||
self.bot.send(u"You have received a message in group: %s@%s"
|
||||
% (room, self.backend.spectrum_jid))
|
||||
self.bot.send("Join the group in order to reply")
|
||||
self.bot.send("%s: %s" % (nick, messageContent))
|
||||
self.bot.send(u"Join the group in order to reply")
|
||||
self.bot.send(u"%s: %s" % (nick, messageContent))
|
||||
except KeyError:
|
||||
self.logger.warn("Group is not in group list")
|
||||
self.logger.warn(u"Group is not in group list")
|
||||
self.backend.handleMessage(self.user, self._shortenGroupId(room),
|
||||
messageContent, number, "", timestamp)
|
||||
messageContent, number, u"", timestamp)
|
||||
|
||||
|
||||
def changeStatus(self, status):
|
||||
if status != self.status:
|
||||
self.logger.info("Status changed: %s", status)
|
||||
self.logger.info(u"Status changed: %s", status)
|
||||
self.status = status
|
||||
|
||||
if status == protocol_pb2.STATUS_ONLINE \
|
||||
|
@ -690,19 +690,19 @@ class Session(YowsupApp):
|
|||
def changeStatusMessage(self, statusMessage):
|
||||
if (statusMessage != self.statusMessage) or (self.initialized == False):
|
||||
self.statusMessage = statusMessage
|
||||
self.setStatus(statusMessage.encode('utf-8'))
|
||||
self.logger.info("Status message changed: %s", statusMessage)
|
||||
self.setStatus(statusMessage.encode(u'utf-8'))
|
||||
self.logger.info(u"Status message changed: %s", statusMessage)
|
||||
|
||||
#if self.initialized == False:
|
||||
# self.sendOfflineMessages()
|
||||
# self.bot.call("welcome")
|
||||
# self.bot.call(u"welcome")
|
||||
# self.initialized = True
|
||||
|
||||
def sendOfflineMessages(self):
|
||||
# Flush Queues
|
||||
while self.offlineQueue:
|
||||
msg = self.offlineQueue.pop(0)
|
||||
self.backend.handleMessage(self.user, msg[0], msg[1], "", "", msg[2])
|
||||
self.backend.handleMessage(self.user, msg[0], msg[1], u"", u"", msg[2])
|
||||
|
||||
# Called when user logs in to initialize the roster
|
||||
def loadBuddies(self, buddies):
|
||||
|
@ -710,56 +710,56 @@ class Session(YowsupApp):
|
|||
|
||||
# also for adding a new buddy
|
||||
def updateBuddy(self, buddy, nick, groups, image_hash = None):
|
||||
if buddy != "bot":
|
||||
if buddy != u"bot":
|
||||
self.buddies.update(buddy, nick, groups, image_hash)
|
||||
|
||||
def removeBuddy(self, buddy):
|
||||
if buddy != "bot":
|
||||
self.logger.info("Buddy removed: %s", buddy)
|
||||
if buddy != u"bot":
|
||||
self.logger.info(u"Buddy removed: %s", buddy)
|
||||
self.buddies.remove(buddy)
|
||||
|
||||
def requestVCard(self, buddy, ID=None):
|
||||
def onSuccess(response, request):
|
||||
self.logger.debug('Sending VCard (%s) with image id %s',
|
||||
self.logger.debug(u'Sending VCard (%s) with image id %s',
|
||||
ID, response.pictureId)
|
||||
image_hash = utils.sha1hash(response.pictureData)
|
||||
self.logger.debug('Image hash is %s', image_hash)
|
||||
self.logger.debug(u'Image hash is %s', image_hash)
|
||||
if ID != None:
|
||||
self.backend.handleVCard(self.user, ID, buddy, "", "", response.pictureData)
|
||||
self.backend.handleVCard(self.user, ID, buddy, u"", u"", response.pictureData)
|
||||
obuddy = self.buddies[buddy]
|
||||
self.updateBuddy(buddy, obuddy.nick, obuddy.groups, image_hash)
|
||||
|
||||
self.logger.debug('Requesting profile picture of %s', buddy)
|
||||
self.logger.debug(u'Requesting profile picture of %s', buddy)
|
||||
self.requestProfilePicture(buddy, onSuccess = onSuccess)
|
||||
|
||||
def onDlsuccess(self, path):
|
||||
self.logger.info("Success: Image downloaded to %s", path)
|
||||
os.rename(path, path+"."+self.imgType)
|
||||
if self.imgType != "jpg":
|
||||
im = Image.open(path+"."+self.imgType)
|
||||
im.save(path+".jpg")
|
||||
self.imgPath = path+".jpg"
|
||||
self.logger.info(u"Success: Image downloaded to %s", path)
|
||||
os.rename(path, path+u"."+self.imgType)
|
||||
if self.imgType != u"jpg":
|
||||
im = Image.open(path+u"."+self.imgType)
|
||||
im.save(path+u".jpg")
|
||||
self.imgPath = path+u".jpg"
|
||||
statinfo = os.stat(self.imgPath)
|
||||
name=os.path.basename(self.imgPath)
|
||||
self.logger.info("Buddy %s",self.imgBuddy)
|
||||
self.logger.info(u"Buddy %s",self.imgBuddy)
|
||||
self.image_send(self.imgBuddy, self.imgPath)
|
||||
|
||||
#self.logger.info("Sending picture %s of size %s with name %s",self.imgPath, statinfo.st_size, name)
|
||||
#mtype = "image"
|
||||
#self.logger.info(u"Sending picture %s of size %s with name %s",self.imgPath, statinfo.st_size, name)
|
||||
#mtype = u"image"
|
||||
|
||||
#sha1 = hashlib.sha256()
|
||||
#fp = open(self.imgPath, 'rb')
|
||||
#fp = open(self.imgPath, u'rb')
|
||||
#try:
|
||||
# sha1.update(fp.read())
|
||||
# hsh = base64.b64encode(sha1.digest())
|
||||
# self.call("media_requestUpload", (hsh, mtype, os.path.getsize(self.imgPath)))
|
||||
# self.call(u"media_requestUpload", (hsh, mtype, os.path.getsize(self.imgPath)))
|
||||
#finally:
|
||||
# fp.close()
|
||||
|
||||
|
||||
def onDlerror(self):
|
||||
self.logger.info("Download Error. Sending message as is.")
|
||||
waId = self.sendTextMessage(self.dlerror_sender + '@s.whatsapp.net', self.dlerror_message)
|
||||
self.logger.info(u"Download Error. Sending message as is.")
|
||||
waId = self.sendTextMessage(self.dlerror_sender + u'@s.whatsapp.net', self.dlerror_message)
|
||||
self.msgIDs[waId] = MsgIDs(self.dlerror_ID, waId)
|
||||
|
||||
|
||||
|
@ -777,7 +777,7 @@ class Session(YowsupApp):
|
|||
def createThumb(self, size=100, raw=False):
|
||||
img = Image.open(self.imgPath)
|
||||
width, height = img.size
|
||||
img_thumbnail = self.imgPath + '_thumbnail'
|
||||
img_thumbnail = self.imgPath + u'_thumbnail'
|
||||
|
||||
if width > height:
|
||||
nheight = float(height) / width * size
|
||||
|
@ -787,47 +787,47 @@ class Session(YowsupApp):
|
|||
nheight = size
|
||||
|
||||
img.thumbnail((nwidth, nheight), Image.ANTIALIAS)
|
||||
img.save(img_thumbnail, 'JPEG')
|
||||
img.save(img_thumbnail, u'JPEG')
|
||||
|
||||
with open(img_thumbnail, 'rb') as imageFile:
|
||||
with open(img_thumbnail, u'rb') as imageFile:
|
||||
raw = base64.b64encode(imageFile.read())
|
||||
|
||||
return raw
|
||||
|
||||
# Not used
|
||||
def onLocationReceived(self, messageId, jid, name, preview, latitude, longitude, receiptRequested, isBroadcast):
|
||||
buddy = jid.split("@")[0]
|
||||
self.logger.info("Location received from %s: %s, %s", buddy, latitude, longitude)
|
||||
buddy = jid.split(u"@")[0]
|
||||
self.logger.info(u"Location received from %s: %s, %s", buddy, latitude, longitude)
|
||||
|
||||
url = "http://maps.google.de?%s" % urllib.urlencode({ "q": "%s %s" % (latitude, longitude) })
|
||||
url = u"http://maps.google.de?%s" % urllib.urlencode({ u"q": u"%s %s" % (latitude, longitude) })
|
||||
self.sendMessageToXMPP(buddy, utils.shorten(url))
|
||||
if receiptRequested: self.call("message_ack", (jid, messageId))
|
||||
if receiptRequested: self.call(u"message_ack", (jid, messageId))
|
||||
|
||||
|
||||
def onGroupSubjectReceived(self, messageId, gjid, jid, subject, timestamp, receiptRequested):
|
||||
room = gjid.split("@")[0]
|
||||
buddy = jid.split("@")[0]
|
||||
room = gjid.split(u"@")[0]
|
||||
buddy = jid.split(u"@")[0]
|
||||
|
||||
self.backend.handleSubject(self.user, room, subject, buddy)
|
||||
if receiptRequested: self.call("subject_ack", (gjid, messageId))
|
||||
if receiptRequested: self.call(u"subject_ack", (gjid, messageId))
|
||||
|
||||
# Yowsup Notifications
|
||||
def onGroupParticipantRemoved(self, gjid, jid, author, timestamp, messageId, receiptRequested):
|
||||
room = gjid.split("@")[0]
|
||||
buddy = jid.split("@")[0]
|
||||
room = gjid.split(u"@")[0]
|
||||
buddy = jid.split(u"@")[0]
|
||||
|
||||
self.logger.info("Removed %s from room %s", buddy, room)
|
||||
self.logger.info(u"Removed %s from room %s", buddy, room)
|
||||
|
||||
self.backend.handleParticipantChanged(self.user, buddy, room, protocol_pb2.PARTICIPANT_FLAG_NONE, protocol_pb2.STATUS_NONE) # TODO
|
||||
if receiptRequested: self.call("notification_ack", (gjid, messageId))
|
||||
if receiptRequested: self.call(u"notification_ack", (gjid, messageId))
|
||||
|
||||
def onContactProfilePictureUpdated(self, jid, timestamp, messageId, pictureId, receiptRequested):
|
||||
# TODO
|
||||
if receiptRequested: self.call("notification_ack", (jid, messageId))
|
||||
if receiptRequested: self.call(u"notification_ack", (jid, messageId))
|
||||
|
||||
def onGroupPictureUpdated(self, jid, author, timestamp, messageId, pictureId, receiptRequested):
|
||||
# TODO
|
||||
if receiptRequested: self.call("notification_ack", (jid, messageId))
|
||||
if receiptRequested: self.call(u"notification_ack", (jid, messageId))
|
||||
|
||||
|
||||
|
||||
|
|
38
transwhat.py
38
transwhat.py
|
@ -1,12 +1,12 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -42,21 +42,21 @@ from yowsup.stacks import YowStack
|
|||
|
||||
# Arguments
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--debug', action='store_true')
|
||||
parser.add_argument('--host', type=str, required=True)
|
||||
parser.add_argument('--port', type=int, required=True)
|
||||
parser.add_argument('--service.backend_id', metavar="ID", type=int, required=True)
|
||||
parser.add_argument('config', type=str)
|
||||
parser.add_argument('-j', type=str, required=True)
|
||||
parser.add_argument(u'--debug', action=u'store_true')
|
||||
parser.add_argument(u'--host', type=str, required=True)
|
||||
parser.add_argument(u'--port', type=int, required=True)
|
||||
parser.add_argument(u'--service.backend_id', metavar=u"ID", type=int, required=True)
|
||||
parser.add_argument(u'config', type=str)
|
||||
parser.add_argument(u'-j', type=str, required=True)
|
||||
|
||||
args, unknown = parser.parse_known_args()
|
||||
|
||||
YowConstants.PATH_STORAGE='/var/lib/spectrum2/' + args.j
|
||||
loggingfile = '/var/log/spectrum2/' + args.j + '/backends/backend.log'
|
||||
YowConstants.PATH_STORAGE=u'/var/lib/spectrum2/' + args.j
|
||||
loggingfile = u'/var/log/spectrum2/' + args.j + u'/backends/backend.log'
|
||||
# Logging
|
||||
logging.basicConfig( \
|
||||
filename=loggingfile,\
|
||||
format = "%(asctime)-15s %(levelname)s %(name)s: %(message)s", \
|
||||
format = u"%(asctime)-15s %(levelname)s %(name)s: %(message)s", \
|
||||
level = logging.DEBUG if args.debug else logging.INFO \
|
||||
)
|
||||
|
||||
|
@ -77,9 +77,9 @@ io = IOChannel(args.host, args.port, handleTransportData, connectionClosed)
|
|||
plugin = WhatsAppBackend(io, args.j)
|
||||
|
||||
plugin.handleBackendConfig({
|
||||
'features': [
|
||||
('send_buddies_on_login', 1),
|
||||
('muc', 'true'),
|
||||
u'features': [
|
||||
(u'send_buddies_on_login', 1),
|
||||
(u'muc', u'true'),
|
||||
],
|
||||
})
|
||||
|
||||
|
@ -87,7 +87,7 @@ while True:
|
|||
try:
|
||||
asyncore.loop(timeout=1.0, count=10, use_poll = True)
|
||||
try:
|
||||
callback = YowStack._YowStack__detachedQueue.get(False) #doesn't block
|
||||
callback = YowStack._YowStack__detachedQueue.get(False) #doesnu't block
|
||||
callback()
|
||||
except Queue.Empty:
|
||||
pass
|
||||
|
|
22
utils.py
22
utils.py
|
@ -1,10 +1,10 @@
|
|||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -26,7 +26,7 @@ import base64
|
|||
import hashlib
|
||||
|
||||
def ago(secs):
|
||||
periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"]
|
||||
periods = [u"second", u"minute", u"hour", u"day", u"week", u"month", u"year", u"decade"]
|
||||
lengths = [60, 60, 24, 7,4.35, 12, 10]
|
||||
|
||||
j = 0
|
||||
|
@ -38,16 +38,16 @@ def ago(secs):
|
|||
j += 1
|
||||
|
||||
period = periods[j]
|
||||
if diff > 1: period += "s"
|
||||
if diff > 1: period += u"s"
|
||||
|
||||
return "%d %s ago" % (diff, period)
|
||||
return u"%d %s ago" % (diff, period)
|
||||
|
||||
def softToUni(message):
|
||||
message = message.decode("utf-8")
|
||||
message = message.decode(u"utf-8")
|
||||
return e4u.translate(message, reverse=False, **e4u.SOFTBANK_TRANSLATE_PROFILE)
|
||||
|
||||
def decodePassword(password):
|
||||
return base64.b64decode(bytes(password.encode("utf-8")))
|
||||
return base64.b64decode(bytes(password.encode(u"utf-8")))
|
||||
|
||||
def sha1hash(data):
|
||||
return hashlib.sha1(data).hexdigest()
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
__author__ = "Steffen Vogel"
|
||||
__copyright__ = "Copyright 2015, Steffen Vogel"
|
||||
__license__ = "GPLv3"
|
||||
__maintainer__ = "Steffen Vogel"
|
||||
__email__ = "post@steffenvogel.de"
|
||||
__author__ = u"Steffen Vogel"
|
||||
__copyright__ = u"Copyright 2015, Steffen Vogel"
|
||||
__license__ = u"GPLv3"
|
||||
__maintainer__ = u"Steffen Vogel"
|
||||
__email__ = u"post@steffenvogel.de"
|
||||
|
||||
"""
|
||||
u"""
|
||||
This file is part of transWhat
|
||||
|
||||
transWhat is free software: you can redistribute it and/or modify
|
||||
|
@ -38,11 +38,11 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
# Used to prevent duplicate messages
|
||||
self.lastMessage = {}
|
||||
|
||||
self.logger.debug("Backend started")
|
||||
self.logger.debug(u"Backend started")
|
||||
|
||||
# RequestsHandlers
|
||||
def handleLoginRequest(self, user, legacyName, password, extra):
|
||||
self.logger.debug("handleLoginRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
self.logger.debug(u"handleLoginRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
if user not in self.sessions:
|
||||
self.sessions[user] = Session(self, user, legacyName, extra)
|
||||
|
||||
|
@ -52,13 +52,13 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
self.sessions[user].login(password)
|
||||
|
||||
def handleLogoutRequest(self, user, legacyName):
|
||||
self.logger.debug("handleLogoutRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
self.logger.debug(u"handleLogoutRequest(user=%s, legacyName=%s)", user, legacyName)
|
||||
if user in self.sessions:
|
||||
self.sessions[user].logout()
|
||||
del self.sessions[user]
|
||||
|
||||
def handleMessageSendRequest(self, user, buddy, message, xhtml = "", ID = 0):
|
||||
self.logger.debug("handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml = %s)", user, buddy, message, xhtml)
|
||||
def handleMessageSendRequest(self, user, buddy, message, xhtml = u"", ID = 0):
|
||||
self.logger.debug(u"handleMessageSendRequest(user=%s, buddy=%s, message=%s, xhtml = %s)", user, buddy, message, xhtml)
|
||||
# For some reason spectrum occasionally sends to identical messages to
|
||||
# a buddy, one to the bare jid and one to /bot. This causes duplicate
|
||||
# messages. Since it is unlikely a user wants to send the same message
|
||||
|
@ -73,48 +73,48 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
usersMessage[buddy] = message
|
||||
|
||||
def handleJoinRoomRequest(self, user, room, nickname, pasword):
|
||||
self.logger.debug("handleJoinRoomRequest(user=%s, room=%s, nickname=%s)", user, room, nickname)
|
||||
self.logger.debug(u"handleJoinRoomRequest(user=%s, room=%s, nickname=%s)", user, room, nickname)
|
||||
self.sessions[user].joinRoom(room, nickname)
|
||||
|
||||
def handleLeaveRoomRequest(self, user, room):
|
||||
self.logger.debug("handleLeaveRoomRequest(user=%s, room=%s)", user, room)
|
||||
self.logger.debug(u"handleLeaveRoomRequest(user=%s, room=%s)", user, room)
|
||||
self.sessions[user].leaveRoom(room)
|
||||
|
||||
def handleStatusChangeRequest(self, user, status, statusMessage):
|
||||
self.logger.debug("handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)", user, status, statusMessage)
|
||||
self.logger.debug(u"handleStatusChangeRequest(user=%s, status=%d, statusMessage=%s)", user, status, statusMessage)
|
||||
self.sessions[user].changeStatusMessage(statusMessage)
|
||||
self.sessions[user].changeStatus(status)
|
||||
|
||||
def handleBuddies(self, buddies):
|
||||
"""Called when user logs in. Used to initialize roster."""
|
||||
self.logger.debug("handleBuddies(buddies=%s)", buddies)
|
||||
u"""Called when user logs in. Used to initialize roster."""
|
||||
self.logger.debug(u"handleBuddies(buddies=%s)", buddies)
|
||||
buddies = [b for b in buddies.buddy]
|
||||
if len(buddies) > 0:
|
||||
user = buddies[0].userName
|
||||
self.sessions[user].loadBuddies(buddies)
|
||||
|
||||
def handleBuddyUpdatedRequest(self, user, buddy, nick, groups):
|
||||
self.logger.debug("handleBuddyUpdatedRequest(user=%s, buddy=%s, nick=%s, groups=%s)", user, buddy, nick, str(groups))
|
||||
self.logger.debug(u"handleBuddyUpdatedRequest(user=%s, buddy=%s, nick=%s, groups=%s)", user, buddy, nick, str(groups))
|
||||
self.sessions[user].updateBuddy(buddy, nick, groups)
|
||||
|
||||
def handleBuddyRemovedRequest(self, user, buddy, groups):
|
||||
self.logger.debug("handleBuddyRemovedRequest(user=%s, buddy=%s, groups=%s)", user, buddy, str(groups))
|
||||
self.logger.debug(u"handleBuddyRemovedRequest(user=%s, buddy=%s, groups=%s)", user, buddy, str(groups))
|
||||
self.sessions[user].removeBuddy(buddy)
|
||||
|
||||
def handleTypingRequest(self, user, buddy):
|
||||
self.logger.debug("handleTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.logger.debug(u"handleTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.sessions[user].sendTypingStarted(buddy)
|
||||
|
||||
def handleTypedRequest(self, user, buddy):
|
||||
self.logger.debug("handleTypedRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.logger.debug(u"handleTypedRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.sessions[user].sendTypingStopped(buddy)
|
||||
|
||||
def handleStoppedTypingRequest(self, user, buddy):
|
||||
self.logger.debug("handleStoppedTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.logger.debug(u"handleStoppedTypingRequest(user=%s, buddy=%s)", user, buddy)
|
||||
self.sessions[user].sendTypingStopped(buddy)
|
||||
|
||||
def handleVCardRequest(self, user, buddy, ID):
|
||||
self.logger.debug("handleVCardRequest(user=%s, buddy=%s, ID=%s)", user, buddy, ID)
|
||||
self.logger.debug(u"handleVCardRequest(user=%s, buddy=%s, ID=%s)", user, buddy, ID)
|
||||
self.sessions[user].requestVCard(buddy, ID)
|
||||
|
||||
|
||||
|
@ -129,7 +129,7 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
pass
|
||||
|
||||
def handleFTStartRequest(self, user, buddy, fileName, size, ftID):
|
||||
self.logger.debug('File send request %s, for user %s, from %s, size: %s',
|
||||
self.logger.debug(u'File send request %s, for user %s, from %s, size: %s',
|
||||
fileName, user, buddy, size)
|
||||
|
||||
def handleFTFinishRequest(self, user, buddy, fileName, size, ftID):
|
||||
|
@ -145,7 +145,7 @@ class WhatsAppBackend(SpectrumBackend):
|
|||
pass
|
||||
|
||||
def handleMessageAckRequest(self, user, legacyName, ID = 0):
|
||||
self.logger.info("Meassage ACK request for %s !!",legacyName)
|
||||
self.logger.info(u"Meassage ACK request for %s !!",legacyName)
|
||||
|
||||
def sendData(self, data):
|
||||
self.io.sendData(data)
|
||||
|
|
142
yowsupwrapper.py
142
yowsupwrapper.py
|
@ -78,7 +78,7 @@ class YowsupApp(object):
|
|||
)
|
||||
|
||||
def login(self, username, password):
|
||||
"""Login to yowsup
|
||||
u"""Login to yowsup
|
||||
|
||||
Should result in onAuthSuccess or onAuthFailure to be called.
|
||||
|
||||
|
@ -102,20 +102,20 @@ class YowsupApp(object):
|
|||
self.stack.broadcastEvent(
|
||||
YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
|
||||
except TypeError as e: # Occurs when password is not correctly formated
|
||||
self.onAuthFailure('password not base64 encoded')
|
||||
self.onAuthFailure(u'password not base64 encoded')
|
||||
# try:
|
||||
# self.stack.loop(timeout=0.5, discrete=0.5)
|
||||
# except AuthError as e: # For some reason Yowsup throws an exception
|
||||
# self.onAuthFailure("%s" % e)
|
||||
# self.onAuthFailure(u"%s" % e)
|
||||
|
||||
def logout(self):
|
||||
"""
|
||||
u"""
|
||||
Logout from whatsapp
|
||||
"""
|
||||
self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
|
||||
|
||||
def sendReceipt(self, _id, _from, read, participant):
|
||||
"""
|
||||
u"""
|
||||
Send a receipt (delivered: double-tick, read: blue-ticks)
|
||||
|
||||
Args:
|
||||
|
@ -128,7 +128,7 @@ class YowsupApp(object):
|
|||
self.sendEntity(receipt)
|
||||
|
||||
def sendTextMessage(self, to, message):
|
||||
"""
|
||||
u"""
|
||||
Sends a text message
|
||||
|
||||
Args:
|
||||
|
@ -140,7 +140,7 @@ class YowsupApp(object):
|
|||
return messageEntity.getId()
|
||||
|
||||
def sendLocation(self, to, latitude, longitude):
|
||||
messageEntity = LocationMediaMessageProtocolEntity(latitude,longitude, None, None, "raw", to = to)
|
||||
messageEntity = LocationMediaMessageProtocolEntity(latitude,longitude, None, None, u"raw", to = to)
|
||||
self.sendEntity(messageEntity)
|
||||
return messageEntity.getId()
|
||||
|
||||
|
@ -170,14 +170,14 @@ class YowsupApp(object):
|
|||
mediaUploader.start()
|
||||
|
||||
def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity):
|
||||
self.logger.error("Request upload for file %s for %s failed" % (path, jid))
|
||||
self.logger.error(u"Request upload for file %s for %s failed" % (path, jid))
|
||||
|
||||
def onUploadError(self, filePath, jid, url):
|
||||
#logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid))
|
||||
self.logger.error("Upload Error!")
|
||||
#logger.error(u"Upload file %s to %s for %s failed!" % (filePath, url, jid))
|
||||
self.logger.error(u"Upload Error!")
|
||||
|
||||
def onUploadProgress(self, filePath, jid, url, progress):
|
||||
#sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress))
|
||||
#sys.stdout.write(u"%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress))
|
||||
#sys.stdout.flush()
|
||||
pass
|
||||
|
||||
|
@ -197,7 +197,7 @@ class YowsupApp(object):
|
|||
|
||||
|
||||
def sendPresence(self, available):
|
||||
"""
|
||||
u"""
|
||||
Send presence to whatsapp
|
||||
|
||||
Args:
|
||||
|
@ -209,42 +209,42 @@ class YowsupApp(object):
|
|||
self.sendEntity(UnavailablePresenceProtocolEntity())
|
||||
|
||||
def subscribePresence(self, phone_number):
|
||||
"""
|
||||
u"""
|
||||
Subscribe to presence updates from phone_number
|
||||
|
||||
Args:
|
||||
- phone_number: (str) The cellphone number of the person to
|
||||
subscribe to
|
||||
"""
|
||||
self.logger.debug("Subscribing to Presence updates from %s", (phone_number))
|
||||
jid = phone_number + '@s.whatsapp.net'
|
||||
self.logger.debug(u"Subscribing to Presence updates from %s", (phone_number))
|
||||
jid = phone_number + u'@s.whatsapp.net'
|
||||
entity = SubscribePresenceProtocolEntity(jid)
|
||||
self.sendEntity(entity)
|
||||
|
||||
def unsubscribePresence(self, phone_number):
|
||||
"""
|
||||
u"""
|
||||
Unsubscribe to presence updates from phone_number
|
||||
|
||||
Args:
|
||||
- phone_number: (str) The cellphone number of the person to
|
||||
unsubscribe from
|
||||
"""
|
||||
jid = phone_number + '@s.whatsapp.net'
|
||||
jid = phone_number + u'@s.whatsapp.net'
|
||||
entity = UnsubscribePresenceProtocolEntity(jid)
|
||||
self.sendEntity(entity)
|
||||
|
||||
def leaveGroup(self, group):
|
||||
"""
|
||||
u"""
|
||||
Permanently leave a WhatsApp group
|
||||
|
||||
Args:
|
||||
- group: (str) the group id (e.g. 27831788123-144024456)
|
||||
"""
|
||||
entity = LeaveGroupsIqProtocolEntity([group + '@g.us'])
|
||||
entity = LeaveGroupsIqProtocolEntity([group + u'@g.us'])
|
||||
self.sendEntity(entity)
|
||||
|
||||
def setStatus(self, statusText):
|
||||
"""
|
||||
u"""
|
||||
Send status to whatsapp
|
||||
|
||||
Args:
|
||||
|
@ -254,14 +254,14 @@ class YowsupApp(object):
|
|||
self.sendIq(iq)
|
||||
|
||||
def sendTyping(self, phoneNumber, typing):
|
||||
"""
|
||||
u"""
|
||||
Notify buddy using phoneNumber that you are typing to him
|
||||
|
||||
Args:
|
||||
- phoneNumber: (str) cellphone number of the buddy you are typing to.
|
||||
- typing: (bool) True if you are typing, False if you are not
|
||||
"""
|
||||
jid = phoneNumber + '@s.whatsapp.net'
|
||||
jid = phoneNumber + u'@s.whatsapp.net'
|
||||
if typing:
|
||||
state = OutgoingChatstateProtocolEntity(
|
||||
ChatstateProtocolEntity.STATE_TYPING, jid
|
||||
|
@ -273,7 +273,7 @@ class YowsupApp(object):
|
|||
self.sendEntity(state)
|
||||
|
||||
def sendSync(self, contacts, delta = False, interactive = True):
|
||||
"""
|
||||
u"""
|
||||
You need to sync new contacts before you interact with
|
||||
them, failure to do so could result in a temporary ban.
|
||||
|
||||
|
@ -293,7 +293,7 @@ class YowsupApp(object):
|
|||
self.sendIq(iq)
|
||||
|
||||
def requestStatuses(self, contacts, success = None, failure = None):
|
||||
"""
|
||||
u"""
|
||||
Request the statuses of a number of users.
|
||||
|
||||
Args:
|
||||
|
@ -302,19 +302,19 @@ class YowsupApp(object):
|
|||
- success: (func) called when request is successful
|
||||
- failure: (func) called when request has failed
|
||||
"""
|
||||
iq = GetStatusesIqProtocolEntity([c + '@s.whatsapp.net' for c in contacts])
|
||||
iq = GetStatusesIqProtocolEntity([c + u'@s.whatsapp.net' for c in contacts])
|
||||
def onSuccess(response, request):
|
||||
self.logger.debug("Received Statuses %s", response)
|
||||
self.logger.debug(u"Received Statuses %s", response)
|
||||
s = {}
|
||||
for k, v in response.statuses.iteritems():
|
||||
s[k.split('@')[0]] = v
|
||||
s[k.split(u'@')[0]] = v
|
||||
success(s)
|
||||
|
||||
self.sendIq(iq, onSuccess = onSuccess, onError = failure)
|
||||
|
||||
|
||||
def requestLastSeen(self, phoneNumber, success = None, failure = None):
|
||||
"""
|
||||
u"""
|
||||
Requests when user was last seen.
|
||||
Args:
|
||||
- phone_number: (str) the phone number of the user
|
||||
|
@ -323,22 +323,22 @@ class YowsupApp(object):
|
|||
since last seen.
|
||||
- failure: (func) called when request has failed
|
||||
"""
|
||||
iq = LastseenIqProtocolEntity(phoneNumber + '@s.whatsapp.net')
|
||||
iq = LastseenIqProtocolEntity(phoneNumber + u'@s.whatsapp.net')
|
||||
self.sendIq(iq, onSuccess = partial(self._lastSeenSuccess, success),
|
||||
onError = failure)
|
||||
|
||||
def _lastSeenSuccess(self, success, response, request):
|
||||
success(response._from.split('@')[0], response.seconds)
|
||||
success(response._from.split(u'@')[0], response.seconds)
|
||||
|
||||
def requestProfilePicture(self, phoneNumber, onSuccess = None, onFailure = None):
|
||||
"""
|
||||
u"""
|
||||
Requests profile picture of whatsapp user
|
||||
Args:
|
||||
- phoneNumber: (str) the phone number of the user
|
||||
- onSuccess: (func) called when request is successfully processed.
|
||||
- onFailure: (func) called when request has failed
|
||||
"""
|
||||
iq = GetPictureIqProtocolEntity(phoneNumber + '@s.whatsapp.net')
|
||||
iq = GetPictureIqProtocolEntity(phoneNumber + u'@s.whatsapp.net')
|
||||
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
|
||||
|
||||
def requestGroupsList(self, onSuccess = None, onFailure = None):
|
||||
|
@ -346,7 +346,7 @@ class YowsupApp(object):
|
|||
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
|
||||
|
||||
def requestGroupInfo(self, group, onSuccess = None, onFailure = None):
|
||||
"""
|
||||
u"""
|
||||
Request info on a specific group (includes participants, subject, owner etc.)
|
||||
|
||||
Args:
|
||||
|
@ -354,11 +354,11 @@ class YowsupApp(object):
|
|||
- onSuccess: (func) called when request is successfully processed.
|
||||
- onFailure: (func) called when request is has failed
|
||||
"""
|
||||
iq = InfoGroupsIqProtocolEntity(group + '@g.us')
|
||||
iq = InfoGroupsIqProtocolEntity(group + u'@g.us')
|
||||
self.sendIq(iq, onSuccess = onSuccess, onError = onFailure)
|
||||
|
||||
def onAuthSuccess(self, status, kind, creation, expiration, props, nonce, t):
|
||||
"""
|
||||
u"""
|
||||
Called when login is successful.
|
||||
|
||||
Args:
|
||||
|
@ -373,7 +373,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAuthFailure(self, reason):
|
||||
"""
|
||||
u"""
|
||||
Called when login is a failure
|
||||
|
||||
Args:
|
||||
|
@ -382,7 +382,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onReceipt(self, _id, _from, timestamp, type, participant, offline, items):
|
||||
"""
|
||||
u"""
|
||||
Called when a receipt is received (double tick or blue tick)
|
||||
|
||||
Args
|
||||
|
@ -398,7 +398,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAck(self, _id,_class, _from, timestamp):
|
||||
"""
|
||||
u"""
|
||||
Called when Ack is received
|
||||
|
||||
Args:
|
||||
|
@ -410,7 +410,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onPresenceReceived(self, _type, name, _from, last):
|
||||
"""
|
||||
u"""
|
||||
Called when presence (e.g. available, unavailable) is received
|
||||
from whatsapp
|
||||
|
||||
|
@ -423,12 +423,12 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onDisconnect(self):
|
||||
"""
|
||||
u"""
|
||||
Called when disconnected from whatsapp
|
||||
"""
|
||||
|
||||
def onContactTyping(self, number):
|
||||
"""
|
||||
u"""
|
||||
Called when contact starts to type
|
||||
|
||||
Args:
|
||||
|
@ -437,7 +437,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onContactPaused(self, number):
|
||||
"""
|
||||
u"""
|
||||
Called when contact stops typing
|
||||
|
||||
Args:
|
||||
|
@ -446,7 +446,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onTextMessage(self, _id, _from, to, notify, timestamp, participant, offline, retry, body):
|
||||
"""
|
||||
u"""
|
||||
Called when text message is received
|
||||
|
||||
Args:
|
||||
|
@ -463,7 +463,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onImage(self, entity):
|
||||
"""
|
||||
u"""
|
||||
Called when image message is received
|
||||
|
||||
Args:
|
||||
|
@ -472,7 +472,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAudio(self, entity):
|
||||
"""
|
||||
u"""
|
||||
Called when audio message is received
|
||||
|
||||
Args:
|
||||
|
@ -482,7 +482,7 @@ class YowsupApp(object):
|
|||
|
||||
|
||||
def onVideo(self, entity):
|
||||
"""
|
||||
u"""
|
||||
Called when video message is received
|
||||
|
||||
Args:
|
||||
|
@ -491,7 +491,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onLocation(self, entity):
|
||||
"""
|
||||
u"""
|
||||
Called when location message is received
|
||||
|
||||
Args:
|
||||
|
@ -500,7 +500,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onVCard(self, _id, _from, name, card_data, to, notify, timestamp, participant):
|
||||
"""
|
||||
u"""
|
||||
Called when VCard message is received
|
||||
|
||||
Args:
|
||||
|
@ -516,15 +516,15 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def onAddedToGroup(self, entity):
|
||||
"""Called when the user has been added to a new group"""
|
||||
u"""Called when the user has been added to a new group"""
|
||||
pass
|
||||
|
||||
def onParticipantsAddedToGroup(self, entity):
|
||||
"""Called when participants have been added to a group"""
|
||||
u"""Called when participants have been added to a group"""
|
||||
pass
|
||||
|
||||
def onParticipantsRemovedFromGroup(self, group, participants):
|
||||
"""Called when participants have been removed from a group
|
||||
u"""Called when participants have been removed from a group
|
||||
|
||||
Args:
|
||||
- group: (str) id of the group (e.g. 27831788123-144024456)
|
||||
|
@ -533,7 +533,7 @@ class YowsupApp(object):
|
|||
pass
|
||||
|
||||
def sendEntity(self, entity):
|
||||
"""Sends an entity down the stack (as if YowsupAppLayer called toLower)"""
|
||||
u"""Sends an entity down the stack (as if YowsupAppLayer called toLower)"""
|
||||
self.stack.broadcastEvent(YowLayerEvent(YowsupAppLayer.TO_LOWER_EVENT,
|
||||
entity = entity
|
||||
))
|
||||
|
@ -551,9 +551,9 @@ class YowsupApp(object):
|
|||
from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
|
||||
|
||||
class YowsupAppLayer(YowInterfaceLayer):
|
||||
EVENT_START = 'transwhat.event.YowsupAppLayer.start'
|
||||
TO_LOWER_EVENT = 'transwhat.event.YowsupAppLayer.toLower'
|
||||
SEND_IQ = 'transwhat.event.YowsupAppLayer.sendIq'
|
||||
EVENT_START = u'transwhat.event.YowsupAppLayer.start'
|
||||
TO_LOWER_EVENT = u'transwhat.event.YowsupAppLayer.toLower'
|
||||
SEND_IQ = u'transwhat.event.YowsupAppLayer.sendIq'
|
||||
|
||||
def onEvent(self, layerEvent):
|
||||
# We cannot pass instance varaibles in through init, so we use an event
|
||||
|
@ -561,24 +561,24 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
# Return False if you want the event to propogate down the stack
|
||||
# return True otherwise
|
||||
if layerEvent.getName() == YowsupAppLayer.EVENT_START:
|
||||
self.caller = layerEvent.getArg('caller')
|
||||
self.caller = layerEvent.getArg(u'caller')
|
||||
self.logger = logging.getLogger(self.__class__.__name__)
|
||||
return True
|
||||
elif layerEvent.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECTED:
|
||||
self.caller.onDisconnect()
|
||||
return True
|
||||
elif layerEvent.getName() == YowsupAppLayer.TO_LOWER_EVENT:
|
||||
self.toLower(layerEvent.getArg('entity'))
|
||||
self.toLower(layerEvent.getArg(u'entity'))
|
||||
return True
|
||||
elif layerEvent.getName() == YowsupAppLayer.SEND_IQ:
|
||||
iq = layerEvent.getArg('iq')
|
||||
success = layerEvent.getArg('success')
|
||||
failure = layerEvent.getArg('failure')
|
||||
iq = layerEvent.getArg(u'iq')
|
||||
success = layerEvent.getArg(u'success')
|
||||
failure = layerEvent.getArg(u'failure')
|
||||
self._sendIq(iq, success, failure)
|
||||
return True
|
||||
return False
|
||||
|
||||
@ProtocolEntityCallback('success')
|
||||
@ProtocolEntityCallback(u'success')
|
||||
def onAuthSuccess(self, entity):
|
||||
# entity is SuccessProtocolEntity
|
||||
status = entity.status
|
||||
|
@ -587,21 +587,21 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
expiration = entity.expiration
|
||||
props = entity.props
|
||||
nonce = entity.nonce
|
||||
t = entity.t # I don't know what this is
|
||||
t = entity.t # I donu't know what this is
|
||||
self.caller.onAuthSuccess(status, kind, creation, expiration, props, nonce, t)
|
||||
|
||||
@ProtocolEntityCallback('failure')
|
||||
@ProtocolEntityCallback('failureu')
|
||||
def onAuthFailure(self, entity):
|
||||
# entity is FailureProtocolEntity
|
||||
reason = entity.reason
|
||||
self.caller.onAuthFailure(reason)
|
||||
|
||||
@ProtocolEntityCallback('receipt')
|
||||
@ProtocolEntityCallback('receiptu')
|
||||
def onReceipt(self, entity):
|
||||
"""Sends ack automatically"""
|
||||
# entity is IncomingReceiptProtocolEntity
|
||||
ack = OutgoingAckProtocolEntity(entity.getId(),
|
||||
'receipt', entity.getType(), entity.getFrom())
|
||||
'receiptu', entity.getType(), entity.getFrom())
|
||||
self.toLower(ack)
|
||||
_id = entity._id
|
||||
_from = entity._from
|
||||
|
@ -612,7 +612,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
items = entity.items
|
||||
self.caller.onReceipt(_id, _from, timestamp, type, participant, offline, items)
|
||||
|
||||
@ProtocolEntityCallback('ack')
|
||||
@ProtocolEntityCallback('acku')
|
||||
def onAck(self, entity):
|
||||
# entity is IncomingAckProtocolEntity
|
||||
self.caller.onAck(
|
||||
|
@ -622,7 +622,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
entity.timestamp
|
||||
)
|
||||
|
||||
@ProtocolEntityCallback('notification')
|
||||
@ProtocolEntityCallback('notificationu')
|
||||
def onNotification(self, entity):
|
||||
"""
|
||||
Sends ack automatically
|
||||
|
@ -635,11 +635,11 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
self.caller.onParticipantsAddedToGroup(entity)
|
||||
elif isinstance(entity, RemoveGroupsNotificationProtocolEntity):
|
||||
self.caller.onParticipantsRemovedFromGroup(
|
||||
entity.getGroupId().split('@')[0],
|
||||
entity.getGroupId().split('@u')[0],
|
||||
entity.getParticipants().keys()
|
||||
)
|
||||
|
||||
@ProtocolEntityCallback('message')
|
||||
@ProtocolEntityCallback('messageu')
|
||||
def onMessageReceived(self, entity):
|
||||
self.logger.debug("Received Message: %s", entity)
|
||||
if entity.getType() == MessageProtocolEntity.MESSAGE_TYPE_TEXT:
|
||||
|
@ -677,7 +677,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
elif isinstance(entity, LocationMediaMessageProtocolEntity):
|
||||
self.caller.onLocation(entity)
|
||||
|
||||
@ProtocolEntityCallback('presence')
|
||||
@ProtocolEntityCallback('presenceu')
|
||||
def onPresenceReceived(self, presence):
|
||||
_type = presence.getType()
|
||||
name = presence.getName()
|
||||
|
@ -685,7 +685,7 @@ class YowsupAppLayer(YowInterfaceLayer):
|
|||
last = presence.getLast()
|
||||
self.caller.onPresenceReceived(_type, name, _from, last)
|
||||
|
||||
@ProtocolEntityCallback('chatstate')
|
||||
@ProtocolEntityCallback('chatstateu')
|
||||
def onChatstate(self, chatstate):
|
||||
number = chatstate._from.split('@')[0]
|
||||
if chatstate.getState() == ChatstateProtocolEntity.STATE_TYPING:
|
||||
|
|
Loading…
Reference in a new issue