-
-
Notifications
You must be signed in to change notification settings - Fork 361
/
__init__.py
1811 lines (1570 loc) · 61.5 KB
/
__init__.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
import argparse
import json
import logging
import optparse
import os
import platform
import random
import sys
import time
import traceback
import types
import urllib.parse
from configparser import ConfigParser
from typing import (
IO,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Union,
)
import distro
import requests
from typing_extensions import Literal, override
__version__ = "0.9.0"
# Ensure the Python version is supported
assert sys.version_info >= (3, 6)
logger = logging.getLogger(__name__)
API_VERSTRING = "v1/"
# An optional parameter to `move_topic` and `update_message` actions
# See eg. https://zulip.com/api/update-message#parameter-propagate_mode
EditPropagateMode = Literal["change_one", "change_all", "change_later"]
# Generally a `reaction_type` is present whenever an emoji is specified:
# - Optional parameters to actions: `add_reaction`, `remove_reaction`
# - Events: "user_status", "reaction", "message", "update_message"
# - Inside each reaction in the `reactions` field of returned message objects.
EmojiType = Literal["realm_emoji", "unicode_emoji", "zulip_extra_emoji"]
# Message flags which may be directly modified by the current user:
# - Updated by `update_message_flags` (and for the `read` flag, also
# the `mark_all_as_read`, `mark_stream_as_read`, and
# `mark_topic_as_read` actions).
# - User is notified of changes via `update_message_flags` events.
# See subset of https://zulip.com/api/update-message-flags#available-flags
ModifiableMessageFlag = Literal["read", "starred", "collapsed"]
# All possible message flags.
# - Generally present in `flags` object of returned message objects.
# - User is notified of changes via "update_message_flags" and `update_message`
# events. The latter is important for clients to learn when a message is
# edited to mention the current user or contain an alert word.
# See https://zulip.com/api/update-message-flags#available-flags
MessageFlag = Literal[
ModifiableMessageFlag,
"mentioned",
"wildcard_mentioned",
"has_alert_word",
"historical",
]
class CountingBackoff:
def __init__(
self,
maximum_retries: int = 10,
timeout_success_equivalent: Optional[float] = None,
delay_cap: float = 90.0,
) -> None:
"""Sets up a retry-backoff object. Example usage:
backoff = zulip.CountingBackoff()
while backoff.keep_going():
try:
something()
backoff.succeed()
except Exception:
backoff.fail()
timeout_success_equivalent is used in cases where 'success' is
never possible to determine automatically; it sets the
threshold in seconds before the next keep_going/fail, above
which the last run is treated like it was a success.
"""
self.number_of_retries = 0
self.maximum_retries = maximum_retries
self.timeout_success_equivalent = timeout_success_equivalent
self.last_attempt_time = 0.0
self.delay_cap = delay_cap
def keep_going(self) -> bool:
self._check_success_timeout()
return self.number_of_retries < self.maximum_retries
def succeed(self) -> None:
self.number_of_retries = 0
self.last_attempt_time = time.time()
def fail(self) -> None:
self._check_success_timeout()
self.number_of_retries = min(self.number_of_retries + 1, self.maximum_retries)
self.last_attempt_time = time.time()
def _check_success_timeout(self) -> None:
if (
self.timeout_success_equivalent is not None
and self.last_attempt_time != 0
and time.time() - self.last_attempt_time > self.timeout_success_equivalent
):
self.number_of_retries = 0
class RandomExponentialBackoff(CountingBackoff):
@override
def fail(self) -> None:
super().fail()
# Exponential growth with ratio sqrt(2); compute random delay
# between x and 2x where x is growing exponentially
delay_scale = int(2 ** (self.number_of_retries / 2.0 - 1)) + 1
delay = min(delay_scale + random.randint(1, delay_scale), self.delay_cap) # noqa: S311
message = f"Sleeping for {delay}s [max {delay_scale * 2}] before retrying."
try:
logger.warning(message)
except NameError:
print(message)
time.sleep(delay)
def _default_client() -> str:
return "ZulipPython/" + __version__
def add_default_arguments(
parser: argparse.ArgumentParser,
patch_error_handling: bool = True,
allow_provisioning: bool = False,
) -> argparse.ArgumentParser:
if patch_error_handling:
def custom_error_handling(self: argparse.ArgumentParser, message: str) -> None:
self.print_help(sys.stderr)
self.exit(2, f"{self.prog}: error: {message}\n")
parser.error = types.MethodType(custom_error_handling, parser) # type: ignore[method-assign] # patching function
if allow_provisioning:
parser.add_argument(
"--provision",
action="store_true",
dest="provision",
help="install dependencies for this script (found in requirements.txt)",
)
group = parser.add_argument_group("Zulip API configuration")
group.add_argument("--site", dest="zulip_site", help="Zulip server URI", default=None)
group.add_argument("--api-key", dest="zulip_api_key", action="store")
group.add_argument(
"--user", dest="zulip_email", help="Email address of the calling bot or user."
)
group.add_argument(
"--config-file",
action="store",
dest="zulip_config_file",
help="""Location of an ini file containing the above
information. (default ~/.zuliprc)""",
)
group.add_argument("-v", "--verbose", action="store_true", help="Provide detailed output.")
group.add_argument(
"--client", action="store", default=None, dest="zulip_client", help=argparse.SUPPRESS
)
group.add_argument(
"--insecure",
action="store_true",
dest="insecure",
help="""Do not verify the server certificate.
The https connection will not be secure.""",
)
group.add_argument(
"--cert-bundle",
action="store",
dest="cert_bundle",
help="""Specify a file containing either the
server certificate, or a set of trusted
CA certificates. This will be used to
verify the server's identity. All
certificates should be PEM encoded.""",
)
group.add_argument(
"--client-cert",
action="store",
dest="client_cert",
help="""Specify a file containing a client
certificate (not needed for most deployments).""",
)
group.add_argument(
"--client-cert-key",
action="store",
dest="client_cert_key",
help="""Specify a file containing the client
certificate's key (if it is in a separate
file).""",
)
return parser
# This method might seem redundant with `add_default_arguments()`,
# except for the fact that is uses the deprecated `optparse` module.
# We still keep it for legacy support of out-of-tree bots and integrations
# depending on it.
def generate_option_group(parser: optparse.OptionParser, prefix: str = "") -> optparse.OptionGroup:
logging.warning(
"""zulip.generate_option_group is based on optparse, which
is now deprecated. We recommend migrating to argparse and
using zulip.add_default_arguments instead."""
)
group = optparse.OptionGroup(parser, "Zulip API configuration")
group.add_option(f"--{prefix}site", dest="zulip_site", help="Zulip server URI", default=None)
group.add_option(f"--{prefix}api-key", dest="zulip_api_key", action="store")
group.add_option(
f"--{prefix}user",
dest="zulip_email",
help="Email address of the calling bot or user.",
)
group.add_option(
f"--{prefix}config-file",
action="store",
dest="zulip_config_file",
help="Location of an ini file containing the\nabove information. (default ~/.zuliprc)",
)
group.add_option("-v", "--verbose", action="store_true", help="Provide detailed output.")
group.add_option(
f"--{prefix}client",
action="store",
default=None,
dest="zulip_client",
help=optparse.SUPPRESS_HELP,
)
group.add_option(
"--insecure",
action="store_true",
dest="insecure",
help="""Do not verify the server certificate.
The https connection will not be secure.""",
)
group.add_option(
"--cert-bundle",
action="store",
dest="cert_bundle",
help="""Specify a file containing either the
server certificate, or a set of trusted
CA certificates. This will be used to
verify the server's identity. All
certificates should be PEM encoded.""",
)
group.add_option(
"--client-cert",
action="store",
dest="client_cert",
help="""Specify a file containing a client
certificate (not needed for most deployments).""",
)
group.add_option(
"--client-cert-key",
action="store",
dest="client_cert_key",
help="""Specify a file containing the client
certificate's key (if it is in a separate
file).""",
)
return group
def init_from_options(options: Any, client: Optional[str] = None) -> "Client":
if getattr(options, "provision", False):
requirements_path = os.path.abspath(os.path.join(sys.path[0], "requirements.txt"))
try:
import pip
except ImportError:
traceback.print_exc()
print(
"Module `pip` is not installed. To install `pip`, follow the instructions here: "
"https://pip.pypa.io/en/stable/installing/"
)
sys.exit(1)
if not pip.main(["install", "--upgrade", "--requirement", requirements_path]):
print(
"{color_green}You successfully provisioned the dependencies for {script}.{end_color}".format(
color_green="\033[92m",
end_color="\033[0m",
script=os.path.splitext(os.path.basename(sys.argv[0]))[0],
)
)
sys.exit(0)
if options.zulip_client is not None:
client = options.zulip_client
elif client is None:
client = _default_client()
return Client(
email=options.zulip_email,
api_key=options.zulip_api_key,
config_file=options.zulip_config_file,
verbose=options.verbose,
site=options.zulip_site,
client=client,
cert_bundle=options.cert_bundle,
insecure=options.insecure,
client_cert=options.client_cert,
client_cert_key=options.client_cert_key,
)
def get_default_config_filename() -> Optional[str]:
if os.environ.get("HOME") is None:
return None
config_file = os.path.join(os.environ["HOME"], ".zuliprc")
if not os.path.exists(config_file) and os.path.exists(
os.path.join(os.environ["HOME"], ".humbugrc")
):
raise ZulipError(
"The Zulip API configuration file is now ~/.zuliprc; please run:\n\n"
" mv ~/.humbugrc ~/.zuliprc\n"
)
return config_file
def validate_boolean_field(field: Optional[str]) -> Union[bool, None]:
if not isinstance(field, str):
return None
field = field.lower()
if field == "true":
return True
elif field == "false":
return False
else:
return None
class ZulipError(Exception):
pass
class ConfigNotFoundError(ZulipError):
pass
class MissingURLError(ZulipError):
pass
class UnrecoverableNetworkError(ZulipError):
pass
class Client:
def __init__(
self,
email: Optional[str] = None,
api_key: Optional[str] = None,
config_file: Optional[str] = None,
verbose: bool = False,
retry_on_errors: bool = True,
site: Optional[str] = None,
client: Optional[str] = None,
cert_bundle: Optional[str] = None,
insecure: Optional[bool] = None,
client_cert: Optional[str] = None,
client_cert_key: Optional[str] = None,
) -> None:
if client is None:
client = _default_client()
# Normalize user-specified path
if config_file is not None:
config_file = os.path.abspath(os.path.expanduser(config_file))
# Fill values from Environment Variables if not available in Constructor
if config_file is None:
config_file = os.environ.get("ZULIP_CONFIG")
if api_key is None:
api_key = os.environ.get("ZULIP_API_KEY")
if email is None:
email = os.environ.get("ZULIP_EMAIL")
if site is None:
site = os.environ.get("ZULIP_SITE")
if client_cert is None:
client_cert = os.environ.get("ZULIP_CERT")
if client_cert_key is None:
client_cert_key = os.environ.get("ZULIP_CERT_KEY")
if cert_bundle is None:
cert_bundle = os.environ.get("ZULIP_CERT_BUNDLE")
if insecure is None:
# Be quite strict about what is accepted so that users don't
# disable security unintentionally.
insecure_setting = os.environ.get("ZULIP_ALLOW_INSECURE")
if insecure_setting is not None:
insecure = validate_boolean_field(insecure_setting)
if insecure is None:
raise ZulipError(
"The ZULIP_ALLOW_INSECURE environment "
f"variable is set to '{insecure_setting}', it must be "
"'true' or 'false'"
)
if config_file is None:
config_file = get_default_config_filename()
if config_file is not None and os.path.exists(config_file):
config = ConfigParser()
with open(config_file) as f:
config.read_file(f, config_file)
if api_key is None:
api_key = config.get("api", "key")
if email is None:
email = config.get("api", "email")
if site is None and config.has_option("api", "site"):
site = config.get("api", "site")
if client_cert is None and config.has_option("api", "client_cert"):
client_cert = config.get("api", "client_cert")
if client_cert_key is None and config.has_option("api", "client_cert_key"):
client_cert_key = config.get("api", "client_cert_key")
if cert_bundle is None and config.has_option("api", "cert_bundle"):
cert_bundle = config.get("api", "cert_bundle")
if insecure is None and config.has_option("api", "insecure"):
# Be quite strict about what is accepted so that users don't
# disable security unintentionally.
insecure_setting = config.get("api", "insecure")
insecure = validate_boolean_field(insecure_setting)
if insecure is None:
raise ZulipError(
f"insecure is set to '{insecure_setting}', it must be "
f"'true' or 'false' if it is used in {config_file}"
)
elif None in (api_key, email):
raise ConfigNotFoundError(
f"api_key or email not specified and file {config_file} does not exist"
)
assert api_key is not None and email is not None
self.api_key = api_key
self.email = email
self.verbose = verbose
if site is not None:
if site.startswith("localhost"):
site = "http://" + site
elif not site.startswith("http"):
site = "https://" + site
# Remove trailing "/"s from site to simplify the below logic for adding "/api"
site = site.rstrip("/")
self.base_url = site
else:
raise MissingURLError("Missing Zulip server URL; specify via --site or ~/.zuliprc.")
if not self.base_url.endswith("/api"):
self.base_url += "/api"
self.base_url += "/"
self.retry_on_errors = retry_on_errors
self.client_name = client
if insecure:
logger.warning(
"Insecure mode enabled. The server's SSL/TLS "
"certificate will not be validated, making the "
"HTTPS connection potentially insecure"
)
self.tls_verification: Union[bool, str] = False
elif cert_bundle is not None:
if not os.path.isfile(cert_bundle):
raise ConfigNotFoundError(f"tls bundle '{cert_bundle}' does not exist")
self.tls_verification = cert_bundle
else:
# Default behavior: verify against system CA certificates
self.tls_verification = True
if client_cert is None:
if client_cert_key is not None:
raise ConfigNotFoundError(
f"client cert key '{client_cert_key}' specified, but no client cert public part provided"
)
else: # we have a client cert
if not os.path.isfile(client_cert):
raise ConfigNotFoundError(f"client cert '{client_cert}' does not exist")
if client_cert_key is not None and not os.path.isfile(client_cert_key):
raise ConfigNotFoundError(f"client cert key '{client_cert_key}' does not exist")
self.client_cert = client_cert
self.client_cert_key = client_cert_key
self.session: Optional[requests.Session] = None
self.has_connected = False
server_settings = self.get_server_settings()
self.zulip_version: Optional[str] = server_settings.get("zulip_version")
self.feature_level: int = server_settings.get("zulip_feature_level", 0)
assert self.zulip_version is not None
def ensure_session(self) -> None:
# Check if the session has been created already, and return
# immediately if so.
if self.session:
return
# Build a client cert object for requests
if self.client_cert_key is not None:
assert self.client_cert is not None # Otherwise ZulipError near end of __init__
client_cert: Union[None, str, Tuple[str, str]] = (
self.client_cert,
self.client_cert_key,
)
else:
client_cert = self.client_cert
# Actually construct the session
session = requests.Session()
session.auth = requests.auth.HTTPBasicAuth(self.email, self.api_key)
session.verify = self.tls_verification
session.cert = client_cert
session.headers.update({"User-agent": self.get_user_agent()})
self.session = session
def get_user_agent(self) -> str:
vendor = ""
vendor_version = ""
try:
vendor = platform.system()
vendor_version = platform.release()
except OSError:
# If the calling process is handling SIGCHLD, platform.system() can
# fail with an IOError. See http://bugs.python.org/issue9127
pass
if vendor == "Linux":
vendor = distro.name()
vendor_version = distro.version()
elif vendor == "Windows":
vendor_version = platform.win32_ver()[1]
elif vendor == "Darwin":
vendor_version = platform.mac_ver()[0]
return f"{self.client_name} ({vendor}; {vendor_version})"
def do_api_query(
self,
orig_request: Mapping[str, Any],
url: str,
method: str = "POST",
longpolling: bool = False,
files: Optional[List[IO[Any]]] = None,
timeout: Optional[float] = None,
) -> Dict[str, Any]:
if files is None:
files = []
# When long-polling, set timeout to 90 sec as a balance
# between a low traffic rate and a still reasonable latency
# time in case of a connection failure.
# Otherwise, 15s should be plenty of time.
request_timeout = 90.0 if longpolling else timeout or 15.0
request = {
key: val if isinstance(val, str) else json.dumps(val)
for key, val in orig_request.items()
}
req_files = [(f.name, f) for f in files]
self.ensure_session()
assert self.session is not None
query_state: Dict[str, Any] = {
"had_error_retry": False,
"request": request,
"failures": 0,
}
def error_retry(error_string: str) -> bool:
if not self.retry_on_errors or query_state["failures"] >= 10:
return False
if self.verbose:
if not query_state["had_error_retry"]:
sys.stdout.write(
"zulip API({}): connection error{} -- retrying.".format(
url.split(API_VERSTRING, 2)[0],
error_string,
)
)
query_state["had_error_retry"] = True
else:
sys.stdout.write(".")
sys.stdout.flush()
query_state["request"]["dont_block"] = json.dumps(True)
time.sleep(1)
query_state["failures"] += 1
return True
def end_error_retry(succeeded: bool) -> None:
if query_state["had_error_retry"] and self.verbose:
if succeeded:
print("Success!")
else:
print("Failed!")
while True:
try:
kwarg = "params" if method == "GET" else "data"
kwargs = {kwarg: query_state["request"]}
if files:
kwargs["files"] = req_files
# Actually make the request!
res = self.session.request(
method,
urllib.parse.urljoin(self.base_url, url),
timeout=request_timeout,
**kwargs,
)
self.has_connected = True
# On 50x errors, try again after a short sleep
if str(res.status_code).startswith("5") and error_retry(
f" (server {res.status_code})"
):
continue
# Otherwise fall through and process the python-requests error normally
except (requests.exceptions.Timeout, requests.exceptions.SSLError) as e:
# Timeouts are either a Timeout or an SSLError; we
# want the later exception handlers to deal with any
# non-timeout other SSLErrors
if (
isinstance(e, requests.exceptions.SSLError)
and str(e) != "The read operation timed out"
):
raise UnrecoverableNetworkError("SSL Error") from e
if longpolling:
# When longpolling, we expect the timeout to fire,
# and the correct response is to just retry
continue
else:
end_error_retry(False)
raise
except requests.exceptions.ConnectionError as e:
if not self.has_connected:
# If we have never successfully connected to the server, don't
# go into retry logic, because the most likely scenario here is
# that somebody just hasn't started their server, or they passed
# in an invalid site.
raise UnrecoverableNetworkError(
"cannot connect to server " + self.base_url
) from e
if error_retry(""):
continue
end_error_retry(False)
raise
except Exception:
# We'll split this out into more cases as we encounter new bugs.
raise
try:
json_result = res.json()
except Exception:
end_error_retry(False)
return {
"msg": "Unexpected error from the server",
"result": "http-error",
"status_code": res.status_code,
}
end_error_retry(True)
return json_result
def call_endpoint(
self,
url: Optional[str] = None,
method: str = "POST",
request: Optional[Dict[str, Any]] = None,
longpolling: bool = False,
files: Optional[List[IO[Any]]] = None,
timeout: Optional[float] = None,
) -> Dict[str, Any]:
if request is None:
request = dict()
marshalled_request = {}
for k, v in request.items():
if v is not None:
marshalled_request[k] = v
versioned_url = API_VERSTRING + (url if url is not None else "")
return self.do_api_query(
marshalled_request,
versioned_url,
method=method,
longpolling=longpolling,
files=files,
timeout=timeout,
)
def call_on_each_event(
self,
callback: Callable[[Dict[str, Any]], None],
event_types: Optional[List[str]] = None,
narrow: Optional[List[List[str]]] = None,
**kwargs: object,
) -> None:
if narrow is None:
narrow = []
def do_register() -> Tuple[str, int]:
while True:
if event_types is None:
res = self.register(None, None, **kwargs)
else:
res = self.register(event_types, narrow, **kwargs)
if "error" in res["result"]:
if self.verbose:
print("Server returned error:\n{}".format(res["msg"]))
time.sleep(1)
else:
return (res["queue_id"], res["last_event_id"])
queue_id = None
# Make long-polling requests with `get_events`. Once a request
# has received an answer, pass it to the callback and before
# making a new long-polling request.
while True:
if queue_id is None:
queue_id, last_event_id = do_register()
try:
res = self.get_events(queue_id=queue_id, last_event_id=last_event_id)
except (
requests.exceptions.Timeout,
requests.exceptions.SSLError,
requests.exceptions.ConnectionError,
):
if self.verbose:
print(f"Connection error fetching events:\n{traceback.format_exc()}")
# TODO: Make this use our backoff library
time.sleep(1)
continue
except Exception:
print(f"Unexpected error:\n{traceback.format_exc()}")
# TODO: Make this use our backoff library
time.sleep(1)
continue
if "error" in res["result"]:
if res["result"] == "http-error":
if self.verbose:
print("HTTP error fetching events -- probably a server restart")
else:
if self.verbose:
print("Server returned error:\n{}".format(res["msg"]))
# Eventually, we'll only want the
# BAD_EVENT_QUEUE_ID check, but we check for the
# old string to support legacy Zulip servers. We
# should remove that legacy check in 2019.
if res.get("code") == "BAD_EVENT_QUEUE_ID" or res["msg"].startswith(
"Bad event queue id:"
):
# Our event queue went away, probably because
# we were asleep or the server restarted
# abnormally. We may have missed some
# events while the network was down or
# something, but there's not really anything
# we can do about it other than resuming
# getting new ones.
#
# Reset queue_id to register a new event queue.
queue_id = None
# Add a pause here to cover against potential bugs in this library
# causing a DoS attack against a server when getting errors.
# TODO: Make this back off exponentially.
time.sleep(1)
continue
for event in res["events"]:
last_event_id = max(last_event_id, int(event["id"]))
if event["type"] == "heartbeat":
# Heartbeat events are sent to clients regardless
# of the client's requested event types, and are
# intended to be an internal part of the Zulip
# longpolling protocol, not something that clients
# need to handle.
continue
callback(event)
def call_on_each_message(
self, callback: Callable[[Dict[str, Any]], None], **kwargs: object
) -> None:
def event_callback(event: Dict[str, Any]) -> None:
if event["type"] == "message":
callback(event["message"])
self.call_on_each_event(event_callback, ["message"], None, **kwargs)
def get_messages(self, message_filters: Dict[str, Any]) -> Dict[str, Any]:
"""
See examples/get-messages for example usage
"""
return self.call_endpoint(url="messages", method="GET", request=message_filters)
def check_messages_match_narrow(self, **request: Dict[str, Any]) -> Dict[str, Any]:
"""
Example usage:
>>> client.check_messages_match_narrow(msg_ids=[11, 12],
narrow=[{'operator': 'has', 'operand': 'link'}]
)
{'result': 'success', 'msg': '', 'messages': [{...}, {...}]}
"""
return self.call_endpoint(url="messages/matches_narrow", method="GET", request=request)
def get_raw_message(self, message_id: int) -> Dict[str, str]:
"""
See examples/get-raw-message for example usage
"""
return self.call_endpoint(url=f"messages/{message_id}", method="GET")
def send_message(self, message_data: Dict[str, Any]) -> Dict[str, Any]:
"""
See examples/send-message for example usage.
"""
return self.call_endpoint(
url="messages",
request=message_data,
)
def upload_file(self, file: IO[Any]) -> Dict[str, Any]:
"""
See examples/upload-file for example usage.
"""
return self.call_endpoint(url="user_uploads", files=[file])
def get_attachments(self) -> Dict[str, Any]:
"""
Example usage:
>>> client.get_attachments()
{'result': 'success', 'msg': '', 'attachments': [{...}, {...}]}
"""
return self.call_endpoint(url="attachments", method="GET")
def update_message(self, message_data: Dict[str, Any]) -> Dict[str, Any]:
"""
See examples/edit-message for example usage.
"""
return self.call_endpoint(
url="messages/%d" % (message_data["message_id"],),
method="PATCH",
request=message_data,
)
def delete_message(self, message_id: int) -> Dict[str, Any]:
"""
See examples/delete-message for example usage.
"""
return self.call_endpoint(url=f"messages/{message_id}", method="DELETE")
def update_message_flags(self, update_data: Dict[str, Any]) -> Dict[str, Any]:
"""
See examples/update-flags for example usage.
"""
return self.call_endpoint(url="messages/flags", method="POST", request=update_data)
def mark_all_as_read(self) -> Dict[str, Any]:
"""
Example usage:
>>> client.mark_all_as_read()
{'result': 'success', 'msg': ''}
"""
return self.call_endpoint(
url="mark_all_as_read",
method="POST",
)
def mark_stream_as_read(self, stream_id: int) -> Dict[str, Any]:
"""
Example usage:
>>> client.mark_stream_as_read(42)
{'result': 'success', 'msg': ''}
"""
return self.call_endpoint(
url="mark_stream_as_read",
method="POST",
request={"stream_id": stream_id},
)
def mark_topic_as_read(self, stream_id: int, topic_name: str) -> Dict[str, Any]:
"""
Example usage:
>>> client.mark_all_as_read(42, 'new coffee machine')
{'result': 'success', 'msg': ''}
"""
return self.call_endpoint(
url="mark_topic_as_read",
method="POST",
request={
"stream_id": stream_id,
"topic_name": topic_name,
},
)
def get_message_history(self, message_id: int) -> Dict[str, Any]:
"""
See examples/message-history for example usage.
"""
return self.call_endpoint(url=f"messages/{message_id}/history", method="GET")
def add_reaction(self, reaction_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Example usage:
>>> client.add_reaction({
'message_id': 100,
'emoji_name': 'joy',
'emoji_code': '1f602',
'reaction_type': 'unicode_emoji'
})
{'result': 'success', 'msg': ''}
"""
return self.call_endpoint(
url="messages/{}/reactions".format(reaction_data["message_id"]),
method="POST",
request=reaction_data,
)
def remove_reaction(self, reaction_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Example usage:
>>> client.remove_reaction({
'message_id': 100,
'emoji_name': 'joy',
'emoji_code': '1f602',
'reaction_type': 'unicode_emoji'
})
{'msg': '', 'result': 'success'}
"""
return self.call_endpoint(
url="messages/{}/reactions".format(reaction_data["message_id"]),
method="DELETE",
request=reaction_data,
)
def get_realm_emoji(self) -> Dict[str, Any]:
"""
See examples/realm-emoji for example usage.
"""
return self.call_endpoint(url="realm/emoji", method="GET")
def upload_custom_emoji(self, emoji_name: str, file_obj: IO[Any]) -> Dict[str, Any]:
"""
Example usage:
>>> client.upload_custom_emoji(emoji_name, file_obj)
{'result': 'success', 'msg': ''}
"""
return self.call_endpoint(f"realm/emoji/{emoji_name}", method="POST", files=[file_obj])
def delete_custom_emoji(self, emoji_name: str) -> Dict[str, Any]:
"""
Example usage:
>>> client.delete_custom_emoji("green_tick")
{'result': 'success', 'msg': ''}
"""
return self.call_endpoint(
url=f"realm/emoji/{emoji_name}",
method="DELETE",
)
def get_realm_linkifiers(self) -> Dict[str, Any]:
"""
Example usage: