Use methods provided in vk_api for supporting conversations

This commit is contained in:
Manuel Cortez 2018-12-09 07:25:30 -06:00
parent ba5d734a05
commit feb3215745
5 changed files with 41 additions and 28 deletions

View File

@ -611,6 +611,7 @@ class empty(object):
def remove_buffer(self, mandatory=False): return False def remove_buffer(self, mandatory=False): return False
class chatBuffer(baseBuffer): class chatBuffer(baseBuffer):
random_id = 1
def insert(self, item, reversed=False): def insert(self, item, reversed=False):
""" Add a new item to the list. Uses session.composefunc for parsing the dictionary and create a valid result for putting it in the list.""" """ Add a new item to the list. Uses session.composefunc for parsing the dictionary and create a valid result for putting it in the list."""
@ -706,11 +707,15 @@ class chatBuffer(baseBuffer):
def _send_message(self, text): def _send_message(self, text):
# try: # try:
# Let's take care about the random_id attribute.
# This should be unique per message and should be changed right after the message has been sent.
# If the message is tried to be sent twice this random_id should be the same for both copies.
# At the moment we just calculate len(text)_user_id, hope that will work.
random_id = "{0}_{1}".format(len(text), self.kwargs["user_id"])
if hasattr(self, "attachments_to_be_sent"): if hasattr(self, "attachments_to_be_sent"):
response = self.session.vk.client.messages.send(user_id=self.kwargs["user_id"], message=text, attachment=self.attachments_to_be_sent) response = self.session.vk.client.messages.send(user_id=self.kwargs["user_id"], message=text, attachment=self.attachments_to_be_sent, random_id=random_id)
print self.attachments_to_be_sent
else: else:
response = self.session.vk.client.messages.send(user_id=self.kwargs["user_id"], message=text) response = self.session.vk.client.messages.send(user_id=self.kwargs["user_id"], message=text, random_id=random_id)
# except VkAPIMethodError as ex: # except VkAPIMethodError as ex:
# if ex.code == 9: # if ex.code == 9:
# output.speak(_(u"You have been sending a message that is already sent. Try to update the buffer if you can't see the new message in the history.")) # output.speak(_(u"You have been sending a message that is already sent. Try to update the buffer if you can't see the new message in the history."))

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import threading import threading
from mysc import longpoll from vk_api.longpoll import VkLongPoll, VkEventType
from pubsub import pub from pubsub import pub
from logging import getLogger from logging import getLogger
log = getLogger("controller.longpolThread") log = getLogger("controller.longpolThread")
@ -8,15 +8,19 @@ log = getLogger("controller.longpolThread")
class worker(threading.Thread): class worker(threading.Thread):
def __init__(self, session): def __init__(self, session):
super(worker, self).__init__() super(worker, self).__init__()
log.debug("Instanciating longPoll server") log.debug("Instantiating longPoll server")
self.session = session self.session = session
self.l = longpoll.LongPoll(self.session.vk.client) self.longpoll = VkLongPoll(self.session.vk.session_object)
def run(self): def run(self):
while self.session.is_logged == True: print("starting events")
log.debug("Calling to check...") for event in self.longpoll.listen():
p = self.l.check() print(event)
# log.debug("check has returned " + p) if event.type == VkEventType.MESSAGE_NEW:
for i in p: pub.sendMessage("order-sent-message", obj=event)
if i.text != None and i.from_id != None and i.flags != None and i.message_flags != None: elif event.type == VkEventType.USER_ONLINE:
pub.sendMessage("order-sent-message", obj=i) print "User online"
print event.user_id
elif event.type == VkEventType.USER_OFFLINE:
print "User offline"
print event.user_id

View File

