def doRepostForFriends(self, identifier, message): if not isinstance(message, str): message = '' try: api = vk.api() response = api.wall.repost(object=identifier, message=message) print('doRepostForFriends response: ' + json.dumps(response)) ''' def updateCache(): likesCount = response.get('likes') if isinstance(likesCount, int): cache = PostsDatabase() data = cache.getById(ownerId, itemId) likes = data['likes'] likes['count'] = likesCount likes['user_likes'] = 1 if like == True else 0 data['likes'] = likes cache.update([data]) cache.close() thread = threading.Thread(target=updateCache) thread.start() ''' except Exception as e: print('doRepostForFriends exception: ' + str(e)) return response
def createPost(self, ownerId, text): response = None try: api = vk.api() response = api.wall.post(owner_id=ownerId, message=text) except Exception as e: print('CreatePostService exception: ' + str(e)) return response
def doConnect(self): currentThread = self.longPollThread api = vk.api() response = api.messages.getLongPollServer(need_pts=need_pts, lp_version=lp_version) self.connectToLongPollServer(response['key'], response['server'], response['ts'], response['pts'], currentThread)
def report(self, type, ownerId, itemId): response = False results = 0 dialogsManager = PyDialogsManager() try: api = vk.api() if type == 'post': results = api.wall.reportPost(owner_id=ownerId, post_id=itemId) elif type == 'user': items = ['p**n', 'spam', 'insult', 'advertisment'] index, cancelled = dialogsManager.showRowsDialogWithTitles( items) if cancelled: return type = items[index] message, cancelled = dialogsManager.showTextFieldDialogWithText( 'enter_report_message') if cancelled: return results = api.users.report(user_id=ownerId, type=type, comment=message) elif type == 'photo': results = api.photos.report(owner_id=ownerId, photo_id=itemId) elif type == 'video': message, cancelled = dialogsManager.showTextFieldDialogWithText( 'enter_report_message') if cancelled: return results = api.video.report(owner_id=ownerId, video_id=itemId, comment=message) elif type == 'post_comment': results = api.wall.reportComment(owner_id=ownerId, comment_id=itemId) elif type == 'photo_comment': results = api.photos.reportComment(owner_id=ownerId, comment_id=itemId) elif type == 'video_comment': results = api.video.reportComment(owner_id=ownerId, comment_id=itemId) else: raise ValueError('unsupported type of item for report') if isinstance(results, int) and results == 1: response = True except Exception as e: print('posts report exception: ' + str(e)) if response == False: print('report send failed with results: ' + str(results)) dialogsManager.showDialogWithMessage('error_reporting') else: dialogsManager.showDialogWithMessage('report_sended_successfully') print('report sended successfully for type: ' + str(type)) pass
def getPhoto(self, ownerId, photoId): api = vk.api() items = None try: cache = PhotosDatabase() items = cache.getPhoto(ownerId, photoId) cache.close() except Exception as e: print('DetailPhotoService getPhoto exception: ' + str(e)) return items
def getAllFromCache(self, ownerId, albumId): api = vk.api() items = None try: cache = PhotosDatabase() items = cache.getAll(ownerId, albumId) cache.close() except Exception as e: print('getAllFromCache exception: ' + str(e)) return {'items': items}
def joinOrLeaveGroup(self, is_member): response = {} try: api = vk.api() if is_member == 0: response = api.groups.join(group_id=abs(self.userId)) else: response = api.groups.leave(group_id=abs(self.userId)) except Exception as e: print('wallviewmodel.py joinOrLeaveGroup exception: ' + str(e)) return response
def sendComment(self, ownerId, postId, messsage, reply_to_comment=0): result = None try: api = vk.api() result = api.wall.createComment(owner_id=ownerId, post_id=postId, text=messsage, reply_to_comment=reply_to_comment) except Exception as e: print('wallService: sendComments exception: ' + str(e)) return result
def sendComment(self, ownerId, postId, messsage, reply_to_comment=0): result = None try: api = vk.api() result = api.video.createComment(owner_id=ownerId, video_id=postId, message=messsage, reply_to_comment=reply_to_comment) except Exception as e: print('DetailVideoService: sendComment exception: ' + str(e)) return result
def getFriendsIds(self, userId, offset, usersListType): api = vk.api() try: friendsArray = [] db = FriendsDatabase() ''' if usersListType == UsersListTypes.FRIENDS: friendsArray = db.getFriendsIds(userId, offset, g_count) if not friendsArray: friendsArray = [] ''' if len(friendsArray) >= g_count: result = [d.get('id') for d in friendsArray] print('results from db: ' + str(len(result))) return result if usersListType == UsersListTypes.SUBSCRIPTIONS: print('usersListType offset: ' + str(offset)) response = api.users.getSubscriptions(user_id=userId, extended=1, offset=offset, count=g_count) elif usersListType == UsersListTypes.FOLLOWERS: response = api.users.getFollowers(user_id=userId, offset=offset, count=g_count) else: response = api.friends.get(offset=offset, count=g_count, order='mobile', user_id=userId) l = response['items'] if usersListType == UsersListTypes.SUBSCRIPTIONS: ar = [] for d in l: if d.get('type') == 'page': ar.append(-d.get('id')) elif d.get('type') == 'profile': ar.append(d.get('id')) l = ar print('usersListType l: ' + str(l)) count = response['count'] if usersListType == UsersListTypes.FRIENDS: db.appendFriendsIds(l) db.close() return l except ConnectionError as e: raise e except Exception as e: print('getFriendsIds exception: ' + str(e)) return []
def doUnbanUser(self, userId): result = 0 try: api = vk.api() result = api.account.unban(owner_id=userId) except Exception as e: print('unbanUser exception: ' + str(e)) if not isinstance(result, int) or result != 1: message = 'error_unban_user' if userId > 0 else 'error_unban_group' dialogsManager = PyDialogsManager() dialogsManager.showDialogWithMessage(message) return False return True
def downloadMessageById(self, messageId): msg = {} try: api = vk.api() response = api.messages.getById(message_ids=str(messageId)) dialogservice.updateMessagesResponseWithUsers(response) if isinstance(response, dict): l = response.get('items') if isinstance(l, list) and len(l) > 0: msg = l[0] print('downloaded msg: ' + json.dumps(msg, indent=4)) except Exception as e: print('downloadMessageById exception: ' + str(e)) return msg
def getWallComments(self, ownerId, postId, offset, count): result = {} try: api = vk.api() result = api.wall.getComments(owner_id=ownerId, post_id=postId, offset=offset, count=count, extended=1) self.processResult(result) l = result['items'] cache = CommentsDatabase() cache.update(l) cache.close() except Exception as e: print('getWallComments exception: ' + str(e)) print(traceback.format_exc()) return result
def likeObjectWithTypeownerIditemIdaccessKeylike(self, type, ownerId, itemId, accessKey, like): analytics.log('Posts_like') try: if type == 'wall': type = 'post' api = vk.api() #print('type: ' + str(type) + ' ownerId ' + str(ownerId) + ' itemId ' + str(itemId) + ' accessKey ' + str(accessKey) + ' like ' + str(like)) if like == True: response = api.likes.add(type=type, owner_id=ownerId, item_id=itemId, access_key=accessKey) else: response = api.likes.delete(type=type, owner_id=ownerId, item_id=itemId) def updateCache(): likesCount = response.get('likes') if isinstance(likesCount, int): if type == 'wall': cache = PostsDatabase() data = cache.getById(ownerId, itemId) likes = data['likes'] likes['count'] = likesCount likes['user_likes'] = 1 if like == True else 0 data['likes'] = likes cache.update([data]) cache.close() elif type == 'video': cache = VideosDatabase() data = cache.getById(ownerId, itemId) print('video data: ' + json.dumps(data, indent=4)) likes = data['likes'] likes['count'] = likesCount likes['user_likes'] = 1 if like == True else 0 data['likes'] = likes cache.update([data]) cache.close() thread = threading.Thread(target=updateCache) thread.start() except Exception as e: print('likeObjectWithTypeownerIditemIdaccessKeylike exception: ' + str(e)) return response
def getBanned(self, offset): response = None count = 0 try: api = vk.api() response = api.account.getBanned(offset=offset, count=g_count) l = response['items'] count = len(l) ids = [d['id'] for d in l] usersData = users.getShortUsersByIds(set(ids)) response['items'] = usersData except Exception as e: print('getBanned exception: ' + str(e)) print(traceback.format_exc()) return response, count
def getPhotos(self, ownerId, albumId, offset, count): response = None try: api = vk.api() response = api.photos.get(owner_id=ownerId, album_id=albumId, offset=offset, count=count, extended=1) l = response['items'] #print('photos.get resp: ' + json.dumps(response, indent=4)) cache = PhotosDatabase() cache.update(l) cache.close() except ConnectionError as e: raise e except Exception as e: print('getPhotos exception: ' + str(e)) return response
def getVideoComments(self, ownerId, videoId, offset, count): api = vk.api() result = None try: result = api.video.getComments(owner_id=ownerId, video_id=videoId, offset=offset, count=count, extended=1) self.processResult(result) l = result['items'] ''' cache = CommentsDatabase() cache.update(l) cache.close() ''' except Exception as e: print('getVideoComments: get comments exception: ' + str(e)) return result
def didRegisterForRemoteNotificationsWithDeviceTokendeviceId( self, token, deviceId): print('didRegisterForRemoteNotificationsWithDeviceToken: ' + str(token) + '; deviceId: ' + str(deviceId)) api = vk.api() try: response = api.account.registerDevice(token=token, device_id=deviceId, sandbox=0, settings=json.dumps( {'msg': 'on'})) print('registerDevice response: ' + str(response)) except Exception as e: print('send device token exception: ' + str(e)) pass
def getDialogs(self, offset): api = vk.api() response = None usersData = None try: response = api.messages.getDialogs(offset=offset, count=g_LoadingElements) l = response["items"] #print('response dialogs: ' + json.dumps(response, indent=4)) ids = set([d['message']['user_id'] for d in l]) usersData = users.getShortUsersByIds(ids) except ConnectionError as e: raise e except Exception as e: print('get dialogs exception: ' + str(e)) return {'response': response, 'users': usersData}
def hideSource(self, userId): results = 0 try: api = vk.api() if userId > 0: results = api.newsfeed.addBan(user_ids=userId) elif userId < 0: results = api.newsfeed.addBan(group_ids=abs(userId)) else: raise ValueError('userId on hideSource is 0') except Exception as e: print('hideSource exception: ' + str(e)) if not isinstance(results, int) or results != 1: dialogsManager = PyDialogsManager() dialogsManager.showDialogWithMessage('error_ignore_item')
def getDocuments(self, ownerId, offset): api = vk.api() response = None count = 0 try: response = api.docs.get(owner_id=ownerId, offset=offset) l = response['items'] count = len(l) cache = DocumentsDatabase() cache.update(l) cache.close() except Exception as e: print('getDocuments exception: ' + str(e)) return {'response': response}, count
def updateVideo(self, ownerId, videoId): result = {} try: api = vk.api() result = api.video.get(videos=str(ownerId) + '_' + str(videoId), extended=1) textpatcher.cropTagsInResults(result, 'description') items = result['items'] cache = VideosDatabase() cache.update(items) cache.close() representation = items[0] if isinstance(representation, dict): result = representation except Exception as e: print('DetailVideoService: updateVideo exception: ' + str(e)) return result
def getAnswers(self, offset, next_from): response = None usersData = None try: api = vk.api() if isinstance(next_from, str): response = api.notifications.get(start_from=next_from) else: response = api.notifications.get() next_from = response.get('next_from') print('answers response: ' + json.dumps(response, indent=4)) l = response["items"] usersData = self.usersDecorator.usersDataFromAnswers(l) except Exception as e: print('getAnswers.get exception: ' + str(e)) results = {'response': response, 'users': usersData} return results, next_from
def getVideos(self, ownerId, offset): api = vk.api() response = None count = 0 try: response = api.video.get(owner_id=ownerId, offset=offset, extended=1) l = response['items'] #print('videos l: ' + json.dumps(l, indent=4)) count = len(l) cache = VideosDatabase() cache.update(l) cache.close() except ConnectionError as e: raise e except Exception as e: print('getVideos exception: ' + str(e)) return {'response': response}, count
def performLongPollHistory(self): try: api = vk.api() response = api.messages.getLongPollHistory(ts=self.ts, pts=self.pts) history = response.get('history') messages = response.get('messages') #print('longpoll response is: ' + str(response)) if isinstance(messages, dict): l = messages.get('items') if isinstance(l, list): cache = MessagesDatabase() cache.update(l) cache.close() if isinstance(history, list): threading.Thread(target=partial(parseUpdates, history)).start() except Exception as e: print('performLongPollHistory exception: ' + str(e)) pass
def getPhotoAlbums(self, ownerId, offset): api = vk.api() response = None try: response = api.photos.getAlbums(owner_id=ownerId, offset=offset, count=g_count, need_system=1, need_covers=1, photo_sizes=1) l = response['items'] cache = PhotoAlbumsDatabase() cache.update(l) cache.close() except ConnectionError as e: raise e except Exception as e: print('getPhotoAlbums exception: ' + str(e)) return response
def deleteComment(self, type, ownerId, commentId, parentItemOwnerId): results = 0 try: api = vk.api() if type == 'post_comment': results = api.wall.deleteComment(owner_id=parentItemOwnerId, comment_id=commentId) elif type == 'photo_comment': results = api.photos.deleteComment(owner_id=parentItemOwnerId, comment_id=commentId) elif type == 'video_comment': results = api.video.deleteComment(owner_id=parentItemOwnerId, comment_id=commentId) except Exception as e: print('deleteComment exception: ' + str(e)) if not isinstance(results, int) or results != 1: dialogsManager = PyDialogsManager() dialogsManager.showDialogWithMessage('error_delete_comment') else: self.guiDelegate.commentDeleted()
def getWall(self, offset, userId, count): print('getWall userId: ' + str(userId)) response = None usersData = None try: api = vk.api() response = api.wall.get(offset=offset, owner_id=userId, count=count) textpatcher.cropTagsOnPostsResults(response) l = response["items"] #print('wall response: ' + json.dumps(l, indent=4)) cache = PostsDatabase() cache.update(l) cache.close() usersData = self.usersDecorator.usersDataFromPosts(l) except Exception as e: print('wall.get exception: ' + str(e)) results = {'response':response, 'users':usersData} return results
def getGroups(self, userId, offset): api = vk.api() response = None usersData = None count = 0 try: response = api.groups.get(user_id=userId, offset=offset, count=g_count) l = response['items'] #print('groups.get response is: ' + json.dumps(response, indent=4)) count = len(l) gl = [-id for id in l] response['items'] = gl usersData = users.getShortUsersByIds(set(gl)) except ConnectionError as e: raise e except Exception as e: print('groups.get exception: ' + str(e)) return {'response': response, 'users': usersData}, count
def blockUser(self, userId): result = 0 try: api = vk.api() result = api.account.ban(owner_id=userId) except VkAPIError as e: if 'already blacklisted' in e.message: result = 2 except Exception as e: print('blockUser exception: ' + str(e)) message = "" if isinstance(result, int) and result == 2: message = 'already_blacklisted' elif not isinstance(result, int) or result != 1: message = 'error_ban_user' if userId > 0 else 'error_ban_group' else: message = 'user_successfully_banned' if userId > 0 else 'group_successfully_banned' dialogsManager = PyDialogsManager() dialogsManager.showDialogWithMessage(message)