I’m trying to implement VK API, so thanks OAuth code I get a token and just add this scope offline,audio
and now doing this request:
https://api.vk.com/method/account.getInfo?access_token=XXXXX&v=5.62
And go this in return:
{
"error": {
"error_code": 15,
"error_msg": "Access denied: no access to call this method",
"request_params": [
{
"key": "oauth",
"value": "1"
},
{
"key": "method",
"value": "account.getInfo"
},
{
"key": "v",
"value": "5.62"
}
]
}
}
Why, there’s a scope for this too?
Nakilon
34.9k14 gold badges107 silver badges142 bronze badges
asked Jan 19, 2017 at 16:10
Your application isn’t Standalone type or you received access token not via Implicit Flow scheme.
Note: you should set parameter redirect_uri=https://oauth.vk.com/blank.html
to get access token without limitations. In other ways access token will be limited to call methods which available only for standalone applications.
answered Jan 19, 2017 at 22:32
Petr FlaksPetr Flaks
5232 gold badges7 silver badges24 bronze badges
1
I’m trying to implement VK API, so thanks OAuth code I get a token and just add this scope offline,audio
and now doing this request:
https://api.vk.com/method/account.getInfo?access_token=XXXXX&v=5.62
And go this in return:
{
"error": {
"error_code": 15,
"error_msg": "Access denied: no access to call this method",
"request_params": [
{
"key": "oauth",
"value": "1"
},
{
"key": "method",
"value": "account.getInfo"
},
{
"key": "v",
"value": "5.62"
}
]
}
}
Why, there’s a scope for this too?
Nakilon
34.9k14 gold badges107 silver badges142 bronze badges
asked Jan 19, 2017 at 16:10
Your application isn’t Standalone type or you received access token not via Implicit Flow scheme.
Note: you should set parameter redirect_uri=https://oauth.vk.com/blank.html
to get access token without limitations. In other ways access token will be limited to call methods which available only for standalone applications.
answered Jan 19, 2017 at 22:32
Petr FlaksPetr Flaks
5232 gold badges7 silver badges24 bronze badges
1
Написал небольшого бота для личных нужд на python с помощью библиотеки vk_api(хорошо документирована в отличии от vk). Всё было великолепно, прошло фазу теста. А как дело дошло до использования сегодня так получил такую ошибку
vk_api.exceptions.ApiError: [15] Access denied: no access to call this method
сессия начинается так:
login, password = '***', '***'
vk_session = vk_api.VkApi(login, password)
ошибка при обращении к LongPoll серверу тут:
longpoll = VkLongPoll(vk_session, wait=20)
пробовал по-разному указывать scope, и через строку и через число. результат тот же — ошибка доступа
Как исправить это, желательно не переписывая другой библиотекой. Либо же если уж переписывать то посоветуйте библиотеку с хорошей документацией.
Получаю токен через Implicit Flow
https://oauth.vk.com/authorize?client_id={clientId}&redirect_uri={redirectUri}&scope=327680&response_type=token
Приложение Standalone.
Пытаюсь выполнить запрос groups.getRequests
https://api.vk.com/method/groups.getRequests?group_id={groupId}&access_token={accessToken}
Получаю ответ
{"error":{"error_code":15,"error_msg":"Access denied: no access to call this method","request_params":[{"key":"oauth","value":"1"},{"key":"method","value":"groups.getRequests"},{"key":"group_id","value":"xxx"}]}}
Через форму внизу страницы https://vk.com/dev/groups.getRequests запрос успешно выполняется на той же группе.
Другие запросы groups.* (кроме groups.approveRequest, с ним такая же ситуация) выполняются без проблем. Что я делаю не так?
Заметил, если токен получить способом Authorization code flow, то метод работает без ошибок. Хотя в документации сказано (https://vk.com/dev/groups.getRequests) что подойдёт токен полученный через Implicit Flow.
Код, пожалуйте, не работает почему-то создание qr-кода и размытие, он сохраняет qr.jpg, а обратно почему-то не отправляет, код ошибки:
C:UsersUnstaPycharmProjectsuntitledvenvScriptspython.exe C:/Users/Unsta/.PyCharmCE2019.2/config/scratches/scratch_1.py
Traceback (most recent call last):
File «C:/Users/Unsta/.PyCharmCE2019.2/config/scratches/scratch_1.py», line 178, in
main()
File «C:/Users/Unsta/.PyCharmCE2019.2/config/scratches/scratch_1.py», line 132, in main
send_image(event.user_id, ‘На основе Вашего текста «‘ + qr_text + ‘» был сгенерирован QR-код!’, [‘qr.jpg’])
File «C:/Users/Unsta/.PyCharmCE2019.2/config/scratches/scratch_1.py», line 41, in send_image
uploaded_photos = upload.photo_messages(photos)
File «C:UsersUnstaPycharmProjectsuntitledvenvlibsite-packagesvk_apiupload.py», line 93, in photo_messages
url = self.vk.photos.getMessagesUploadServer()[‘upload_url’]
File «C:UsersUnstaPycharmProjectsuntitledvenvlibsite-packagesvk_apivk_api.py», line 681, in call
return self._vk.method(self._method, kwargs)
File «C:UsersUnstaPycharmProjectsuntitledvenvlibsite-packagesvk_apivk_api.py», line 646, in method
raise error
vk_api.exceptions.ApiError: [15] Access denied: no access to call this method
Process finished with exit code 1
Сам код:
import os, qrcode, requests
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from vk_api.utils import get_random_id
from PIL import Image, ImageFilter
from caesar import *
from vigenere import *
vk = vk_api.VkApi(token=’12777***’)
keyboard = VkKeyboard(one_time=False)
keyboard.add_button(‘Шифровка’, color=VkKeyboardColor.POSITIVE)
keyboard.add_button(‘Дешифровка’, color=VkKeyboardColor.NEGATIVE)
keyboard.add_line()
keyboard.add_button(‘Шифр Цезаря’, color=VkKeyboardColor.DEFAULT)
keyboard.add_button(‘Шифр Виженера’, color=VkKeyboardColor.DEFAULT)
keyboard.add_line()
keyboard.add_button(‘Текст’, color=VkKeyboardColor.DEFAULT)
keyboard.add_button(‘Ключ’, color=VkKeyboardColor.DEFAULT)
keyboard.add_line()
keyboard.add_button(‘Результат Шифрования/Дешифрования’, color=VkKeyboardColor.PRIMARY)
keyboard.add_line()
keyboard.add_button(‘Сгенерировать QR-код’, color=VkKeyboardColor.DEFAULT)
keyboard.add_line()
keyboard.add_button(‘Получить размытые фото’, color=VkKeyboardColor.DEFAULT)
longpoll = VkLongPoll(vk)
def send_message(user_id, message):
vk.method(‘messages.send’, {‘user_id’: user_id, ‘message’: message, ‘keyboard’: keyboard.get_keyboard(), ‘random_id’: get_random_id()})
def send_image(user_id, txt_message, photos=[]):
upload = vk_api.VkUpload(vk)
uploaded_photos = upload.photo_messages(photos)
attachments = []
for photo in uploaded_photos:
attachments.append(‘photo{}_{}’.format(photo[‘owner_id’], photo[‘id’]))
vk.method(‘messages.send’, {‘user_id’: user_id, ‘attachment’: ‘,’.join(attachments), ‘message’: txt_message, ‘keyboard’: keyboard.get_keyboard(), ‘random_id’: get_random_id()})
def blur_image(image, counter):
blured_image = Image.open(image).filter(ImageFilter.GaussianBlur(12))
blured_image.save(str(counter) + ‘_blured.jpg’)
def get_image_size(sizes, size_type):
for size in sizes:
if size[‘type’] == size_type:
return size
def download_image(fileLink, counter):
with open(str(counter) + ‘_saved.jpg’, ‘wb’) as handle:
res = requests.get(fileLink, stream = True)
if not res.ok:
print(res)
for block in res.iter_content(1024):
if not block:
break
handle.write(block)
def parse_json_format(attachments):
urls = dict()
for attach in attachments:
photo_id = attach[‘photo’][‘id’]
size = None
for size_type in [‘w’ , ‘y’, ‘z’, ‘x’, ‘m’, ‘s’]:
size = get_image_size(attach[‘photo’][‘sizes’], size_type)
if size is not None:
break
url = size[‘url’]
urls[photo_id] = url
return urls
def main():
mode = ‘Шифровка’
cipher = ‘Шифр Цезаря’
text = ‘python’
key = ‘3’
qr_text = »
photos_id = []
for event in longpoll.listen():
if event.type == VkEventType.MESSAGE_NEW:
if event.to_me:
if event.attachments != {}:
k = list(event.attachments.keys())
counter = 0
for item_type, item_value in event.attachments.items():
if item_value == 'photo':
photos_id.append(event.attachments[k[k.index(item_type) + 1]])
jsonoutput = vk.method('messages.getHistory', {'user_id': event.peer_id, 'count': 1})['items'][0]['attachments']
urls = parse_json_format(jsonoutput)
for photo_id in photos_id:
pid = int(photo_id.split(str(event.user_id) + '_')[1])
if pid in urls:
counter += 1
download_image(urls[pid], counter)
if event.text == 'Получить размытые фото':
counter = 0
for root, dirs, files in os.walk("."):
for filename in files:
if '_saved' in filename:
counter += 1
blur_image(filename, counter)
send_image(event.user_id, 'Размытое фото ' + str(counter) + ':', [filename[0:-9] + 'blured.jpg'])
os.remove(filename)
os.remove(filename[0:-9] + 'blured.jpg')
if 'qr=' in event.text:
qr_text = event.text[3:len(event.text)]
send_message(event.user_id, 'Текст для генерации QR-кода = ' + qr_text)
if 'text=' in event.text:
text = event.text[5:len(event.text)]
send_message(event.user_id, 'Текст = ' + text)
if 'key=' in event.text:
key = event.text[4:len(event.text)]
send_message(event.user_id, 'Ключ = ' + key)
if event.text == 'Сгенерировать QR-код':
if qr_text == '':
send_message(event.user_id, 'Пример ввода текста для генерации QR-кода: qr=word')
else:
qr = qrcode.make(qr_text)
qr.save('qr.jpg')
send_image(event.user_id, 'На основе Вашего текста "' + qr_text + '" был сгенерирован QR-код!', ['qr.jpg'])
os.remove('qr.jpg')
if event.text == 'Шифровка':
mode = 'Шифровка'
send_message(event.user_id, 'Режим работы = Шифрование')
if event.text == 'Дешифровка':
mode = 'Дешифровка'
send_message(event.user_id, 'Режим работы = Дешифрование')
if event.text == 'Текст':
send_message(event.user_id, 'Пример ввода: text=python')
if event.text == 'Ключ':
send_message(event.user_id, 'Пример ввода: key=4')
if event.text == 'Шифр Цезаря':
cipher = 'Шифр Цезаря'
send_message(event.user_id, 'Шифр = метод Цезаря')
if event.text == 'Шифр Виженера':
cipher = 'Шифр Виженера'
send_message(event.user_id, 'Шифр = метод Виженера')
if event.text == 'Результат Шифрования/Дешифрования':
send_message(event.user_id, 'Метод = ' + cipher + 'nРежим работы = ' + mode + 'nТекст = ' + text + 'nКлюч = ' + key)
if cipher == 'Шифр Цезаря':
if mode == 'Шифровка' and key.isdigit():
send_message(event.user_id, 'Результат: ' + encrypt_caesar(text, int(key)))
if mode == 'Дешифровка' and key.isdigit():
send_message(event.user_id, 'Результат: ' + decrypt_caesar(text, int(key)))
if not key.isdigit():
send_message(event.user_id, 'Ключ должен быть числовым!')
if cipher == 'Шифр Виженера':
if mode == 'Шифровка' and not key.isdigit():
if ' ' not in text and ' ' not in key:
send_message(event.user_id, 'Результат: ' + encrypt_vigenere(text, key))
else:
send_message(event.user_id, 'Текст/Ключ содержит пробелы!')
if mode == 'Дешифровка' and not key.isdigit():
if ' ' not in text and ' ' not in key:
send_message(event.user_id, 'Результат: ' + decrypt_vigenere(text, key))
else:
send_message(event.user_id, 'Текст/Ключ содержит пробелы!')
if key.isdigit():
send_message(event.user_id, 'Ключ должен быть буквенным!')
if name == ‘main‘:
main()