Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import sys
import os.path
import git_p4
__version__ = "0.1"
sys.path.insert(0, os.path.dirname(__file__))
from typing import Any, Dict, Optional, Text
import zulip_perforce_config as config
if config.ZULIP_API_PATH is not None:
sys.path.append(config.ZULIP_API_PATH)
import zulip
client = zulip.Client(
email=config.ZULIP_USER,
site=config.ZULIP_SITE,
api_key=config.ZULIP_API_KEY,
client="ZulipPerforce/" + __version__) # type: zulip.Client
try:
changelist = int(sys.argv[1]) # type: int
changeroot = sys.argv[2] # type: str
except IndexError:
print("Wrong number of arguments.\n\n", end=' ', file=sys.stderr)
print(__doc__, file=sys.stderr)
sys.exit(-1)
except ValueError:
print("First argument must be an integer.\n\n", end=' ', file=sys.stderr)
print(__doc__, file=sys.stderr)
sys.exit(-1)
try:
config = read_configuration(options.config)
except Bridge_ConfigException as exception:
print("Could not parse config file: {}".format(exception))
sys.exit(1)
# Get config for each client
zulip_config = config["zulip"]
matrix_config = config["matrix"]
# Initiate clients
backoff = zulip.RandomExponentialBackoff(timeout_success_equivalent=300)
while backoff.keep_going():
print("Starting matrix mirroring bot")
try:
zulip_client = zulip.Client(email=zulip_config["email"],
api_key=zulip_config["api_key"],
site=zulip_config["site"])
matrix_client = MatrixClient(matrix_config["host"])
# Login to Matrix
matrix_login(matrix_client, matrix_config)
# Join a room in Matrix
room = matrix_join_room(matrix_client, matrix_config)
room.add_listener(matrix_to_zulip(zulip_client, zulip_config, matrix_config,
options.no_noise))
print("Starting listener thread on Matrix client")
matrix_client.start_listener_thread()
print("Starting message handler on Zulip client")
Could not find API key file.
You need to either place your api key file at %s,
or specify the --api-key-file option.""" % (options.api_key_file,))))
sys.exit(1)
api_key = open(options.api_key_file).read().strip()
# Store the API key in the environment so that our children
# don't need to read it in
os.environ["HUMBUG_API_KEY"] = api_key
if options.nagios_path is None and options.nagios_class is not None:
logger.error("\n" + "nagios_path is required with nagios_class\n")
sys.exit(1)
zulip_account_email = options.user + "@mit.edu"
import zulip
zulip_client = zulip.Client(
email=zulip_account_email,
api_key=api_key,
verbose=True,
client="zephyr_mirror",
site=options.site)
start_time = time.time()
if options.sync_subscriptions:
configure_logger(logger, None) # make the output cleaner
logger.info("Syncing your ~/.zephyr.subs to your Zulip Subscriptions!")
add_zulip_subscriptions(True)
sys.exit(0)
# Kill all zephyr_mirror processes other than this one and its parent.
if not options.test_mode:
from trac.core import Component, implements
from trac.ticket import ITicketChangeListener
import sys
import os.path
sys.path.insert(0, os.path.dirname(__file__))
import zulip_trac_config as config
VERSION = "0.9"
if False:
from typing import Any, Dict
if config.ZULIP_API_PATH is not None:
sys.path.append(config.ZULIP_API_PATH)
import zulip
client = zulip.Client(
email=config.ZULIP_USER,
site=config.ZULIP_SITE,
api_key=config.ZULIP_API_KEY,
client="ZulipTrac/" + VERSION)
def markdown_ticket_url(ticket, heading="ticket"):
# type: (Any, str) -> str
return "[%s #%s](%s/%s)" % (heading, ticket.id, config.TRAC_BASE_TICKET_URL, ticket.id)
def markdown_block(desc):
# type: (str) -> str
return "\n\n>" + "\n> ".join(desc.split("\n")) + "\n"
def truncate(string, length):
# type: (str, int) -> str
if len(string) <= length:
def send_zulip(email, api_key, site, stream, subject, content):
# type: (str, str, str, str, str, Text) -> None
"""
Send a message to Zulip using the provided credentials, which should be for
a bot in most cases.
"""
client = zulip.Client(email=email, api_key=api_key,
site=site,
client="ZulipMercurial/" + VERSION)
message_data = {
"type": "stream",
"to": stream,
"subject": subject,
"content": content,
}
client.send_message(message_data)
def load_bot_handlers(
available_bots: List[str],
bots_config: Dict[str, Dict[str, str]],
third_party_bot_conf: Optional[configparser.ConfigParser]=None,
) -> Dict[str, lib.ExternalBotHandler]:
bot_handlers = {}
for bot in available_bots:
client = Client(email=bots_config[bot]["email"],
api_key=bots_config[bot]["key"],
site=bots_config[bot]["site"])
bot_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bots', bot)
bot_handler = lib.ExternalBotHandler(
client,
bot_dir,
bot_details={},
bot_config_parser=third_party_bot_conf
)
bot_handlers[bot] = bot_handler
return bot_handlers
#!/usr/bin/env python3
import sys
import os
import simplejson
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'api'))
import zulip
zulip_client = zulip.Client(site="http://localhost:9991", client="ZulipGithubPayloadSender/0.1")
payload_dir = "zerver/fixtures/github"
for filename in os.listdir(payload_dir):
with open(os.path.join(payload_dir, filename)) as f:
req = simplejson.loads(f.read())
req['api-key'] = zulip_client.api_key
req['email'] = zulip_client.email
zulip_client.do_api_query(req, zulip.API_VERSTRING + "external/github")
def generate_support_stats():
# type: () -> None
client = zulip.Client()
narrow = 'stream:support'
count = 2000
msgs = get_recent_messages(client, narrow, count)
msgs_by_topic = collections.defaultdict(list) # type: Dict[str, List[Dict[str, Any]]]
for msg in msgs:
topic = msg['subject']
msgs_by_topic[topic].append(msg)
word_count = collections.defaultdict(int) # type: Dict[str, int]
email_count = collections.defaultdict(int) # type: Dict[str, int]
if False:
for topic in msgs_by_topic:
msgs = msgs_by_topic[topic]
analyze_messages(msgs, word_count, email_count)
#!/usr/bin/env python
import zulip
import json
import requests
import random
import os
# create a Zulip client/bot
client = zulip.Client(email=os.environ['ZULIP_USERNAME'],
api_key=os.environ['ZULIP_API_KEY'])
# call Zulip API to get list of all streams
def get_zulip_streams():
response = requests.get(
'https://api.zulip.com/v1/streams',
auth=requests.auth.HTTPBasicAuth(os.environ['ZULIP_USERNAME'], os.environ['ZULIP_API_KEY'])
)
if response.status_code == 200:
return response.json()['streams']
elif response.status_code == 401:
raise RuntimeError('check yo auth')
else: