Skip to content

Instantly share code, notes, and snippets.

@Dhravya
Last active October 18, 2023 14:57
Show Gist options
  • Save Dhravya/0bdc77bbdece07204afad9219f39e7da to your computer and use it in GitHub Desktop.
Save Dhravya/0bdc77bbdece07204afad9219f39e7da to your computer and use it in GitHub Desktop.
A simple twitter bot using Twitter API v2
import pytwitter
from os import environ as env
from dotenv import load_dotenv
load_dotenv() # Loads the .env file we created earlier
api = pytwitter.Api(
consumer_key=env["CONSUMER_KEY"],
consumer_secret=env["CONSUMER_SECRET"],
access_token=env["OAUTH_TOKEN"],
access_secret=env["OAUTH_TOKEN_SECRET"],
)
# print(api.get_user(username="Twitter")) # To test the api connection
last_tweet_id = 0 # Just a variable to keep track of the last tweet we replied to.
if __name__ == "__main__":
while True:
mentions = api.get_mentions(
user_id=str(BOT_ID), # get bot id from tweeterid.com
return_json=True,
since_id=str(last_tweet_id),
tweet_fields=[
"conversation_id",
"entities",
"in_reply_to_user_id",
"referenced_tweets"
]
)
if not isinstance(mentions, dict):
continue
if not "data" in mentions.keys():
continue # There's no more tweets
for tweet in mentions["data"]:
text = tweet["text"]
reply_to = tweet["id"]
# If it's not a reply to another tweet
if not (tweet["conversation_id"] == tweet["id"]):
if str(tweet["in_reply_to_user_id"]) == str(BOT_ID):
continue
# Get the parent tweet
tweet_ = api.get_tweet(return_json=True,tweet_id=tweet["referenced_tweets"][0]["id"])
text = tweet_["text"]
# If tweet is a reply, it's in the format "@user @user @bot"
users = [
mention["username"] for mention in tweet["entities"]["mentions"]
]
new_txt = tweet["text"]
# Remove all mentions in the start
for user in users:
new_txt = new_txt.replace(f"@{user}", "")
new_txt = new_txt.strip()
if (new_txt == ""):
api.create_tweet(text=text.upper(), reply_in_reply_to_tweet_id = reply_to)
if "meta" in mentions.keys():
if "newest_id" in mentions["meta"].keys():
last_tweet_id = mentions["meta"]["newest_id"]
time.sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment