Skip to main content

Tweepy-self

Telegram channel PyPI version info PyPI supported Python versions PyPI downloads per month

A modern, easy to use, feature-rich, and async ready API wrapper for Twitter's user API written in Python.

  • Docs (soon)

More libraries of the family:

Отдельное спасибо Кузнице Ботов за код для авторизации и разморозки! Подписывайтесь на их Telegram :)

Key Features

  • Modern Pythonic API using async and await.
  • Prevents user account automation detection.

Installing

pip install tweepy-self

Example

import asyncio
import twitter

account = twitter.Account(auth_token="auth_token")

async def main():
    async with twitter.Client(account) as twitter_client:
        await twitter_client.tweet("Hello, tweepy-self! <3")

asyncio.run(main())

More

Automating user accounts is against the Twitter ToS. This library is a proof of concept and I cannot recommend using it. Do so at your own risk

Документация (устаревшая)

Код ушел немного дальше, чем эта документация.

Библиотека позволяет работать с неофициальным API Twitter, а именно:

  • Логин
  • Анлок
  • Привязывать сервисы (приложения).
  • Устанавливать статус аккаунта (бан, лок).
  • Загружать изображения на сервер и изменять баннер и аватарку.
  • Изменять данные о пользователе: имя, описание профиля и другое.
  • Изменять имя пользователя и пароль.
  • Запрашивать информацию о подписчиках.
  • Запрашивать некоторую информацию о пользователе (количество подписчиков и другое).
  • Голосовать.
  • Подписываться и отписываться.
  • Лайкать и дизлайкать.
  • Твиттить, ретвиттить с изображением и без.
  • Закреплять твиты.
  • Запрашивать твиты пользователей.
  • Удалять твиты.
  • И другое.

Статус аккаунта

После любого взаимодействия с Twitter устанавливается статус аккаунта:

  • BAD_TOKEN - Неверный токен.
  • UNKNOWN - Статус аккаунта не установлен.
  • SUSPENDED - Действие учетной записи приостановлено (бан).
  • LOCKED - Учетная запись заморожена (лок) (требуется прохождение капчи).
  • GOOD - Аккаунт в порядке.

Не каждое взаимодействие с Twitter достоверно определяет статус аккаунта. Например, простой запрос данных об аккаунте честно вернет данные, даже если ваш аккаунт заморожен.

Для достоверной установки статуса аккаунта используйте метод establish_status()

Примеры работы

Запрос информации о пользователе:

# Запрос информации о текущем пользователе:
me = await twitter_client.request_user()
print(f"[{account.short_auth_token}] {me}")
print(f"Аккаунт создан: {me.created_at}")
print(f"Following (подписан ты): {me.followings_count}")
print(f"Followers (подписаны на тебя): {me.followers_count}")
print(f"Прочая информация: {me.raw_data}")

# Запрос информации об ином пользователе:
elonmusk = await twitter.request_user("@elonmusk")
print(elonmusk)

Смена имени пользователя и пароля:

account = twitter.Account("auth_token", password="password")
...
await twitter_client.change_username("new_username")
await twitter_client.request_user()
print(f"New username: {account.username}")

await twitter_client.change_password("new_password")
print(f"New password: {account.password}")
print(f"New auth_token: {account.auth_token}")

Смена данных профиля:

await twitter_client.update_birthdate(day=1, month=12, year=2000)
await twitter_client.update_profile(  # Locks account!
    name="New Name",
    description="New description",
    location="New York",
    website="https://github.com/alenkimov/better_automation",
)

Загрузка изображений и смена аватара и баннера:

image = open(f"image.png", "rb").read()
media_id = await twitter_client.upload_image(image)
avatar_image_url = await twitter_client.update_profile_avatar(media_id)
banner_image_url = await twitter_client.update_profile_banner(media_id)

Привязка сервиса (приложения):

