-
Notifications
You must be signed in to change notification settings - Fork 23
/
bwresources.py
1845 lines (1529 loc) · 70.1 KB
/
bwresources.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
"""
bwresources contains the BWMentions, BWQueries, BWGroups, BWRules, BWTags, BWCategories, BWSiteLists, BWAuthorLists, BWLocationLists, and BWSignals classes.
"""
import json
from . import filters
from . import bwdata
import logging
logger = logging.getLogger("bcr_api")
class AmbiguityError(ValueError):
"""Simple class to make errors when handling resource IDs more clear"""
pass
class BWResource:
"""
This class is a superclass for brandwatch resources (queries, groups, mentions, tags, sitelists, authorlists, locationlists and signals).
Attributes:
project: Brandwatch project. This is a BWProject object.
names: Query names, organized in a dictionary of the form {query1id: query1name, query2id: query2name, ...}
"""
def __init__(self, bwproject):
"""
Creates a BWResource object.
Args:
bwproject: Brandwatch project. This is a BWProject object.
"""
self.project = bwproject
self.names = {}
self.reload()
def reload(self):
"""
Refreshes names and ids.
This function is used internally after editing any resource (e.g. uploading) so that our local copy of the id information matches the system's.
The only potential danger is that someone else is editing a resource at the same time you are - in which case your local copy could differ from the system's.
If you fear this has happened, you can call reload() directly.
Raises:
KeyError: If there was an error with the request for resource information.
"""
response = self.project.get(endpoint=self.general_endpoint)
if "results" not in response:
raise KeyError("Could not retrieve" + self.resource_type, response)
self.names = {
resource["id"]: resource["name"] for resource in response["results"]
}
def get_resource_id(self, resource=None):
"""Takes in a resource ID or name and returns the resource ID. Raises an error if an ambiguous name is provided (e.g. if user calls this function with 'Query1' and there is actually a query and a logo query with that name)
"""
if not resource:
return (
""
) # return empty string rather than none to avoid stringified "None" becoming part of the url of an API call
if isinstance(resource, int):
if resource not in self.names.keys():
raise KeyError(
"Could not find the resource ID {} in the project".format(resource)
)
resource_id = resource
elif isinstance(resource, str):
entries = [
resource_id
for resource_id, name in self.names.items()
if name == resource
]
if len(entries) > 1:
raise AmbiguityError(
"The resource name {} is ambiguous: {}".format(resource, entries)
)
if entries:
return entries[0]
else:
try:
resource_id = int(resource)
except ValueError:
raise KeyError(
"Could not find the resource name {} in the project".format(
resource
)
)
if resource_id not in self.names.keys():
raise KeyError(
"Could not find the resource ID {} in the project".format(resource)
)
if resource_id:
return resource_id
def check_resource_exists(self, resource):
try:
self.get_resource_id(resource)
return True
# Check the type of error
# Key errors relate to the resource not being present, if KeyError return False, because the resource doesn't exist
# If there's a ValueError, we want that still to be raised, because it means the resource name is ambiguous, and we want to raise that
except AmbiguityError:
raise
except KeyError:
return False
def get(self, name=None):
"""
If you specify an ID, this function will retrieve all information for that resource as it is stored in Brandwatch.
If you specify a name, this will be mapped to the appropriate ID. An error will be raised if there are two IDs with the name specified.
If you do not pass anything in with the `name` argument, this function will retrieve all information for all resources of that type as they are stored in Brandwatch.
Args:
name: ID or name of the resource that you'd like to retrieve - Optional. If you do not specify an ID, all resources of that type will be retrieved.
Raises:
KeyError: If you specify a resource ID and the resource does not exist.
Returns:
All information for the specified resource, or a list of information on every resource of that type in the account.
"""
id_num = self.get_resource_id(resource=name)
return self.project.get(endpoint=self.specific_endpoint + "/" + str(id_num))
def upload(self, create_only=False, modify_only=False, **kwargs):
"""
Uploads a resource.
Args:
create_only: If True and the resource already exists, no action will be triggered - Optional. Defaults to False.
modify_only: If True and the resource does not exist, no action will be triggered - Optional. Defaults to False.
kwargs: Keyword arguments for resource information. Error handling is handeled in the child classes.
Returns:
The uploaded resource information in a dictionary of the form {resource1name: resource1id}
"""
return self.upload_all([kwargs], create_only, modify_only)
def upload_all(self, data_list, create_only=False, modify_only=False):
"""
Uploads a list of resources.
Args:
data_list: List of data for each resource. Error handling is handeled in the child classes.
create_only: If True and the query already exists, no action will be triggered - Optional. Defaults to False.
modify_only: If True and the query does not exist, no action will be triggered - Optional. Defaults to False.
Returns:
The uploaded resource information in a dictionary of the form {resource1name: resource1id, resource2name: resource2id, ...}
"""
resources = {}
for data in data_list:
# eventually make _fill_data() a BWResource func
filled_data = self._fill_data(data)
name = data["name"]
if self.check_resource_exists(name) and not create_only:
resource_id = self.get_resource_id(name)
response = self.project.put(
endpoint=self.specific_endpoint + "/" + str(resource_id),
data=filled_data,
)
elif (
not self.check_resource_exists(name) and not modify_only
): # if resource does not exist
response = self.project.post(
endpoint=self.specific_endpoint, data=filled_data
)
else:
continue
logger.info("Uploading {} {}".format(self.resource_type, response["name"]))
resources[response["name"]] = response["id"]
self.reload()
return resources
def rename(self, name, new_name):
"""
Renames an existing resource.
Args:
name: Name of existing resource.
new_name: New name for the resource.
Raises:
KeyError: If the resource does not exist.
"""
if not self.check_resource_exists(name): # if the resource does not exist
raise KeyError(
"Cannot rename a " + self.resource_type + " which does not exist", name
)
else:
info = self.get(
name=name
) # will raise error if ambiguous name provided, so we should be okay to provide a name from this point forward (it won't be ambiguous if we get past this stage)
info.pop("name")
self.upload(name=name, new_name=new_name, **info)
def delete(self, name):
"""
Deletes a resource.
Args:
name: Name of the resource that you'd like to delete.
"""
self.delete_all([name])
def delete_all(self, names):
"""
Deletes a list of resources.
Args:
names: A list of the names of the queries that you'd like to delete.
"""
resource_ids = [self.get_resource_id(x) for x in names]
for resource_id in resource_ids:
if resource_id in self.names.keys():
self.project.delete(
endpoint=self.specific_endpoint + "/" + str(resource_id)
)
logger.info(
"{} {} deleted".format(self.resource_type, self.names[resource_id])
)
self.reload()
def _fill_data():
raise NotImplementedError
class BWQueries(BWResource, bwdata.BWData):
"""
This class provides an interface for query level operations within a prescribed project (e.g. uploading, downloading, renaming, downloading a list of mentions).
Attributes:
tags: All tags in the project - handeled at the class level to prevent repetitive API calls. This is a BWTags object.
categories: All categories in the project - handeled at the class level to prevent repetitive API calls. This is a BWCategories object.
"""
general_endpoint = "queries"
specific_endpoint = "queries"
resource_type = "queries"
resource_id_name = "queryId"
def __init__(self, bwproject):
"""
Creates a BWQueries object.
Args:
bwproject: Brandwatch project. This is a BWProject object.
"""
super(BWQueries, self).__init__(bwproject)
self.tags = BWTags(self.project)
self.categories = BWCategories(self.project)
def upload(self, create_only=False, modify_only=False, **kwargs):
"""
Uploads a query.
Args:
name: Query name
booleanQuery: Query boolean (e.g. "cat AND dog")
startDate: Date for query data to be collected from (equivalent to backfill_date in Analytics SDK)
contentSources: Optional, defaults to same sources in UI
description: Optional, defaults to empty string (e.g. "a query to find mentions about cats and dogs")
languages: Optional, defaults to en
languageAgnostic: Optional, set to True instead of passing in a language for the query to match against all mentions regardless of language (generally not recommended)
monitor_sample_percentage: Optional, defaults to 100 (percent)
query_type: Optional, defaults to 'monitor'
Raises:
KeyError: If you do not pass name and booleanQuery for each query in the data_list.
Returns:
The uploaded query information in a dictionary of the form {query1name: query1id}
"""
return self.upload_all([kwargs], create_only, modify_only)
def upload_all(self, data_list, create_only=False, modify_only=False):
"""
Uploads multiple queries.
Args:
name: Query name
booleanQuery: Query boolean (e.g. "cat AND dog")
startDate: Date for query data to be collected from (equivalent to backfill_date in Analytics SDK)
contentSources: Optional, defaults to same sources in UI
description: Optional, defaults to empty string (e.g. "a query to find mentions about cats and dogs")
languages: Optional, defaults to en
languageAgnostic: Optional, set to True instead of passing in a language for the query to match against all mentions regardless of language (generally not recommended)
monitor_sample_percentage: Optional, defaults to 100 (percent)
query_type: Optional, defaults to 'monitor'
Raises:
KeyError: If you do not pass name and booleanQuery for each query in the data_list.
Returns:
The uploaded query information in a dictionary of the form {query1name: query1id, query2name: query2id, ...}
"""
queries = super(BWQueries, self).upload_all(
data_list, create_only=False, modify_only=False
)
return queries
def rename(self, name, new_name):
"""
Renames an existing resource.
Args:
name: Name of existing resource.
new_name: New name for the resource.
Raises:
KeyError: If the resource does not exist.
"""
if not self.check_resource_exists(name):
raise KeyError(
"Cannot rename a " + self.resource_type + " which does not exist", name
)
else:
info = self.get(name=name)
info.pop("name")
if info["type"] == "search string":
self.upload(name=name, new_name=new_name, **info)
else:
raise KeyError(
"We cannot support automated renaming of channels at this time."
)
def get_mention(self, **kwargs):
"""
Retrieves a single mention by url or resource id.
This is ONLY a valid function for queries (not groups), which is why it isn't split out into bwdata.
Note: Clients do not have access to full Twitter mentions through the API because of our data agreement with Twitter.
Args:
kwargs: You must pass in name (query name), and either url or resourceId.
Raises:
KeyError: If the mentions call fails.
Returns:
A single mention.
"""
params = self._fill_mention_params(kwargs)
resource_id = self.get_resource_id(kwargs["name"])
mention = self.project.get(
endpoint="query/" + str(resource_id) + "/mentionfind", params=params
)
if "errors" in mention:
raise KeyError("Mentions GET request failed", mention)
return mention["mention"]
def _name_to_id(self, attribute, setting):
if isinstance(setting, int):
return setting
elif isinstance(setting, list):
try:
return [int(i) for i in setting]
except ValueError:
pass
if attribute in ["category", "xcategory"]:
# setting is a dictionary with one key-value pair, so this loop iterates only once
# but is necessary to extract the values in the dictionary
ids = []
for category in setting:
parent = category
children = setting[category]
for child in children:
ids.append(self.categories.ids[parent]["children"][child])
return ids
elif attribute in [
"parentCategory",
"xparentCategory",
"parentCategories",
"categories",
]:
# plural included for get_charts syntax
# note: parentCategories and categories params will be ignored for everything but chart calls
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(self.categories.ids[s]["id"])
return ids
elif attribute in ["tag", "xtag", "tags"]:
# plural included for get_charts syntax
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(self.tags.get_resource_id(s))
return ids
elif attribute in ["authorGroup", "xauthorGroup"]:
authorlists = BWAuthorLists(self.project)
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(authorlists.get(s)["id"])
return ids
elif attribute in [
"locationGroup",
"xlocationGroup",
"authorLocationGroup",
"xauthorLocationGroup",
]:
locationlists = BWLocationLists(self.project)
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(locationlists.get(s)["id"])
return ids
elif attribute in ["siteGroup", "xsiteGroup"]:
sitelists = BWSiteLists(self.project)
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(sitelists.get(s)["id"])
return ids
else:
return setting
def _fill_data(self, data):
default_content_sources = [
"qq",
"news",
"youtube",
"forum",
"twitter",
"review",
"facebook",
"reddit",
"tumblr",
"instagram",
"blog",
]
filled = dict()
if ("name" not in data) or ("booleanQuery" not in data):
raise KeyError("Need name and booleanQuery to post query", data)
if ("language" in data) and ("languageAgnostic" in data):
raise ValueError(
"Please choose either to specify languages or a language agnostic query"
)
filled["booleanQuery"] = data["booleanQuery"]
# if resource exists, create value for filled['id']
if self.check_resource_exists(data["name"]):
filled["id"] = self.get_resource_id(data["name"])
if "new_name" in data:
filled["name"] = data["new_name"]
else: # if resource doesn't exist, add name to filled dictionary
filled["name"] = data["name"]
# params with default values
filled["type"] = data.get("query_type", "monitor")
filled["languageAgnostic"] = data.get("languageAgnostic", False)
filled["contentSources"] = data.get("contentSources", default_content_sources)
filled["monitorSamplePercentage"] = data.get("monitorSamplePercentage", 100)
filled["description"] = data.get("description", "")
# currently languages field defaults to 'en', similar to UI, but it could alternatively default to False, to create a language agnostic query
filled["languages"] = data.get("languages", "en")
# If user passes in string to languages parameter, turn into a list containing only that string
if isinstance(filled["languages"], str):
filled["languages"] = [filled["languages"]]
# optional params, with no defaults
if "startDate" in data:
filled["startDate"] = data["startDate"]
# validating the query search - comment this out to skip validation
self.project.validate_query_search(
query=filled["booleanQuery"], language=filled["languages"]
)
return json.dumps(filled)
def _fill_mention_params(self, data):
if "name" not in data:
raise KeyError("Must specify query or group name", data)
elif not self.check_resource_exists(data["name"]): # if resource does not exist
raise KeyError("Could not find " + self.resource_type + " " + data["name"])
if ("url" not in data) and ("resourceId" not in data):
raise KeyError("Must provide either a url or a resourceId", data)
filled = {}
if "url" in data:
filled["url"] = data["url"]
else:
filled["resourceId"] = data["resourceId"]
return filled
class BWGroups(BWResource, bwdata.BWData):
"""
This class provides an interface for group level operations within a prescribed project.
Attributes:
queries: All queries in the project - handeled at the class level to prevent repetitive API calls. This is a BWQueries object.
tags: All tags in the project - handeled at the class level to prevent repetitive API calls. This is a BWTags object.
categories: All categories in the project - handeled at the class level to prevent repetitive API calls. This is a BWCategories object.
"""
general_endpoint = "querygroups"
specific_endpoint = "querygroups"
resource_type = "groups"
resource_id_name = "queryGroupId"
def __init__(self, bwproject):
"""
Creates a BWGroups object.
Args:
bwproject: Brandwatch project. This is a BWProject object.
"""
super(BWGroups, self).__init__(bwproject)
self.queries = BWQueries(self.project)
self.tags = self.queries.tags
self.categories = self.queries.categories
def rename(self, name, new_name):
"""
Renames an existing resource.
Args:
name: Name of existing resource.
new_name: New name for the resource.
Raises:
KeyError: If the resource does not exist.
"""
if not self.check_resource_exists(name):
raise KeyError(
"Cannot rename a " + self.resource_type + " which does not exist", name
)
else:
info = self.get(name=name)
queries = [x["name"] for x in info["queries"]]
self.upload(name=name, new_name=new_name, queries=queries)
def upload_queries_as_group(
self,
group_name,
query_data_list,
create_only=False,
modify_only=False,
**kwargs
):
"""
Uploads a list of queries and saves them as a group.
Args:
group_name: Name of the group.
query_data_list: List of dictionaries, where each dictionary includes the information for one query in the following format {name: queryname, includedTerms: searchstring}
create_only: If True and the group already exists, no action will be triggered - Optional. Defaults to False.
modify_only: If True and the group does not exist, no action will be triggered - Optional. Defaults to False.
kwargs: You can pass in shared, sharedProjectIds and users - Optional.
Returns:
The uploaded group information in a dictionary of the form {groupname: groupid}
"""
kwargs["queries"] = self.queries.upload_all(
query_data_list, create_only, modify_only
)
kwargs["name"] = group_name
return self.upload(create_only, modify_only, **kwargs)
def deep_delete(self, name):
"""
Deletes a group and all of the queries in the group.
Args:
name: Name of the group that you'd like to delete.
"""
# No need to delete the group itself, since a group will be deleted automatically when empty
BWQueries(self.project).delete_all(self.get_group_queries(name))
logger.info("Group {} deleted".format(name))
def get_group_queries(self, name):
"""
Retrieves information about the queries in the group.
Args:
name: Name of the group that you'd like to retrieve.
Returns:
A dictionary of the form {query1name: query1id, query2name:query2id, ...}.
"""
return {q["name"]: q["id"] for q in self.get(name)["queries"]}
def _name_to_id(self, attribute, setting):
if isinstance(setting, int):
return setting
elif isinstance(setting, list):
try:
return [int(i) for i in setting]
except ValueError:
pass
if attribute in ["category", "xcategory"]:
# setting is a dictionary with one key-value pair, so this loop iterates only once
# but is necessary to extract the values in the dictionary
ids = []
for category in setting:
parent = category
children = setting[category]
for child in children:
ids.append(self.categories.ids[parent]["children"][child])
return ids
elif attribute in [
"parentCategory",
"xparentCategory",
"parentCategories",
"categories",
]:
# plural included for get_charts syntax
# note: parentCategories and categories params will be ignored for everything but chart calls
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(self.categories.ids[s]["id"])
return ids
elif attribute in ["tag", "xtag", "tags"]:
# plural included for get_charts syntax
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(self.tags.get_resource_id(s))
return ids
elif attribute in ["authorGroup", "xauthorGroup"]:
authorlists = BWAuthorLists(self.project)
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(authorlists.get(s)["id"])
return ids
elif attribute in [
"locationGroup",
"xlocationGroup",
"authorLocationGroup",
"xauthorLocationGroup",
]:
locationlists = BWLocationLists(self.project)
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(locationlists.get(s)["id"])
return ids
elif attribute in ["siteGroup", "xsiteGroup"]:
sitelists = BWSiteLists(self.project)
if not isinstance(setting, list):
setting = [setting]
ids = []
for s in setting:
ids.append(sitelists.get(s)["id"])
return ids
else:
return setting
def _fill_data(self, data):
filled = {}
if ("name" not in data) or ("queries" not in data):
raise KeyError("Need name and queries to upload group", data)
if self.check_resource_exists(
data["name"]
): # if resource exists, create value for filled['id']
filled["id"] = self.get_resource_id(data["name"])
if "new_name" in data:
filled["name"] = data["new_name"]
else:
filled["name"] = data["name"]
queries = data["queries"]
query_ids = [self.queries.get_resource_id(resource=x) for x in queries]
# now we have a reliable list of ids, we can turn this into a list of dictionaries in the form [{'name': 'MyQuery', 'id': 1111}]
filled["queries"] = [
{"name": self.queries.names[resource_id], "id": resource_id}
for resource_id in query_ids
]
filled["shared"] = data["shared"] if "shared" in data else "public"
filled["sharedProjectIds"] = (
data["sharedProjectIds"]
if "sharedProjectIds" in data
else [self.project.project_id]
)
filled["users"] = (
data["users"]
if "users" in data
else [{"id": self.project.get_self()["id"]}]
)
return json.dumps(filled)
class BWMentions:
"""
This class handles patching lists of mentions.
For retrieving mentions, see the BWQueries or BWGroups class instead (as you must specify a query or group in order to retrieve mentions, we thought it most sensible to tie that task to the BWQueries and BWGroups classes).
Attributes:
tags: All tags in the project - handeled at the class level to prevent repetitive API calls. This is a BWTags object.
categories: All categories in the project - handeled at the class level to prevent repetitive API calls. This is a BWCategories object.
"""
def __init__(self, bwproject):
"""
Creates a BWMentions object.
Args:
bwproject: Brandwatch project. This is a BWProject object.
"""
self.project = bwproject
self.tags = BWTags(self.project)
self.categories = BWCategories(self.project)
def patch_mentions(self, mentions, action, setting):
"""
Edits a list of mentions by adding or removing categories, tags, priority, status, or assignment, or changing sentiment, checked or starred status, or location.
This function will also handle uploading categories and tags, if you want to edit mentions by adding categories or tags that do not yet exist in the system.
Args:
mentions: List of mentions to be edited.
action: Action to be taken when editing the mention. See the list titled mutable in filters.py for the possible actions you can take to edit a mention.
setting: If the action is addTag or removeTag, the setting is a list of string(s) where each string is a tag name. If the action is addCategories or removeCategories, the setting is a dictionary of in the format: {parent:[child1, child2, etc]} for any number of subcatagories (parent subcatagory names are strings). See the dictionary titled mutable_options in filters.py for the accepted values for other actions.
Raises:
KeyError: If you pass in an invalid action or setting.
KeyError: If there is an error when attempting to edit the mentions.
"""
# add cats and tags if they don't exist
if action in ["addCategories", "removeCategories"]:
# the following loop is only one iteration
for category in setting:
parent = category
children = setting[category]
self.categories.upload(name=parent, children=children)
setting = []
for child in children:
setting.append(self.categories.ids[parent]["children"][child])
elif action in ["addTag", "removeTag"]:
for s in setting:
self.tags.upload(name=s, create_only=True)
filled_data = []
for mention in mentions:
if action in filters.mutable and self._valid_patch_input(action, setting):
filled_data.append(
self._fill_mention_data(
mention=mention, action=action, setting=setting
)
)
else:
raise KeyError("invalid action or setting", action, setting)
response = self.project.patch(
endpoint="data/mentions", data=json.dumps(filled_data)
)
if "errors" in response:
raise KeyError("patch failed", response)
logger.info("{} mentions updated".format(len(response)))
def _valid_patch_input(self, action, setting):
""" internal use """
if not isinstance(setting, filters.mutable[action]):
return False
if (
action in filters.mutable_options
and setting not in filters.mutable_options[action]
):
return False
else:
return True
def _fill_mention_data(self, **data):
""" internal use """
# pass in mention, filter_type, setting
filled = {}
filled["queryId"] = data["mention"]["queryId"]
filled["resourceId"] = data["mention"]["resourceId"]
if data["action"] in filters.mutable:
filled[data["action"]] = data["setting"]
else:
raise KeyError("not a mutable field", data["action"])
return filled
class BWAuthorLists(BWResource):
"""
This class provides an interface for Author List operations within a prescribed project.
"""
general_endpoint = "group/author/summary"
specific_endpoint = "group/author"
resource_type = "authorlists"
def add_items(self, name, items):
"""
Adds authors to an existing author list.
Args:
name: Name of the author list to edit.
items: List of new authors to add.
"""
prev_list = set(self.get(name)["authors"])
prev_list.update(items)
new_list = list(prev_list)
self.upload(name=name, authors=new_list)
def _fill_data(self, data):
filled = {}
if ("name" not in data) or ("authors" not in data):
raise KeyError("Need name and authors to upload authorlist", data)
if self.check_resource_exists(
data["name"]
): # if resource exists, create value for filled['id']
filled["id"] = self.get_resource_id(data["name"])
if "new_name" in data:
filled["name"] = data["new_name"]
else:
filled["name"] = data["name"]
filled["authors"] = data["authors"]
filled["shared"] = data["shared"] if "shared" in data else "public"
filled["sharedProjectIds"] = (
data["sharedProjectIds"]
if "sharedProjectIds" in data
else [self.project.project_id]
)
filled["userName"] = self.project.username
filled["userId"] = self.project.get_self()["id"]
return json.dumps(filled)
class BWSiteLists(BWResource):
"""
This class provides an interface for Site List operations within a prescribed project.
"""
general_endpoint = "group/site/summary"
specific_endpoint = "group/site"
resource_type = "sitelists"
def add_items(self, name, items):
"""
Adds sites to an existing site list.
Args:
name: Name of the site list to edit.
items: List of new sites to add.
"""
prev_list = set(self.get(name)["domains"])
prev_list.update(items)
new_list = list(prev_list)
self.upload(name=name, domains=new_list)
def _fill_data(self, data):
filled = {}
if ("name" not in data) or ("domains" not in data):
raise KeyError("Need name and domains to upload sitelist", data)
if self.check_resource_exists(
data["name"]
): # if resource exists, create value for filled['id']
filled["id"] = self.get_resource_id(data["name"])
if "new_name" in data:
filled["name"] = data["new_name"]
else:
filled["name"] = data["name"]
filled["domains"] = data["domains"]
filled["shared"] = data["shared"] if "shared" in data else "public"
filled["sharedProjectIds"] = (
data["sharedProjectIds"]
if "sharedProjectIds" in data
else [self.project.project_id]
)
filled["userName"] = self.project.username
filled["userId"] = self.project.get_self()["id"]
return json.dumps(filled)
class BWLocationLists(BWResource):
"""
This class provides an interface for Location List operations within a prescribed project.
"""
general_endpoint = "group/location/summary"
specific_endpoint = "group/location"
resource_type = "locationlists"
def add_items(self, name, items):
"""
Adds sites to an existing site list.
Args:
name: Name of the location list to edit.
items: List of new locations to add.
"""
prev_list = self.get(name)["locations"]
new_list = prev_list
for item in items:
new_list.append(item)
self.upload(name=name, locations=new_list)
def _fill_data(self, data):
filled = {}
if ("name" not in data) or ("locations" not in data):
raise KeyError("Need name and locations to upload locationlist", data)
if self.check_resource_exists(data["name"]):
filled["id"] = self.get_resource_id(data["name"])
if "new_name" in data:
filled["name"] = data["new_name"]
else:
filled["name"] = data["name"]
filled["locations"] = data["locations"]
filled["shared"] = data["shared"] if "shared" in data else "public"
filled["sharedProjectIds"] = (
data["sharedProjectIds"]
if "sharedProjectIds" in data
else [self.project.project_id]
)
filled["userName"] = self.project.username
filled["userId"] = self.project.get_self()["id"]
return json.dumps(filled)
class BWTags(BWResource):
"""
This class provides an interface for Tag operations within a prescribed project.
"""
general_endpoint = "tags"
specific_endpoint = "tags"
resource_type = "tags"