Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions twitter-bot-python-tweepy/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM python:3.15-slim

COPY bots/config.py /bots/
COPY bots/likerepost.py /bots/
COPY requirements.txt /tmp
RUN python -m pip install -r /tmp/requirements.txt

WORKDIR /bots
CMD ["python", "likerepost.py"]
68 changes: 68 additions & 0 deletions twitter-bot-python-tweepy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# How to Make an X (Twitter) Bot in Python With Tweepy

This folder contains the code for the Real Python tutorial [How to Make an X (Twitter) Bot in Python With Tweepy](https://realpython.com/twitter-bot-python-tweepy/).

## Setup

You need Python 3.9 or later. The code was tested on Python 3.15 with Tweepy 4.17.0.

Create and activate a [virtual environment](https://realpython.com/python-virtual-environments-a-primer/), then install the pinned dependencies:

```sh
$ python -m venv venv
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

Follow the tutorial to create an app in the [X Developer Console](https://console.x.com). Choose the *Automated App or bot* type, and register `http://127.0.0.1:8000/callback` as the callback URL. Copy the app's **Client ID** and **Client Secret** into `authorize.py`, then run it once to authorize your account:

```sh
(venv) $ python authorize.py
```

The script opens the OAuth 2.0 authorization flow in your browser and writes the access and refresh tokens to `token.json`. Never commit `token.json`, because the tokens are your bot's password. If the refresh token stops working, run `authorize.py` again.

The bots read the app's credentials from two environment variables:

```sh
$ export CLIENT_ID="your-client-id"
$ export CLIENT_SECRET="your-client-secret"
```

The X API is pay-per-use. You need to add credits in the Developer Console before any request goes through.

## Usage

Run the bots from this folder so that they find `token.json`:

```sh
(venv) $ python bots/followfollowers.py
```

- `authorize.py`: one-time OAuth 2.0 authorization that creates `token.json`
- `bots/config.py`: creates a `tweepy.Client` that refreshes its access token before it expires and saves the new refresh token
- `bots/followfollowers.py`: follows back everyone who follows you
- `bots/likerepost.py`: likes and reposts recent posts that mention Python or Tweepy
- `bots/autoreply.py`: replies to mentions that contain the words "help" or "support"

Each bot polls the X API once a minute. Stop it with `Ctrl-C`.

### Docker

The `Dockerfile` packages the Like & Repost bot. Build and run it with the token file mounted into the container, so that refreshed tokens survive a restart:

```sh
$ docker build . -t like-repost-bot
$ docker run -it -e CLIENT_ID="your-client-id" \
-e CLIENT_SECRET="your-client-secret" \
-v "$(pwd)/token.json:/bots/token.json" \
like-repost-bot
```

## Author

- **Miguel Garcia**

## License

Distributed under the MIT license. See `LICENSE` in the root directory of this `materials` repo for more information.
38 changes: 38 additions & 0 deletions twitter-bot-python-tweepy/authorize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import json
import os

import tweepy

os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

CLIENT_ID = "WVhnd3dGV0c4MjNXbW4ySEo0bmR0OjE6Y2k"
CLIENT_SECRET = "Q0n9FbU3mLRtXAkPE2vV5Gh8Zc1yJdS7wNoHaIeKp4Tq6B0f_x"
REDIRECT_URI = "http://127.0.0.1:8000/callback"
SCOPES = [
"tweet.read",
"tweet.write",
"users.read",
"follows.read",
"follows.write",
"like.write",
"offline.access",
]

handler = tweepy.OAuth2UserHandler(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPES,
)

print("Open this URL in your browser and authorize the app:")
print(handler.get_authorization_url())
response_url = input("Paste the URL you were redirected to: ")

token = handler.fetch_token(response_url)
with open("token.json", mode="w", encoding="utf-8") as file:
json.dump(token, file, indent=2)

client = tweepy.Client(bearer_token=token["access_token"])
me = client.get_me(user_auth=False).data
print(f"Authentication OK for @{me.username}")
45 changes: 45 additions & 0 deletions twitter-bot-python-tweepy/bots/autoreply.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env python

import logging
import time

from config import create_client

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


def check_mentions(client, me, keywords, since_id):
logger.info("Retrieving mentions")
response = client.get_users_mentions(
me.id,
since_id=since_id,
tweet_fields=["author_id", "in_reply_to_user_id"],
)
new_since_id = since_id
for mention in response.data or []:
new_since_id = max(mention.id, new_since_id)
if mention.in_reply_to_user_id is not None:
continue
if any(keyword in mention.text.lower() for keyword in keywords):
logger.info(f"Answering post {mention.id}")
client.follow_user(mention.author_id, user_auth=False)
client.create_tweet(
text="Please reach us via DM",
in_reply_to_tweet_id=mention.id,
user_auth=False,
)
return new_since_id


def main():
client, me = create_client()
since_id = 1
while True:
since_id = check_mentions(client, me, ["help", "support"], since_id)
logger.info("Waiting...")
time.sleep(60)


if __name__ == "__main__":
main()
58 changes: 58 additions & 0 deletions twitter-bot-python-tweepy/bots/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import json
import logging
import os
import time

import tweepy

logger = logging.getLogger()

TOKEN_URL = "https://api.x.com/2/oauth2/token"
TOKEN_FILE = "token.json"
REDIRECT_URI = "http://127.0.0.1:8000/callback"


class OAuth2Client(tweepy.Client):
def __init__(self, handler, token_file, **kwargs):
self.handler = handler
self.token_file = token_file
with open(token_file, encoding="utf-8") as file:
self.token = json.load(file)
super().__init__(bearer_token=self.token["access_token"], **kwargs)

def refresh_if_needed(self):
if time.time() < self.token["expires_at"] - 60:
return
logger.info("Refreshing the access token")
self.token = self.handler.refresh_token(
TOKEN_URL,
refresh_token=self.token["refresh_token"],
auth=self.handler.auth,
client_id=self.handler.client_id,
)
self.bearer_token = self.token["access_token"]
with open(self.token_file, mode="w", encoding="utf-8") as file:
json.dump(self.token, file, indent=2)

def request(self, method, route, *args, **kwargs):
self.refresh_if_needed()
return super().request(method, route, *args, **kwargs)


def create_client():
with open(TOKEN_FILE, encoding="utf-8") as file:
scope = json.load(file)["scope"]
handler = tweepy.OAuth2UserHandler(
client_id=os.getenv("CLIENT_ID"),
client_secret=os.getenv("CLIENT_SECRET"),
redirect_uri=REDIRECT_URI,
scope=scope,
)
client = OAuth2Client(handler, TOKEN_FILE, wait_on_rate_limit=True)
try:
me = client.get_me(user_auth=False).data
except Exception:
logger.error("Error creating client", exc_info=True)
raise
logger.info(f"Client created for @{me.username}")
return client, me
42 changes: 42 additions & 0 deletions twitter-bot-python-tweepy/bots/followfollowers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env python

import logging
import time

import tweepy
from config import create_client

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


def get_following_ids(client, me):
paginator = tweepy.Paginator(
client.get_users_following, me.id, max_results=1000
)
return {user.id for user in paginator.flatten()}


def follow_followers(client, me, following_ids):
logger.info("Retrieving and following followers")
paginator = tweepy.Paginator(
client.get_users_followers, me.id, max_results=1000
)
for follower in paginator.flatten():
if follower.id not in following_ids:
logger.info(f"Following @{follower.username}")
client.follow_user(follower.id, user_auth=False)
following_ids.add(follower.id)


def main():
client, me = create_client()
following_ids = get_following_ids(client, me)
while True:
follow_followers(client, me, following_ids)
logger.info("Waiting...")
time.sleep(60)


if __name__ == "__main__":
main()
43 changes: 43 additions & 0 deletions twitter-bot-python-tweepy/bots/likerepost.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env python

import logging
import time

from config import create_client

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


def like_and_repost(client, me, query, since_id):
logger.info("Searching for new posts")
response = client.search_recent_tweets(
query, since_id=since_id, max_results=10
)
new_since_id = since_id
for post in response.data or []:
logger.info(f"Processing post id {post.id}")
new_since_id = max(post.id, new_since_id)
try:
client.like(post.id, user_auth=False)
client.retweet(post.id, user_auth=False)
except Exception:
logger.error("Error on like and repost", exc_info=True)
return new_since_id


def main(keywords):
client, me = create_client()
query = (
f"({' OR '.join(keywords)}) lang:en"
f" -is:reply -is:retweet -from:{me.username}"
)
since_id = 1
while True:
since_id = like_and_repost(client, me, query, since_id)
logger.info("Waiting...")
time.sleep(60)


if __name__ == "__main__":
main(["Python", "Tweepy"])
8 changes: 8 additions & 0 deletions twitter-bot-python-tweepy/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
certifi==2026.11.20
charset-normalizer==3.5.3
idna==3.21
oauthlib==3.3.1
requests==2.34.2
requests-oauthlib==2.0.0
tweepy==4.17.0
urllib3==2.8.0
Loading