# Изучите запросы сервиса и найдите подобные данные для авторизации (привязки):
bind_data = {
    'response_type': 'code',
    'client_id': 'TjFVQm52ZDFGWEtNT0tKaktaSWU6MTpjaQ',
    'redirect_uri': 'https://waitlist.lens.xyz/tw/',
    'scope': 'users.read tweet.read offline.access',
    'state': 'state',  # Может быть как статичным, так и динамическим.
    'code_challenge': 'challenge',
    'code_challenge_method': 'plain'
}

bind_code = await twitter_client.oauth_2(**bind_data)
# Передайте код авторизации (привязки) сервису.
# Сервис также может потребовать state, если он динамический.

Отправка сообщения:

bro = await twitter_client.request_user("@username")
await twitter_client.send_message(bro.id, "I love you!")

Запрос входящих сообщений:

messages = await twitter_client.request_messages()
for message in messages:
    message_data = message["message_data"]
    recipient_id = message_data["recipient_id"]
    sender_id = message_data["sender_id"]
    text = message_data["text"]
    print(f"[id  {sender_id}] -> [id {recipient_id}]: {text}")

Другие методы:

# Выражение любви через твит
tweet_id = await twitter_client.tweet("I love YOU! !!!!1!1")
print(f"Любовь выражена! Tweet id: {tweet_id}")

print(f"Tweet is pined: {await twitter_client.pin_tweet(tweet_id)}")

# Лайк
print(f"Tweet {tweet_id} is liked: {await twitter_client.like(tweet_id)}")

# Репост (ретвит)
print(f"Tweet {tweet_id} is retweeted. Tweet id: {await twitter_client.repost(tweet_id)}")

# Коммент (реплай)
print(f"Tweet {tweet_id} is replied. Reply id: {await twitter_client.reply(tweet_id, 'tem razão')}")

# Подписываемся на Илона Маска
print(f"@{elonmusk.username} is followed: {await twitter_client.follow(elonmusk.id)}")

# Отписываемся от Илона Маска
print(f"@{elonmusk.username} is unfollowed: {await twitter_client.unfollow(elonmusk.id)}")

tweet_url = 'https://twitter.com/CreamIce_Cone/status/1691735090529976489'
# Цитата (Quote tweet)
quote_tweet_id = await twitter_client.quote(tweet_url, 'oh....')
print(f"Quoted! Tweet id: {quote_tweet_id}")

# Запрашиваем первых трех подписчиков
# (Параметр count по каким-то причинам работает некорректно)
followers = await twitter_client.request_followers(count=20)
print("Твои подписчики:")
for follower in followers:
    print(follower)

Metadata

Release files for qtweepy 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for qtweepy 1.0.0
File Size Uploaded Provenance Actions
qtweepy-1.0.0.tar.gz 32.2 kB Without provenance Details for qtweepy-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for qtweepy 1.0.0
File Interpreter ABI Platform Actions
qtweepy-1.0.0-py3-none-any.whl Python 3 none any Details for qtweepy-1.0.0-py3-none-any.whl

Total release size: 66.7 kB

Release files / qtweepy-1.0.0.tar.gz

Download URL qtweepy-1.0.0.tar.gz
Size 32.2 kB
Tags Source
SHA-256 checksum
How to use checksums
8988aa5957f59e5e7eba4e8f48878d36e0d9893edbd45603cf34a946d9cdc0c9
BLAKE2b-256 checksum
How to use checksums
2dfe25966656ed11f211536e59748aa20122195730683b02faa7f7514c2b6adf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.2 CPython/3.9.13 Windows/10

Release files / qtweepy-1.0.0-py3-none-any.whl

Download URL qtweepy-1.0.0-py3-none-any.whl
Size 34.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1503744f52fbab7709c46beeb2c41888055fedf91281958a26ccd545082ccfb4
BLAKE2b-256 checksum
How to use checksums
bb367efa9b87797dc0ae12c6eb8db2b4a2fd662ffb33146fac970de34ffc7afb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.2 CPython/3.9.13 Windows/10

Security for qtweepy 1.0.0

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page