@ -373,15 +373,18 @@ class Controller(object):
""" Searches or creates a chat buffer with the id of the user that is sending or receiving a message. """ Searches or creates a chat buffer with the id of the user that is sending or receiving a message.
obj mysc.longpoll.event: an event wich defines some data from the vk's long poll server.""" obj mysc.longpoll.event: an event wich defines some data from the vk's long poll server."""
print obj print obj
# Set user_id to the id of the friend wich is receiving or sending the message. if obj.to_me:
obj.user_id = obj.from_id buffer = self.search_chat_buffer(obj.user_id)
buffer = self.search_chat_buffer(obj.user_id) uid = obj.user_id
else:
buffer = self.search_chat_buffer(obj.peer_id)
uid = obj.peer_id
if buffer == None: if buffer == None:
wx.CallAfter(self.chat_from_id, obj.user_id) wx.CallAfter(self.chat_from_id, uid)
self.session.soundplayer.play("chat.ogg") self.session.soundplayer.play("chat.ogg")
return return
# If the chat already exists, let's create a dictionary wich will contains data of the received message. # If the chat already exists, let's create a dictionary wich will contains data of the received message.
message = {"id": obj.message_id, "user_id": obj.user_id, "date": obj.timestamp, "body": obj.text, "attachments": obj.attachments} message = {"id": obj.message_id, "user_id": uid, "date": obj.timestamp, "body": obj.text, "attachments": obj.attachments}
# if attachments is true, let's request for the full message with attachments formatted in a better way. # if attachments is true, let's request for the full message with attachments formatted in a better way.
# Todo: code improvements. We shouldn't need to request the same message again just for these attachments. # Todo: code improvements. We shouldn't need to request the same message again just for these attachments.
if len(message["attachments"]) != 0: if len(message["attachments"]) != 0:
@ -389,10 +392,10 @@ class Controller(object):
results = self.session.vk.client.messages.getById(message_ids=message_ids) results = self.session.vk.client.messages.getById(message_ids=message_ids)
message = results["items"][0] message = results["items"][0]
# If outbox it's true, it means that message["from_id"] should be the current user. If not, the obj.user_id should be taken. # If outbox it's true, it means that message["from_id"] should be the current user. If not, the obj.user_id should be taken.
if obj.message_flags.has_key("outbox") == True: if obj.from_me:
message["from_id"] = self.session.user_id message["from_id"] = self.session.user_id
else: else:
message["from_id"] = obj.from_id message["from_id"] = obj.user_id
data = [message] data = [message]
# Let's add this to the buffer. # Let's add this to the buffer.
# ToDo: Clean this code and test how is the database working with this set to True. # ToDo: Clean this code and test how is the database working with this set to True.

View File

@ -114,6 +114,7 @@ class vkSession(object):
self.vk.login(self.settings["vk"]["user"], self.settings["vk"]["password"]) self.vk.login(self.settings["vk"]["user"], self.settings["vk"]["password"])
self.settings["vk"]["token"] = self.vk.client._session.access_token self.settings["vk"]["token"] = self.vk.client._session.access_token
self.settings.write() self.settings.write()
self.logged = True
except ValueError: except ValueError:
self.settings["vk"]["user"] = "" self.settings["vk"]["user"] = ""
self.settings["vk"]["password"] = "" self.settings["vk"]["password"] = ""

View File

@ -12,20 +12,20 @@ class vkObject(object):
def login(self, user, password): def login(self, user, password):
log.debug("Logging in vk using user/password authentication") log.debug("Logging in vk using user/password authentication")
vk_session = vk_api.VkApi(app_id=self.api_key, login=user, password=password, scope="wall, notify, friends, photos, audio, video, docs, notes, pages, status, groups, messages, notifications, stats") self.session_object = vk_api.VkApi(app_id=self.api_key, login=user, password=password, scope="wall, notify, friends, photos, audio, video, docs, notes, pages, status, groups, messages, notifications, stats")
vk_session.auth() self.session_object.auth()
self.client = vk_session.get_api() self.client = self.session_object.get_api()
# self.client = API(s, v=self.api_version) # self.client = API(s, v=self.api_version)
log.debug("Getting tokens for 24 hours...") log.debug("Getting tokens for 24 hours...")
self.client.account.getProfileInfo() self.client.account.getProfileInfo()
# Add session data to the application statistics. # Add session data to the application statistics.
self.client.stats.trackVisitor() self.client.stats.trackVisitor()
self.client_audio = VkAudio(vk_session) self.client_audio = VkAudio(self.session_object)
def login_access_token(self, token): def login_access_token(self, token):
log.debug("Logging in VK using stored tokens...") log.debug("Logging in VK using stored tokens...")
vk_session = vk_api.VkApi(app_id=self.api_key, token=token, scope="wall, notify, friends, photos, audio, video, docs, notes, pages, status, groups, messages, notifications, stats") self.session_object = vk_api.VkApi(app_id=self.api_key, token=token, scope="wall, notify, friends, photos, audio, video, docs, notes, pages, status, groups, messages, notifications, stats")
vk_session.auth() self.session_object.auth()
self.client = vk_session.get_api() self.client = self.session_object.get_api()
self.client_audio = VkAudio(vk_session) self.client_audio = VkAudio(self.session_object)
return self.client.account.getProfileInfo() return self.client.account.getProfileInfo()