-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy pathcommand2.py
2365 lines (2071 loc) · 71.1 KB
/
command2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
The command line interfact to the Twitter v2 API.
"""
from itertools import filterfalse
import os
import re
import json
import time
import twarc
import click
import logging
import pathlib
import datetime
import humanize
import requests
import configobj
import threading
from tqdm.auto import tqdm
from tqdm.utils import CallbackIOWrapper
from datetime import timezone
from click_plugins import with_plugins
from pkg_resources import iter_entry_points
from twarc.version import version
from twarc.handshake import handshake
from twarc.config import ConfigProvider
from twarc.expansions import (
ensure_flattened,
EXPANSIONS,
TWEET_FIELDS,
USER_FIELDS,
MEDIA_FIELDS,
POLL_FIELDS,
PLACE_FIELDS,
)
from click import command, option, Option, UsageError
from click_config_file import configuration_option
from twarc.decorators2 import (
cli_api_error,
TimestampProgressBar,
FileSizeProgressBar,
FileLineProgressBar,
_millis2snowflake,
_date2millis,
)
config_provider = ConfigProvider()
log = logging.getLogger("twarc")
@with_plugins(iter_entry_points("twarc.plugins"))
@click.group()
@click.option(
"--consumer-key",
type=str,
envvar="CONSUMER_KEY",
help='Twitter app consumer key (aka "App Key")',
)
@click.option(
"--consumer-secret",
type=str,
envvar="CONSUMER_SECRET",
help='Twitter app consumer secret (aka "App Secret")',
)
@click.option(
"--access-token",
type=str,
envvar="ACCESS_TOKEN",
help="Twitter app access token for user authentication.",
)
@click.option(
"--access-token-secret",
type=str,
envvar="ACCESS_TOKEN_SECRET",
help="Twitter app access token secret for user authentication.",
)
@click.option(
"--bearer-token",
type=str,
envvar="BEARER_TOKEN",
help="Twitter app access bearer token.",
)
@click.option(
"--app-auth/--user-auth",
default=True,
help="Use application authentication or user authentication. Some rate limits are "
"higher with user authentication, but not all endpoints are supported.",
show_default=True,
)
@click.option("--log", "-l", "log_file", default="twarc.log")
@click.option("--verbose", is_flag=True, default=False)
@click.option(
"--metadata/--no-metadata",
default=True,
show_default=True,
help="Include/don't include metadata about when and how data was collected.",
)
@configuration_option(
cmd_name="twarc", config_file_name="config", provider=config_provider
)
@click.pass_context
def twarc2(
ctx,
consumer_key,
consumer_secret,
access_token,
access_token_secret,
bearer_token,
log_file,
metadata,
app_auth,
verbose,
):
"""
Collect data from the Twitter V2 API.
"""
logging.basicConfig(
filename=log_file,
level=logging.DEBUG if verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
log.info("using config %s", config_provider.file_path)
if bearer_token or (consumer_key and consumer_secret):
if app_auth and (bearer_token or (consumer_key and consumer_secret)):
ctx.obj = twarc.Twarc2(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
bearer_token=bearer_token,
metadata=metadata,
)
# Check everything is present for user auth.
elif consumer_key and consumer_secret and access_token and access_token_secret:
ctx.obj = twarc.Twarc2(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret,
metadata=metadata,
)
else:
click.echo(
click.style(
"🙃 To use user authentication, you need all of the following:\n"
"- consumer_key\n",
"- consumer_secret\n",
"- access_token\n",
"- access_token_secret\n",
fg="red",
),
err=True,
)
click.echo("You can configure twarc2 using the `twarc2 configure` command.")
else:
click.echo()
click.echo("👋 Hi I don't see a configuration file yet, so let's make one.")
click.echo()
click.echo("Please follow these steps:")
click.echo()
click.echo("1. visit https://developer.twitter.com/en/portal/")
click.echo("2. create a project and an app")
click.echo("3. go to your Keys and Tokens and generate your keys")
click.echo()
ctx.invoke(configure)
@twarc2.command("configure")
@click.pass_context
def configure(ctx):
"""
Set up your Twitter app keys.
"""
config_file = config_provider.file_path
log.info("creating config file: %s", config_file)
config_dir = pathlib.Path(config_file).parent
if not config_dir.is_dir():
log.info("creating config directory: %s", config_dir)
config_dir.mkdir(parents=True)
keys = handshake()
if keys is None:
raise click.ClickException("Unable to authenticate")
config = configobj.ConfigObj(unrepr=True)
config.filename = config_file
# Only write non empty keys.
for key in [
"consumer_key",
"consumer_secret",
"access_token",
"access_token_secret",
"bearer_token",
]:
if keys.get(key, None):
config[key] = keys[key]
config.write()
click.echo(
click.style(f"\nYour keys have been written to {config_file}", fg="green")
)
click.echo()
click.echo("\n✨ ✨ ✨ Happy twarcing! ✨ ✨ ✨\n")
ctx.exit()
@twarc2.command("version")
def get_version():
"""
Return the version of twarc that is installed.
"""
click.echo(f"twarc v{version}")
def _search(
T,
query,
outfile,
since_id,
until_id,
start_time,
end_time,
limit,
max_results,
archive,
hide_progress,
expansions,
tweet_fields,
user_fields,
media_fields,
poll_fields,
place_fields,
):
"""
Common function to Search for tweets.
"""
count = 0
# Make sure times are always in UTC, click sometimes doesn't add timezone:
if start_time is not None and start_time.tzinfo is None:
start_time = start_time.replace(tzinfo=timezone.utc)
if end_time is not None and end_time.tzinfo is None:
end_time = end_time.replace(tzinfo=timezone.utc)
if archive:
search_method = T.search_all
# start time defaults to the beginning of Twitter to override the
# default of the last month. Only do this if start_time is not already
# specified and since_id and until_id aren't being used
if start_time is None and since_id is None and until_id is None:
start_time = datetime.datetime(2006, 3, 21, tzinfo=datetime.timezone.utc)
else:
search_method = T.search_recent
hide_progress = True if (outfile.name == "<stdout>") else hide_progress
with TimestampProgressBar(
since_id, until_id, start_time, end_time, disable=hide_progress
) as progress:
for result in search_method(
query=query,
since_id=since_id,
until_id=until_id,
start_time=start_time,
end_time=end_time,
max_results=max_results,
expansions=expansions,
tweet_fields=tweet_fields,
user_fields=user_fields,
media_fields=media_fields,
poll_fields=poll_fields,
place_fields=place_fields,
):
_write(result, outfile)
tweet_ids = [t["id"] for t in result.get("data", [])]
log.info("archived %s", ",".join(tweet_ids))
progress.update_with_result(result)
count += len(result["data"])
if limit != 0 and count >= limit:
# Display message when stopped early
progress.desc = f"Set --limit of {limit} reached"
break
else:
progress.early_stop = False
class MutuallyExclusiveOption(Option):
"""
Custom click class to make some options mutually exclusive
via https://gist.github.com/jacobtolar/fb80d5552a9a9dfc32b12a829fa21c0c
"""
def __init__(self, *args, **kwargs):
self.mutually_exclusive = set(kwargs.pop("mutually_exclusive", []))
help = kwargs.get("help", "")
if self.mutually_exclusive:
ex_str = ", ".join(
self.parse_name(name) for name in self.mutually_exclusive
)
kwargs["help"] = help + (
" NOTE: This argument is mutually exclusive with "
" arguments: [" + ex_str + "]."
)
super(MutuallyExclusiveOption, self).__init__(*args, **kwargs)
def parse_name(self, name):
return f'--{name.replace("_","-")}'
def handle_parse_result(self, ctx, opts, args):
if self.mutually_exclusive.intersection(opts) and self.name in opts:
raise UsageError(
f"Incorrect usage: {self.parse_name(self.name)} is mutually exclusive with "
f"arguments `{', '.join(self.parse_name(name) for name in self.mutually_exclusive)} use either one or the other."
)
return super(MutuallyExclusiveOption, self).handle_parse_result(ctx, opts, args)
def command_line_input_output_file_arguments(f):
"""
Decorator for specifying input and output file arguments in a command
"""
f = click.argument("outfile", type=click.File("w"), default="-")(f)
f = click.argument("infile", type=click.File("r"), default="-")(f)
return f
def command_line_progressbar_option(f):
"""
Decorator for specifying a progress bar option.
"""
f = click.option(
"--hide-progress",
is_flag=True,
default=False,
help="Hide the Progress bar. Default: show progress, unless using pipes.",
)(f)
return f
def command_line_search_options(f):
"""
Decorator for specifying time range search API parameters.
"""
f = click.option(
"--until-id", type=int, help="Match tweets sent prior to tweet id"
)(f)
f = click.option("--since-id", type=int, help="Match tweets sent after tweet id")(f)
f = click.option(
"--end-time",
type=click.DateTime(formats=("%Y-%m-%d", "%Y-%m-%dT%H:%M:%S")),
help='Match tweets sent before UTC time (ISO 8601/RFC 3339), \n e.g. --end-time "2021-01-01T12:31:04"',
)(f)
f = click.option(
"--start-time",
type=click.DateTime(formats=("%Y-%m-%d", "%Y-%m-%dT%H:%M:%S")),
help='Match tweets created after UTC time (ISO 8601/RFC 3339), \n e.g. --start-time "2021-01-01T12:31:04"',
)(f)
return f
def command_line_timelines_options(f):
"""
Decorator for common timelines command line options
"""
f = click.option(
"--exclude-replies",
is_flag=True,
default=False,
help="Exclude replies from timeline",
)(f)
f = click.option(
"--exclude-retweets",
is_flag=True,
default=False,
help="Exclude retweets from timeline",
)(f)
f = click.option(
"--use-search",
is_flag=True,
default=False,
help="Use the search/all API endpoint which is not limited to the last 3200 tweets, but requires Academic Product Track access.",
)(f)
return f
def _validate_max_results(context, parameter, value):
"""
Validate and set appropriate max_results parameter.
"""
archive_set = "archive" in context.params and context.params["archive"]
no_context_annotations_set = (
"no_context_annotations" in context.params
and context.params["no_context_annotations"]
)
minimal_fields_set = (
"minimal_fields" in context.params and context.params["minimal_fields"]
)
has_context_annotations = (
"tweet_fields" in context.params
and "context_annotations" in context.params["tweet_fields"].split(",")
)
if value:
if not archive_set and value > 100:
raise click.BadParameter(
"--max-results cannot be greater than 100 when using Standard Access. Specify --archive if you have Academic Access."
)
if value < 10 or value > 500:
raise click.BadParameter("--max-results must be between 10 and 500")
if value > 100 and has_context_annotations:
raise click.BadParameter(
"--max-results cannot be greater than 100 when using context annotations. Set --no-context-annotations to remove them, or don't specify them in --tweet-fields."
)
return value
else:
if archive_set and (
no_context_annotations_set
or minimal_fields_set
or not has_context_annotations
):
return 500
return 100
def command_line_search_archive_options(f):
"""
Decorator for specifying additional search API parameters.
"""
f = click.option(
"--limit", default=0, help="Maximum number of tweets to save", type=int
)(f)
f = click.option(
"--max-results",
default=None,
help="Maximum number of tweets per API response",
callback=_validate_max_results,
type=int,
)(f)
f = click.option(
"--archive",
is_flag=True,
default=False,
is_eager=True,
help="Use the full archive (requires Academic Research track)",
)(f)
return f
def _validate_expansions(context, parameter, value):
"""
Validate passed comma separated values for expansions.
"""
if value:
values = value.split(",")
valid = parameter.default.split(",")
for v in values:
if v not in valid:
raise click.BadOptionUsage(
parameter.name,
f'"{v}" is not a valid entry for --{parameter.name}. Must be a comma separated string, without spaces, like this:\n--{parameter.name} "{parameter.default}"',
)
return ",".join(values)
def command_line_expansions_options(f):
"""
Decorator for specifying custom fields and expansions
"""
f = click.option(
"--poll-fields",
default=",".join(POLL_FIELDS),
type=click.STRING,
help="Comma separated list of poll fields to retrieve. Default is all available.",
callback=_validate_expansions,
)(f)
f = click.option(
"--place-fields",
default=",".join(PLACE_FIELDS),
type=click.STRING,
help="Comma separated list of place fields to retrieve. Default is all available.",
callback=_validate_expansions,
)(f)
f = click.option(
"--media-fields",
default=",".join(MEDIA_FIELDS),
type=click.STRING,
help="Comma separated list of media fields to retrieve. Default is all available.",
callback=_validate_expansions,
)(f)
f = click.option(
"--user-fields",
default=",".join(USER_FIELDS),
type=click.STRING,
help="Comma separated list of user fields to retrieve. Default is all available.",
callback=_validate_expansions,
)(f)
f = click.option(
"--tweet-fields",
default=",".join(TWEET_FIELDS),
type=click.STRING,
is_eager=True,
help="Comma separated list of tweet fields to retrieve. Default is all available.",
callback=_validate_expansions,
)(f)
f = click.option(
"--expansions",
default=",".join(EXPANSIONS),
type=click.STRING,
help="Comma separated list of expansions to retrieve. Default is all available.",
callback=_validate_expansions,
)(f)
return f
def command_line_expansions_shortcuts(f):
"""
Decorator for specifying common fields and expansions presets
"""
f = click.option(
"--minimal-fields",
cls=MutuallyExclusiveOption,
mutually_exclusive=[
"no_context_annotations",
"expansions",
"tweet_fields",
"user_fields",
"media_fields",
"poll_fields",
"place_fields",
"counts_only",
],
is_flag=True,
default=False,
is_eager=True,
help="By default twarc gets all available data. This option requests the minimal retrievable amount of data - only IDs and object references are retrieved. Setting this makes --max-results 500 the default.",
)(f)
f = click.option(
"--no-context-annotations",
cls=MutuallyExclusiveOption,
mutually_exclusive=[
"minimal_fields",
"expansions",
"tweet_fields",
"user_fields",
"media_fields",
"poll_fields",
"place_fields",
"counts_only",
],
is_flag=True,
default=False,
is_eager=True,
help="By default twarc gets all available data. This leaves out context annotations (Twitter API limits --max-results to 100 if these are requested). Setting this makes --max-results 500 the default.",
)(f)
return f
def _process_expansions_shortcuts(kwargs):
# Override fields and expansions
if kwargs.pop("minimal_fields", None):
kwargs[
"expansions"
] = "author_id,in_reply_to_user_id,referenced_tweets.id,referenced_tweets.id.author_id,attachments.poll_ids,attachments.media_keys,geo.place_id"
kwargs[
"tweet_fields"
] = "id,conversation_id,author_id,in_reply_to_user_id,referenced_tweets,geo"
kwargs[
"user_fields"
] = "id,username,name,pinned_tweet_id" # pinned_tweet_id is the only extra one, id,username,name are always returned.
kwargs["media_fields"] = "media_key"
kwargs["poll_fields"] = "id"
kwargs["place_fields"] = "id"
if kwargs.pop("no_context_annotations", None):
kwargs[
"tweet_fields"
] = "attachments,author_id,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,public_metrics,text,possibly_sensitive,referenced_tweets,reply_settings,source,withheld"
return kwargs
def command_line_verbose_options(f):
"""
Decorator for specifying verbose and json output
"""
f = click.option(
"--verbose",
is_flag=True,
default=False,
help="Show all URLs and metadata.",
)(f)
f = click.option(
"--json-output",
is_flag=True,
default=False,
help="Return the raw json content from the API.",
)(f)
return f
@twarc2.command("search")
@command_line_search_options
@command_line_search_archive_options
@command_line_expansions_shortcuts
@command_line_expansions_options
@command_line_progressbar_option
@click.argument("query", type=str)
@click.argument("outfile", type=click.File("w"), default="-")
@click.pass_obj
@cli_api_error
def search(
T,
query,
outfile,
**kwargs,
):
"""
Search for tweets. For help on how to write a query see https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/build-a-query
"""
kwargs = _process_expansions_shortcuts(kwargs)
return _search(
T,
query,
outfile,
**kwargs,
)
@twarc2.command("counts")
@command_line_search_options
@click.option(
"--archive",
is_flag=True,
default=False,
help="Count using the full archive (requires Academic Research track)",
)
@click.option(
"--granularity",
default="hour",
type=click.Choice(["day", "hour", "minute"], case_sensitive=False),
help="Aggregation level for counts. Can be one of: day, hour, minute. Default is hour.",
)
@click.option(
"--limit",
default=0,
help="Maximum number of days of results to save (minimum is 30 days)",
)
@click.option(
"--text",
is_flag=True,
default=False,
help="Output the counts as human readable text",
)
@click.option("--csv", is_flag=True, default=False, help="Output counts as CSV")
@command_line_progressbar_option
@click.argument("query", type=str)
@click.argument("outfile", type=click.File("w"), default="-")
@click.pass_obj
@cli_api_error
def counts(
T,
query,
outfile,
since_id,
until_id,
start_time,
end_time,
archive,
granularity,
limit,
text,
csv,
hide_progress,
):
"""
Return counts of tweets matching a query.
"""
count = 0
# Make sure times are always in UTC, click sometimes doesn't add timezone:
if start_time is not None and start_time.tzinfo is None:
start_time = start_time.replace(tzinfo=timezone.utc)
if end_time is not None and end_time.tzinfo is None:
end_time = end_time.replace(tzinfo=timezone.utc)
if archive:
count_method = T.counts_all
# start time defaults to the beginning of Twitter to override the
# default of the last month. Only do this if start_time is not already
# specified and since_id/until_id aren't being used
if start_time is None and since_id is None and until_id is None:
start_time = datetime.datetime(2006, 3, 21, tzinfo=datetime.timezone.utc)
else:
count_method = T.counts_recent
if csv:
click.echo(f"start,end,{granularity}_count", file=outfile)
hide_progress = True if (outfile.name == "<stdout>") else hide_progress
total_tweets = 0
with TimestampProgressBar(
since_id, until_id, start_time, end_time, disable=hide_progress
) as progress:
for result in count_method(
query,
since_id,
until_id,
start_time,
end_time,
granularity,
):
# Count outputs:
if text:
for r in result["data"]:
total_tweets += r["tweet_count"]
click.echo(
"{start} - {end}: {tweet_count:,}".format(**r), file=outfile
)
elif csv:
for r in result["data"]:
click.echo(
f'{r["start"]},{r["end"]},{r["tweet_count"]}', file=outfile
)
else:
_write(result, outfile)
# Progress and limits:
if len(result["data"]) > 0:
progress.update_with_dates(
result["data"][0]["start"], result["data"][-1]["end"]
)
progress.tweet_count += result["meta"]["total_tweet_count"]
count += len(result["data"])
if limit != 0 and count >= limit:
break
if text:
click.echo(
click.style(
"\nTotal Tweets: {:,}\n".format(total_tweets), fg="green"
),
file=outfile,
)
else:
progress.early_stop = False
@twarc2.command("tweet")
@command_line_expansions_shortcuts
@command_line_expansions_options
@click.option("--pretty", is_flag=True, default=False, help="Pretty print the JSON")
@click.argument("tweet_id", type=str)
@click.argument("outfile", type=click.File("w"), default="-")
@click.pass_obj
@cli_api_error
def tweet(T, tweet_id, outfile, pretty, **kwargs):
"""
Look up a tweet using its tweet id or URL.
"""
kwargs = _process_expansions_shortcuts(kwargs)
if "https" in tweet_id:
tweet_id = tweet_id.split("/")[-1]
if not re.match("^\d+$", tweet_id):
click.echo(click.style("Please enter a tweet URL or ID", fg="red"), err=True)
result = next(T.tweet_lookup([tweet_id], **kwargs))
_write(result, outfile, pretty=pretty)
@twarc2.command("followers")
@click.option(
"--limit",
default=0,
help="Maximum number of followers to save. Increments of 1000 or --max-results if set.",
type=int,
)
@click.option(
"--max-results",
default=1000,
help="Maximum number of users per page. Default is 1000.",
type=int,
)
@command_line_progressbar_option
@click.argument("user", type=str)
@click.argument("outfile", type=click.File("w"), default="-")
@click.pass_obj
@cli_api_error
def followers(T, user, outfile, limit, max_results, hide_progress):
"""
Get the followers for a given user.
"""
count = 0
user_id = None
lookup_total = 0
if outfile is not None and (outfile.name == "<stdout>"):
hide_progress = True
if not hide_progress:
target_user = T._ensure_user(user)
user_id = target_user["id"]
lookup_total = target_user["public_metrics"]["followers_count"]
with tqdm(disable=hide_progress, total=lookup_total) as progress:
for result in T.followers(user, user_id=user_id, max_results=max_results):
_write(result, outfile)
count += len(result["data"])
progress.update(len(result["data"]))
if limit != 0 and count >= limit:
progress.desc = f"Set --limit of {limit} reached"
break
@twarc2.command("following")
@click.option(
"--limit",
default=0,
help="Maximum number of friends to save. Increments of 1000 or --max-results if set.",
type=int,
)
@click.option(
"--max-results",
default=1000,
help="Maximum number of users per page. Default is 1000.",
type=int,
)
@command_line_progressbar_option
@click.argument("user", type=str)
@click.argument("outfile", type=click.File("w"), default="-")
@click.pass_obj
@cli_api_error
def following(T, user, outfile, limit, max_results, hide_progress):
"""
Get the users that a given user is following.
"""
count = 0
user_id = None
lookup_total = 0
if outfile is not None and (outfile.name == "<stdout>"):
hide_progress = True
if not hide_progress:
target_user = T._ensure_user(user)
user_id = target_user["id"]
lookup_total = target_user["public_metrics"]["following_count"]
with tqdm(disable=hide_progress, total=lookup_total) as progress:
for result in T.following(user, user_id=user_id, max_results=max_results):
_write(result, outfile)
count += len(result["data"])
progress.update(len(result["data"]))
if limit != 0 and count >= limit:
progress.desc = f"Set --limit of {limit} reached"
break
@twarc2.command("sample")
@command_line_expansions_shortcuts
@command_line_expansions_options
@click.option("--limit", default=0, help="Maximum number of tweets to save")
@click.argument("outfile", type=click.File("a+"), default="-")
@click.pass_obj
@cli_api_error
def sample(T, outfile, limit, **kwargs):
"""
Fetch tweets from the sample stream.
"""
kwargs = _process_expansions_shortcuts(kwargs)
count = 0
event = threading.Event()
click.echo(
click.style(
f"Started a random sample stream, writing to {outfile.name}\nCTRL+C to stop...",
fg="green",
),
err=True,
)
for result in T.sample(event=event, **kwargs):
count += 1
if limit != 0 and count >= limit:
event.set()
_write(result, outfile)
if result:
log.info("archived %s", result["data"]["id"])
@twarc2.command("hydrate")
@command_line_expansions_shortcuts
@command_line_expansions_options
@command_line_input_output_file_arguments
@command_line_progressbar_option
@click.pass_obj
@cli_api_error
def hydrate(T, infile, outfile, hide_progress, **kwargs):
"""
Hydrate tweet ids.
"""
kwargs = _process_expansions_shortcuts(kwargs)
with FileLineProgressBar(infile, outfile, disable=hide_progress) as progress:
for result in T.tweet_lookup(infile, **kwargs):
_write(result, outfile)
tweet_ids = [t["id"] for t in result.get("data", [])]
log.info("archived %s", ",".join(tweet_ids))
progress.update_with_result(result, error_resource_type="tweet")
@twarc2.command("dehydrate")
@click.option(
"--id-type",
default="tweets",
type=click.Choice(["tweets", "users"], case_sensitive=False),
help="IDs to extract - either 'tweets' or 'users'.",
)
@command_line_progressbar_option
@command_line_input_output_file_arguments
@cli_api_error
def dehydrate(infile, outfile, id_type, hide_progress):
"""
Extract tweet or user IDs from a dataset.
"""
if infile.name == outfile.name:
click.echo(
click.style(
f"💔 Cannot extract files in-place, specify a different output file!",
fg="red",
),
err=True,
)
return
with FileSizeProgressBar(infile, outfile, disable=hide_progress) as progress:
count = 0
unique_ids = set()
for line in infile:
count += 1
progress.update(len(line))
# ignore empty lines
line = line.strip()
if not line:
continue
try:
for tweet in ensure_flattened(json.loads(line)):
if id_type == "tweets":
click.echo(tweet["id"], file=outfile)
unique_ids.add(tweet["id"])
elif id_type == "users":
click.echo(tweet["author_id"], file=outfile)
unique_ids.add(tweet["author_id"])
except KeyError as e:
click.echo(
f"No {id_type} ID found in JSON data on line {count}", err=True
)
break
except ValueError as e:
click.echo(f"Unexpected JSON data on line {count}", err=True)
break
except json.decoder.JSONDecodeError as e:
click.echo(f"Invalid JSON on line {count}", err=True)
break
click.echo(
f"ℹ️ Parsed {len(unique_ids)} {id_type} IDs from {count} lines in {infile.name} file.",
err=True,
)
@twarc2.command("users")
@command_line_expansions_shortcuts
@command_line_expansions_options
@click.option("--usernames", is_flag=True, default=False)
@command_line_progressbar_option
@command_line_input_output_file_arguments
@click.pass_obj