{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "> Notebook to download data using twitter's API" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import tweepy\n", "import os\n", "import csv\n", "import pandas as pd" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Saved the API Keys in the environment variables\n", "consumer_key = os.getenv(\"TWITTER_CONSUMER_KEY\")\n", "consumer_secret = os.getenv(\"TWITTER_CONSUMER_SECRET\")\n", "access_token = os.getenv(\"TWITTER_ACCESS_TOKEN\")\n", "access_token_secret = os.getenv(\"TWITTER_ACCESS_TOKEN_SECRET\")\n", "bearer_token = os.getenv(\"BEARER_TOKEN\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import requests\n", "import json\n", "from requests_oauthlib import OAuth1\n", "import urllib\n", "\n", "\n", "auth = OAuth1(consumer_key, consumer_secret, access_token, access_token_secret)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "https://api.twitter.com/2/tweets/search/recent?query=%23AppleVisionPro-is:retweets&tweet.fields=author_id,created_at&max_results=10000\n" ] } ], "source": [ "def create_url():\n", " query = urllib.parse.quote(\"#AppleVisionPro\") + \"-is:retweets\"\n", " tweet_fields = \"tweet.fields=author_id,created_at\"\n", " max_results = \"max_results=10000\"\n", " url = \"https://api.twitter.com/2/tweets/search/recent?query={}&{}&{}\".format(\n", " query, tweet_fields, max_results\n", " )\n", " print(url)\n", " return url\n", "\n", "\n", "def connect_to_endpoint(url):\n", " headers = {\n", " \"Authorization\": \"Bearer \" + bearer_token,\n", " \"Content-Type\": \"application/json\",\n", " }\n", " response = requests.get(url, headers=headers, auth=auth)\n", " # print(response)\n", " return response.json()\n", "\n", "\n", "def main():\n", " url = create_url()\n", " json_response = connect_to_endpoint(url)\n", " # Create a DataFrame from the JSON response\n", " df = pd.json_normalize(json_response)\n", " # Save the DataFrame as a Parquet file\n", " df.to_parquet(\"avp_tweets.parquet.gzip\", compression=\"gzip\")\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.13" } }, "nbformat": 4, "nbformat_minor": 2 }