An API wrapper for Sferum.
Project description
Sferum API Interface
The Sferum API Interface provides methods to interact with the VK messaging service through API endpoints. This project includes functions for sending messages, retrieving user history, and executing JS-like code code on the server.
Getting Started
Prerequisites
- Python 3.x
Instaling
To install this lib run this in terminal:
pip install SferumBridge
Obtaining the remixdsid Cookie
To interact with VK's API, you'll need to authenticate your session and obtain the remixdsid cookie. Follow these steps:
-
Open your web browser and go to sferum web version.
-
Log in to your VK account if you haven't already.
-
After logging in, open the Developer Tools in your web browser (right-click anywhere on the page and select "Inspect" or press
F12). -
Navigate to the "Application" tab in Developer Tools.
-
On the left sidebar, find and click on "Cookies" under the "Storage" section. You should see a list of cookies that belong to the
https://web.vk.medomain. -
Look for the
remixdsidcookie. This cookie is usually a long alphanumeric string. -
Copy the value of the
remixdsidcookie. You will use this value to authenticate your requests in the SferumAPI class.
Using the Sferum API Interface
Initializing the SferumAPI class
To create an instance of the SferumAPI, you need to pass the remixdsid obtained from the previous step:
import SferumBridge
remixdsid = 'YOUR_REMIXDSID_COOKIE_HERE'
api = SferumAPI(remixdsid)
Available Methods
peer_id is a chat id. You can get it from the URL:
web.vk.me/convo/YOUR_CHAT_ID
-
Sending a Message:
To send a message, use:
response = api.send_message(peer_id=12345678, text="Hello, World!")
-
Deleting a Message:
To delete a message, use:
response = api.delete_message(peer_id=12345678, message_conversation_id=321)
-
Retrieving Message History:
To retrieve message history, use:
response = api.get_history(peer_id=12345678, count=20)
-
Executing Code:
To execute a small piece of JS-like code on the server, use:
response = api.execute(code=""" var res0=API.messages.delete({"peer_id":2000000002,"cmids":"152","delete_for_all":1,"spam":0,"group_id":0,"lang":"ru"}); return [res0]; """)
You can use
fork()to run task in background andwait()to wait it I found out you can make only 999 cycles inwhileloop and 25 API requestsHere`s more complicated example:
response = api.execute(code=""" return [ wait(fork( API.users.get({ user_ids: 1058611848, fields: 'photo_100,photo_200,sex,screen_name,first_name_gen,is_nft,animated_avatar,custom_names_for_calls', }) )), API.calls.getSettings({}), ]; """)
А теперь на русском
Интерфейс API Sferum предоставляет методы для взаимодействия с сервисом обмена сообщениями VK через API-эндпоинты. Этот проект включает функции для отправки сообщений, получения истории пользователей и выполнения кода, подобного JS, на сервере.
Начало работы
Необходимые условия
- Python 3.x
Установка
Чтобы установить эту библиотеку, выполните следующую команду в терминале:
pip install SferumBridge
Получение cookie remixdsid
Чтобы взаимодействовать с API VK, вам необходимо аутентифицировать сессию и получить cookie remixdsid. Следуйте этим шагам:
-
Откройте веб-браузер и перейдите на веб-версию sferum.
-
Войдите в свою учетную запись VK, если еще не сделали этого.
-
После входа откройте Инструменты разработчика в веб-браузере (щелкните правой кнопкой мыши на любой области страницы и выберите "Просмотреть код" или нажмите
F12). -
Перейдите на вкладку "Приложение" в Инструментах разработчика.
-
В левой боковой панели найдите и кликните на "Cookies" в разделе "Хранилище". Вы должны увидеть список cookie, принадлежащих домену
https://web.vk.me. -
Найдите куку
remixdsid. Эта кука обычно представляет собой длинную строку из буквенно-цифровых символов. -
Скопируйте значение куки
remixdsid. Это значение вам понадобится для аутентификации ваших запросов в классе SferumAPI.
Использование интерфейса API Sferum
Инициализация класса SferumAPI
Чтобы создать экземпляр SferumAPI, вы должны передать remixdsid, полученный на предыдущем шаге:
import SferumBridge
remixdsid = 'ВАША_COOKIE_REMIXDSID_ЗДЕСЬ'
api = SferumAPI(remixdsid)
Доступные методы
peer_id - это ID чата. Вы можете получить его из URL:
web.vk.me/convo/YOUR_CHAT_ID
-
Отправка сообщения:
Чтобы отправить сообщение, используйте:
response = api.send_message(peer_id=12345678, text="Привет, мир!")
-
Удаление сообщения:
Чтобы удалить сообщение, используйте:
response = api.delete_message(peer_id=12345678, message_conversation_id=321)
-
Получение истории сообщений:
Чтобы получить историю сообщений, используйте:
response = api.get_history(peer_id=12345678, count=20)
-
Выполнение кода:
Чтобы выполнить небольшой фрагмент кода, подобного JS, на сервере, используйте:
response = api.execute(code=""" var res0=API.messages.delete({"peer_id":2000000002,"cmids":"152","delete_for_all":1,"spam":0,"group_id":0,"lang":"ru"}); return [res0]; """)
Вы можете использовать
fork()для выполнения задач в фоновом режиме иwait(), чтобы подождать. Я узнал, что вы можете выполнить только 999 циклов в циклеwhileи 25 API-запросов.Вот более сложный пример:
response = api.execute(code=""" return [ wait(fork( API.users.get({ user_ids: 1058611848, fields: 'photo_100,photo_200,sex,screen_name,first_name_gen,is_nft,animated_avatar,custom_names_for_calls', }) )), API.calls.getSettings({}), ]; """)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file sferumbridge-1.0.4.tar.gz.
File metadata
- Download URL: sferumbridge-1.0.4.tar.gz
- Upload date:
- Size: 8.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dd12776709a86887817f133187cb5a13f7a9705c84d104e08d3b0528fddf28a5
|
|
| MD5 |
bb1b875f2a1231fb4f26ecdb963d793a
|
|
| BLAKE2b-256 |
9f05ad67deca5f3b8b467808768d682b970479cb541519f6ae701e7ff53dc713
|
Provenance
The following attestation bundles were made for sferumbridge-1.0.4.tar.gz:
Publisher:
python-publish.yml on Sharkow1743/SferumAPI
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sferumbridge-1.0.4.tar.gz -
Subject digest:
dd12776709a86887817f133187cb5a13f7a9705c84d104e08d3b0528fddf28a5 - Sigstore transparency entry: 273355526
- Sigstore integration time:
-
Permalink:
Sharkow1743/SferumAPI@7d61f3e94d2cd59f81944fc1dd7a766fd5ab4ec2 -
Branch / Tag:
refs/tags/v1.0.4 - Owner: https://github.com/Sharkow1743
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@7d61f3e94d2cd59f81944fc1dd7a766fd5ab4ec2 -
Trigger Event:
release
-
Statement type: