Created
March 5, 2025 16:06
-
-
Save mthomason/34b56259d6312481d0724877181ac6d3 to your computer and use it in GitHub Desktop.
Throwaway Python 3 script using to list Twitter-X followers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import getpass | |
from typing import List, Dict | |
from twscrape import API, gather # type: ignore | |
OUTPUT_FILE = "following_export.txt" # Hardcoded output file name | |
async def get_following_accounts(target_username: str, api: API) -> List[Dict[str, str]]: | |
""" | |
Fetch the accounts that the given target user follows. | |
""" | |
target_user = await api.user_by_login(target_username) | |
if not target_user: | |
raise ValueError(f"User '{target_username}' not found") | |
users = await gather(api.following(target_user.id, limit=1000)) | |
return [{ | |
"name": user.displayname, | |
"handle": user.username.lower() # Lowercase for case-insensitive sorting | |
} for user in users] | |
async def main_async() -> None: | |
""" | |
Asynchronous main function with enhanced account management and file output. | |
""" | |
api = API() # Uses default 'accounts.db' | |
# Account handling | |
account_username = input("Twitter account username: ") | |
existing_account = await api.pool.get_account(account_username) | |
if existing_account: | |
print(f"Account {account_username} found in database") | |
if not existing_account.active: | |
print("Account not active, attempting login...") | |
await api.pool.login_all([account_username]) | |
else: | |
print("New account - please enter credentials:") | |
account_password = getpass.getpass("Twitter account password: ") | |
account_email = input("Twitter account email: ") | |
account_email_password = getpass.getpass("Email password (for verification): ") | |
await api.pool.add_account( | |
account_username, | |
account_password, | |
account_email, | |
account_email_password | |
) | |
await api.pool.login_all([account_username]) | |
# Target user handling | |
target_username = input("Enter target username to fetch following list: ").strip() | |
accounts = await get_following_accounts(target_username, api) | |
# Sort accounts by handle (case-insensitive) | |
accounts.sort(key=lambda x: x["handle"]) | |
# File output with zero-padded numbering | |
with open(OUTPUT_FILE, "w", encoding="utf-8") as f: | |
for idx, account in enumerate(accounts): | |
line = f"{idx:04d} - Handle: @{account['handle']}, Name: {account['name']}\n" | |
f.write(line) | |
print(f"\nSuccessfully exported {len(accounts)} accounts to {OUTPUT_FILE}") | |
def main() -> None: | |
asyncio.run(main_async()) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment