Package: gazouilloire
A command line tool for long-term tweets collection. Gazouilloire combines two methods to collect tweets from the
Twitter API ("search" and "filter") in order to maximize the number of collected tweets, and automatically fills the
gaps in the collection in case of connexion errors or reboots. It handles various config options such as:collecting only duringspecific time periodslimiting the collection to somelocationsresolvingredirected urlsdownloading only certain types ofmedia contents(only photos and no videos, for example)unfolding TwitterconversationsPython >= 3.7 compatible.Your Twitter API keys must have been created beforeApril 29, 2022, in order to fully use the tool.
If your keys were created after that date, Gazouilloire will work with the "search" endpoint only, and not the "filter".
SeeTwitter's documentationabout this issue.SummaryInstallationQuick startDisk spaceExport the tweetsAdvanced parametersDaemon modeResetDevelopmentTroubleshootingPublicationsCredits & LicensesInstallationInstall gazouilloirepipinstallgazouilloireInstallElasticSearch, version 7.X (you can also useDockerfor this)Init gazouilloire collection in a specific directory...gazouinitpath/to/collection/directory...or in the current directorygazouinitaconfig.jsonfile is created. Open it to configure the collection parameters.Quick startSet yourTwitter API keyand generate the related Access Token"twitter":{"key":"<Consumer Key (API Key)>xxxxxxxxxxxxxxxxxxxxx","secret":"<Consumer Secret (API Secret)>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","oauth_token":"<Access Token>xxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","oauth_secret":"<Access Token Secret>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}Set your ElasticSearch connection (host & port) within thedatabasesection and choose a database name that will host your corpus' index:"database":{"host":"localhost","port":9200,"db_name":"medialab-tweets"}Note that ElasticSearch's databases names must be lowercased and without any space or accented character.Write down the list of desiredkeywordsand@usersand/or the list of desiredurl_piecesas json arrays:"keywords":["amour","\"mots successifs\"","@medialab_scpo"],"url_pieces":["medialab.sciencespo.fr/fr"],Read below theadvanced settingssection to setup more filters and options or to get precisions on how to properly write your queries within keywords.Start the collection by typing the following command in your terminal:gazourunor, if the config file is located in another directory than the current one:gazourunpath/to/collection/directoryRead below thedaemonsection to let gazouilloire run continuously on a server and how to set up automatic restarts.Disk spaceBefore starting the collection, you should make sure that you will have enough disk space.
It takes about 1GB per million tweets collected (withoutimages and other media contents).You should also consider starting gazouilloire inmulti-index modeif the collection is planed to
exceed 100 million tweets, or simply restart your collection in a new folder and a newdb_name(i.e. open another ElasticSearch index) if the current collection exceeds 150 million tweets.As a point of comparison, here is the number of tweets sent during the whole year 2021 containing certain keywords
(the values were obtained with the API V2tweets countendpoint):QueryNumber of tweets in 2021lemondefr lang:fr3 millionmacron lang:fr21 millionvaccine176 millionExport the tweets in CSV formatData is stored in your ElasticSearch, which you can direcly query. But you can also export it easily in CSV format:# Export all fields from all tweets, sorted in chronological order:gazouexportSort tweetsBy default, tweets are sorted in chronological order, using the "timestamp_utc" field.
However, you can speed-up the export by specifying that you do not need any sort order:gazouexport--sortnoYou can also sort tweets using one or several other sorting keys:gazouexport--sortcollection_time

gazouexport--sortuser_id,user_screen_namePlease note that:Sorting by "id" is not possible.Sorting by long textual fields (links, place_name, proper_links, text, url,
user_description, user_image, user_location, user_url) is not possible.Sorting by other id fields such as "user_id" or "retweeted_id" will sort these fields in
alphabetical order (100, 101, 1000, 99) and not numerical.Sorting by plural fields (e.g. mentions, hashtags, domains) may produce unexpected results.Sorting by several fields maystrongly increase export time.Write into a fileBy default, theexportcommand writes in stdout. You can also use the -o option to write into a file:gazouexport>my_tweets_file.csv# is equivalent togazouexport-omy_tweets_file.csvAlthough if you interrupt the export and need to resume it to complete in multiple sequences,
only the -o option will work with the --resume option.Query specific keywordsExport all tweets containing "medialab" in thetextfield:gazouexportmedialabThe search engine is not case sensitive and it escapes # or @:gazou export sciencespowill export
tweets containing "@sciencespo" or "#SciencesPo". However, itissensitive to accents:gazou export medialabwill not return tweets containing "médialab".Uselucene query syntaxwith the--luceneoption in order to write more complex queries:Use AND / OR:gazouexport--lucene'(medialab OR médialab) AND ("Sciences Po" OR sciencespo)'(note that queries containg AND or OR will be considered in lucene style even if you do not use the --lucene option)Query other fields than the text of the tweets:gazouexport--luceneuser_location:parisQuery tweets containing non-empty fields:gazouexport--luceneplace_country_code:*Query tweets containing empty fields:gazouexport--lucene'NOT retweeted_id:*'# (this is equivalent to:)gazouexport--exclude-retweetsNote that single quotes will not match exact phrases:gazouexport--lucene"NewYork OR \"New York\""#match tweets containing "New York" or "NewYork"gazouexport--lucene"NewYork OR 'New York'"#match tweets containing "New" or "York" or "NewYork"Other available options:# Get documentation for all options of gazou export (-h or --help)gazouexport-h# By default, the export will show a progressbar, which you can disable like this:gazouexport--quiet# Export a csv of all tweets between 2 dates or datetimes (--since is inclusive and --until exclusive):gazouexport--since2021-03-24--until2021-03-25# orgazouexport--since2021-03-24T12:00:00--until2021-03-24T13:00:00# List all available fields for each tweet:gazouexport--list-fields# Export only a selection of fields (-c / --columns or -s / --select the xsv way):gazouexport-cid,user_screen_name,local_time,links# or for example to export only the text of the tweets:gazouexport--selecttext# Exclude tweets collected via conversations or quotes (i.e. which do not match the keywords defined in config.json)gazouexport--exclude-threads# Exclude retweets from the exportgazouexport--exclude-retweets# Export all tweets matching a specific ElasticSearch term query, for instance by user name:gazouexport'{"user_screen_name": "medialab_ScPo"}'# Take a csv file with an "id" column and export only the tweets whose ids are included in this file:gazouexport--export-tweets-from-filelist_of_ids.csv# You can of course combine all of these options, for instance:gazouexportmedialab--since2021-03-24--until2021-03-25-ctext--exclude-threads--exclude-retweets-omedialab_tweets_210324_no_threads_no_rts.csvCount collected tweetsThe Gazouilloire query system is also available for thecountcommand. For example, you can count the number
of tweets that are retweets:gazoucount--luceneretweeted_id:*You can also use the--stepparameter to count the number of tweets per seconds/minutes/hours/days/months/years:gazoucountmedialab--stepmonths--since2018-01-01--until2022-01-01The result is written in CSV format.Export/Import data dumps directly with ElasticSearchIn order to run and reimport backups, you can also export or import data by dialoguing directly with ElasticSearch, with some of the many tools of the ecosystem built for this.We recommend usingelasticdump, which requires to installNodeJs:# Install the packagenpminstall-gelasticdumpThen you can use it directly or via our shipped-in scriptelasticdump.shto run simple exports/imports of your gazouilloire collection indices:gazouscriptselasticdump.sh# and to read its documentation:gazouscripts--infoelasticdump.shAdvanced parametersMany advanced settings can be used to better filter the tweets collected and complete the corpus. They can all be modified within theconfig.jsonfile.- keywordsKeywords syntax follow Twitter's search engine rules. You can forge your queries by typing them within thewebsite's search bar. You can input a single word, or a combination of ones separated by spaces (which will query for tweets matching all of those words). You can also write complex boolean queries such as(medialab OR (media lab)) (Sciences Po OR SciencesPo)but note only the Search API will be used for these ones, not the Streaming API, resulting in less exhaustive results.Some advanced filters can be used in combination with the keywords, such as-undesiredkeyword,filter:links,-filter:media,-filter:retweets, etc. SeeTwitter API's documentationfor more details. Queries including these will also only run on the Search API and not the Streaming API.When adding a Twitter user as a keyword, such as "@medialab_ScPo", Gazouilloire will query specifically "from:medialab_Scpo OR to:medialab_ScPo OR @medialab_ScPo" so that all tweets mentionning the user will also be collected.Using upper or lower case characters in keywords won't change anything.You can leave accents in queries, as Twitter will automatically return both tweets with and without accents through the search API, for instance searching "héros" will find both tweets with "heros" and "héros". The streaming API will only return exact results but it mostly complements the search results.Regarding hashtags, note that querying a word without the # character will return both tweets with the regular word and tweets with the hashtag. Adding a hashtag with the # characters inside keywords will only collect tweets with the hashtag.Note that there are three possibilities to filter further:- languageIn order to collect only tweets written in a specific language: just add"language": "fr"to the config (the language should be written inISO 639-1 code)- geolocationJust add"geolocation": "Paris, France"field to the config with the desired geographical boundaries or give in coordinates of the desired box (for instance[48.70908786918211, 2.1533203125, 49.00274483644453, 2.610626220703125])- time_limited_keywordsIn order to filter on specific keywords during planned time periods, for instance:"time_limited_keywords":{"#fosdem":[["2021-01-27 04:30","2021-01-28 23:30"]]}- url_piecesTo search for specific parts of websites, one can input pieces of urls as keywords in this field. For instance:"url_pieces":["medialab.sciencespo.fr","github.com/medialab"]- resolve_redirected_linksSet totrueorfalseto enable or disable automatic resolution of all links found in tweets (t.co links are always handled, but this allows resolving also for all other shorteners such as bit.ly).Theresolving_delay(set to 30 by default) defines for how many days urls returning errors will be retried before leaving them as such.- grab_conversationsSet totrueto activate automatic recursive retrieval within the corpus of all tweets to which collected tweets are answering (warning: one should account for the presence of these when processing data, it often results in collecting tweets which do not contain the queried keywords and/or which are way out of the collection time period).- catchup_past_weekTwitter's free API allows to collect tweets up to 7 days in the past, which gazouilloire does by default when starting a new corpus. Set this option tofalseto disable this and only collect tweets posted after the collection was started.- download_mediaConfigure this option to activate automatic downloading withinmedia_directoryof photos and/or videos posted by users within the collected tweets (this does not include images from social cards). For instance the following configuration will only collect pictures without videos or gifs:"download_media":{"photo":true,"video":false,"animated_gif":false,"media_directory":"path/to/media/directory"}All fields can also be set totrueto download everything.media_directoryis the folder where Gazouilloire stores the images & videos.
It should either be an absolute path ("/home/user/gazouilloire/my_collection/my_images"),
or a path relative to the directory where config.json is located ("my_images").- timezoneAdjust the timezone within which tweets timestamps should be computed. Allowed values are proposed on Gazouilloire's startup when setting up an invalid one.- verboseWhen set totrue, logs will be way more explicit regarding Gazouilloire's interactions with Twitter's API.Daemon modeFor production use and long term data collection, Gazouilloire can run as a daemon (which means that it executes in the background, and you can safely close the window within which you started it).Start the collection in daemon mode with:gazoustartStop the daemon with:gazoustopRestart the daemon with:gazourestartAccess the current collection status (running/not running, nomber of collected tweets, disk usage, etc.) withgazoustatusGazouilloire should normally restart on its own in case of temporary internet access outages but it might occasionnally fail for various reasons such as ElasticSearch having crashed for instance. In order to ensure a long term collection remains up and running without always checking it, we recommand to program automatic restarts of Gazouilloire at least once every week using cronjobs (missing tweets will be completed up to 7 days after a crash). In order to do so, arestart.shscript is proposed that handles restarting ElasticSearch whenever necessary. You can install it within your corpus directory by doing:gazouscriptsrestart.shUsecases and cronjobs examples are proposed as comments at the top of the script. You can also consult them by doing:gazouscripts--inforestart.shAn example scriptdaily_mail_export.shis also proposed to perform daily tweets exports and get them by e-mail. Feel free to reuse and tailor it to your own needs the same way:gazouscriptsdaily_mail_export.sh# and to read its documentation:gazouscripts--infodaily_mail_export.shMore similar practical scripts are available for diverse usecases:# You can list them all using --list or -l:gazouscripts--list# Read each script's documentation with --info or -i (for instance for "backup_corpus_ids.sh"):gazouscripts--infobackup_corpus_ids.sh# And install it in the current directory with:gazouscriptsbackup_corpus_ids.sh# Or within a specific different directory using --path or -p:gazouscriptsbackup_corpus_ids.sh-pPATH_TO_MY_GAZOUILLOIRE_COLLECTION_DIRECTORY# Or even install all scripts at once using --all or -a (--path applicable as well)gazouscripts--allResetGazouilloire stores its current search state in the collection directory. This means that if you restart Gazouilloire in the same directory, it will not search again for tweets that were already collected. If you want a fresh start, you can reset the search state, as well as everything that was saved on disk, using:gazouresetYou can also choose to delete only some elements, e.g. the tweets stored in ElasticSearch and the media files:gazoureset--onlytweets,mediaPossible values for the --only argument: tweets,links,logs,piles,search_state,mediaDevelopmentTo install Gazouilloire's latest development version or to help develop it, clone the repository and install your local version using the setup.py file:git clone https://github.com/medialab/gazouilloire
cd gazouilloire
python setup.py installGazouilloire's main code relies ingazouilloire/run.pyin which the whole multiprocess architecture is orchestrated. Below is a diagram of all processes and queues.Thesearchercollects tweets queryingTwitter's search API v1.1for all keywords sequentially as much as the API rates allowsThestreamercollects realtime tweets usingTwitter's streaming API v1.1and info on deleted tweets from users explicity followed as keywordsThedepilerprocesses and reformats tweets and deleted tweets usingtwitwibefore indexing them into ElasticSearch. It also extracts media urls and parent tweets to feed thedownloaderand thecatchupperThedownloaderrequests all media urls and stores them on the filesystem (if thedownload_mediaoption is enabled)Thecatchuppercollects recursively viaTwitter's lookup API v1.1parent tweets of all collected tweets that are part of a thread and feeds back thedepiler(if thegrab_conversationsoption is enabled)Theresolverruns multithreaded queries on all urls found as links within the collected tweets and tries to resolve them to get unshortened and harmonized urls (if theresolve_redirected_linksoption is enabled) thanks tominetAll three queues are backed up on filesystem inpile_***.jsonfiles to be reloaded at next restart whenever Gazouilloire is shut down.TroubleshootingElasticSearchRemember toset the heap size(at 1GB by default) when moving to production. 1GB is fine for indices under 15-20 million tweets, but be sure to set a higher value for heavier corpora.Set these values here/etc/elasticsearch/jvm.options(if you use ElasticSearch as a service) or hereyour_installation_folder/config/jvm.options(if you have a custom installation folder):-Xms2g
-Xmx2gHere the heap size is set at 2GB (set the values at-Xms5g -Xmx5gif you need 5GB, etc).If you encounter this ElasticSearch error message:max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]::arrow_right:  Increase themax_map_countvalue:sudosysctl-wvm.max_map_count=262144(source)If you get aClusterBlockException[SERVICE_UNAVAILABLE/1/state not recovered / initialized]when starting ElasticSearch::arrow_right:  Check the value ofgateway.recover_after_nodesin/etc/elasticsearch/elasticsearch.yml:sudo[YOURTEXTEDITOR]/etc/elasticsearch/elasticsearch.ymlEdit the value ofgateway.recover_after_nodesto match your number of nodes (usually1- easily checked here :http://host:port/_nodes).PublicationsGazouilloire presentationsVideo @ FOSDEM (english): MAZOYER Béatrice, "Gazouilloire: a command line tool for long-term tweets collection". Open Research Tools and Technologies devroom, FOSDEM 2021.Slides (french): OOGHE-TABANOU Benjamin, "Gazouilloire : Collecter des données dans la mare de tweets". Séminaire MORDEV, Laboratoire de Linguistique Formelle, Paris 2019.Publications using GazouilloireCASTALDO Maria, VENTURINI Tommaso, FRASCA Paolo, GARGIULO Floriana, "The Rhythms of the Night: increase in online night activity and emotional resilience during the Covid-19 lockdown"  (2020). arXiv preprint arXiv:2007.09353.WARD Jeremy K, GUILLE-ESCURET Paul, ALAPETITE Clément, "Les « antivaccins », figure de l’anti-Science" (2019), in Déviance et Société, 2019/2 (Vol. 43), p. 221-251. DOI: 10.3917/ds.432.0221RICCI, Donato, COLOMBO, Gabriele, MEUNIER, Axel, et al.Designing Digital Methods to monitor and inform Urban Policy. The case of Paris and its Urban Nature initiative. In: 3rd International Conference on Public Policy (ICPP3)-Panel T10P6 Session 1 Digital Methods for Public Policy. SGP, 2017. p. 1-37.DOUAY, Nicolas, REYS, Aurélien, ROBIN, Sabrina.L’usage de Twitter par les maires d’Île-de-France. NETCOM, 29-3/4 | 2015 : Visualisation des réseaux, de l’information et de l’espace, p. 275-296.ANTOLINOS-BASSO Diégo, PADDEU Flaminia, DOUAY Nicolas, BLANC Nathalie.Pourquoi le débat #EuropaCity n’a pas pris sur Twitter ?. RESET, 7 | 2018. DOI : 10.4000/reset.1070Publications talking about GazouilloireJULLIARD, Virginie.#Theoriedugenre: comment débat-on du genre sur Twitter ?. Questions de communication, 2016, no 2, p. 135-157.BOTTINI, Thomas et JULLIARD, Virginie.Entre informatique et sémiotique. Réseaux, 2017, no 4, p. 35-69.Credits & LicenseBenjamin Ooghe-Tabanou,Béatrice Mazoyer,Jules Farjas& al @Sciences Po médialabRead more about Gazouilloire's migration from Python2 & Mongo to Python3 & ElasticSearch inJules' report.Discover more of our projects atmédialab tools.This work has been supported byDIME-Web, part ofDIME-SHSresearch equipment financed by the EQUIPEX program (ANR-10-EQPX-19-01).Gazouilloire is a free open source software released underGPL 3.0 license.