CloudtipsAPI
Неофициальная асинхронная Python-библиотека для CloudTips — получение донатов, поллинг новых поступлений и автоматическое обновление токенов.
Установка
pip install cloudtips
Быстрый старт
import asyncio
import json
from cloudtips import CloudTipsAuth, CloudTipsClient, TokenData
with open("donate.json") as f:
config = json.load(f)
# Колбэк вызывается каждый раз при обновлении токенов.
# Поддерживаются как async, так и обычные функции.
# Refresh-токен одноразовый — обязательно сохраняйте новые!
async def on_token_refresh(token_data: TokenData):
config["cloudtips_token"] = token_data.access_token
config["cloudtips_refresh_token"] = token_data.refresh_token
config["cloudtips_expires_at"] = token_data.expires_at
with open("donate.json", "w") as f:
json.dump(config, f, ensure_ascii=False, indent=2)
auth = CloudTipsAuth(
token=config["cloudtips_token"],
refresh_token=config["cloudtips_refresh_token"],
expires_at=config["cloudtips_expires_at"],
on_token_refresh=on_token_refresh,
)
async def main():
async with CloudTipsClient(auth) as client:
donations = await client.get_all_donations()
for d in donations:
print(d)
# [2024-01-15 14:30] Антон → 100₽ — "спасибо за контент"
asyncio.run(main())
Получение донатов
async with CloudTipsClient(auth) as client:
# Все донаты за последние 24 часа
donations = await client.get_all_donations()
for d in donations:
print(d.name) # Антон
print(d.amount) # 50.0
print(d.comment) # спасибо за сервис
print(d.date) # 2026-04-10 20:44:00+03:00
# За конкретный период
from datetime import datetime, timedelta, timezone
week_ago = datetime.now(tz=timezone.utc) - timedelta(days=7)
weekly = await client.get_all_donations(since=week_ago)
print(f"Всего за неделю: {len(weekly)} донатов")
print(f"Сумма: {sum(d.amount for d in weekly)}₽")
Поллинг новых донатов
Вариант 1 — async-генератор
async with CloudTipsClient(auth) as client:
async for donation in client.poll(interval=30):
print(f"💰 {donation.name} задонатил {donation.amount}₽")
if donation.comment:
print(f" Комментарий: {donation.comment}")
Вариант 2 — async-колбэк
async def handle_donation(donation):
print(f"Новый донат от {donation.name}: {donation.amount}₽")
# await bot.send_message(...)
async with CloudTipsClient(auth) as client:
async for _ in client.poll(interval=15, callback=handle_donation):
pass
Вариант 3 — фоновая задача asyncio
async def poll_task(client):
async for donation in client.poll(interval=30):
print(f"Новый донат: {donation}")
async def main():
async with CloudTipsClient(auth) as client:
task = asyncio.create_task(poll_task(client))
await asyncio.sleep(3600) # работаем час
task.cancel()
asyncio.run(main())
Профиль, карты и баланс
async with CloudTipsClient(auth) as client:
# Профиль пользователя
me = await client.get_me()
print(me.full_name) # Иван Иванов
print(me.payout_method) # Accumulation
# Привязанные карты
for card in await client.get_cards():
print(card) # MIR *0000 (T-BANK, до 00/00) [по умолчанию]
# Баланс к выводу
s = await client.get_accumulation_summary()
print(f"Накоплено: {s.accumulated_amount}₽")
print(f"Комиссия: {s.commission_percent}%")
print(f"Следующая выплата: {s.next_payout_date or 'не запланирована'}")
# Информация о комиссиях
fee = await client.get_payout_fee_info()
print(fee.text)
# Смена метода выплат
await client.set_payout_method("Instant") # мгновенно
await client.set_payout_method("Accumulation") # накопительно
# Удаление карты
for card in await client.get_cards():
if not card.is_default:
await client.delete_card(card.token)
Обработка ошибок
from cloudtips import CloudTipsAuthError, CloudTipsAPIError
try:
async with CloudTipsClient(auth) as client:
donations = await client.get_all_donations()
except CloudTipsAuthError as e:
print(f"Проблема с аутентификацией: {e}")
except CloudTipsAPIError as e:
print(f"Ошибка API (HTTP {e.status_code}): {e.detail}")
Примечания
- Refresh-токен одноразовый. После каждого обновления старый токен становится недействительным. Всегда передавайте
on_token_refreshи сохраняйте новые токены. on_token_refreshподдерживает как обычные (def), так и async-функции (async def).- Библиотека автоматически обновляет токен за 2 минуты до истечения.
- Поллинг отслеживает уже виденные
transaction_id, поэтому дублей не будет. - Клиент — контекстный менеджер (
async with), это рекомендуемый способ использования. - Для логирования внутренних процессов и ошибок сети библиотека использует стандартный модуль
logging. Настройте ваш логгер для отображения сообщений:logging.basicConfig(level=logging.INFO).
Лицензия
MIT
Metadata
Release files for cloudtips 0.4.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cloudtips-0.4.1.tar.gz | 19.6 kB | Without provenance | Details for cloudtips-0.4.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cloudtips-0.4.1-py3-none-any.whl | Python 3 | none | any | Details for cloudtips-0.4.1-py3-none-any.whl |
Total release size: 32.7 kB
Release files / cloudtips-0.4.1.tar.gz
| Download URL | cloudtips-0.4.1.tar.gz |
|---|---|
| Size | 19.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3e4bcc79928c5b28c42c44d6539d3260a78ceae5d202e056a77313a38230eaa3
|
|
BLAKE2b-256 checksum How to use checksums |
4d132e0bfcc286b57887a0aacb83360a6c7ef39cac5cbbb135a20e120df08efb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Release files / cloudtips-0.4.1-py3-none-any.whl
| Download URL | cloudtips-0.4.1-py3-none-any.whl |
|---|---|
| Size | 13.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1609cce3cb553fb111d3840e48d194d27c2c8344552e84aaa60d7adfaeee7f5c
|
|
BLAKE2b-256 checksum How to use checksums |
328ed902cc5af8d7df5e4065a2219c4c302d86b14ab20fe47adc30e81f6fc4d8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
Security for cloudtips 0.4.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.