def __init__(self, config=None, name=NAME, help_string=HELP_STRING): # because public messages are the point of interaction, this is # a map from parsed directives to methods. # each method takes an event, and converts it as needed using the # Where/Context utility constructors. self.command_methods = { 'init': self.init_collective, 'add': self.add_to_collective, 'remove': self.remove_from_collective, 'state': self.state_of_collective, 'ping': self.ping_collective, 'close': self.close_collective, 'love': self.candy_cane, 'help': self.send_help, } self.help_string = help_string if isinstance(config, dict): self.client = zulip.Client(**config) elif isinstance(config, str): self.client = zulip.Client(config_file=config) # besides IO, this is the only state in Coffeebot. self.collectives = {}
def main_loop(): logger.info("Initializing client ...") config_file = os.path.join(os.path.dirname(__file__), "config.ini") config = configparser.ConfigParser() config.read(config_file) zulip_client = zulip.Client(config_file=config_file) stream_name = config['message']['stream'] logger.info("Starting into main loop ...") while True: try: # Calculate time until message and sleep sleep_time = calculate_sleep_time() logger.info("Scheduling next message for {}.".format(sleep_time)) logarithmic_sleep(sleep_time) # Send messages send_menu(zulip_client, stream_name) # Prevent fast retriggering time.sleep(1) except KeyboardInterrupt: logger.info("Received KeyobardInterrupt. Exiting …") return except Exception as e: logger.error("Exception in main loop:", exc_info=e)
def main(cls, match_engine, options): # zuliprc defaults to None, as does config_file # In both cases, this is interpreted as ~/.zuliprc client = zulip.Client(config_file=options.zuliprc) print "Listening..." message_callback = cls.build_processor(match_engine, client) client.call_on_each_message(message_callback)
def __init__(self, zulip_username, zulip_api_key, key_word, subscribed_streams=[], reminder_interval=3600): """ Parameters: ----------- zulip_username: string Email address generated by Zulip, used to authenticate zulip_api_key: string Key generated when bot is registered, used to authenticate key_word: string Word at beginning of message used to trigger bot response subscribed_streams: Streams in which bot listens for commands and posts exercise reminders """ self.username = zulip_username self.api_key = zulip_api_key self.key_word = key_word.lower() self.subscribed_streams = subscribed_streams self.client = zulip.Client(zulip_username, zulip_api_key, site="https://recurse.zulipchat.com/api") self.subscriptions = self.subscribe_to_streams() self.stream_names = [] self.time_last_reminded = datetime.datetime(1970, 1, 1) self.reminder_interval = reminder_interval for stream in self.subscriptions: self.stream_names.append(stream["name"]) self.load_subscribers()
def __init__(self): print(BLUE + "KENZER[3.06] by ARPSyndicate" + CLEAR) print(YELLOW + "automated web assets enumeration & scanning" + CLEAR) self.client = zulip.Client(email=_BotMail, site=_Site, api_key=_APIKey) self.upload = False if _subscribe == "True": self.subscribe() print(YELLOW + "[*] subscribed all streams" + CLEAR) if _uploads == "True": self.upload = True print(YELLOW + "[*] enabled uploads" + CLEAR) print(YELLOW + "[*] training chatterbot" + CLEAR) self.chatbot = ChatBot("Kenzer") self.trainer = ChatterBotCorpusTrainer(self.chatbot) time.sleep(3) self.trainer.train("chatterbot.corpus.english") time.sleep(3) self.modules = [ "monitor", "subenum", "webenum", "headenum", "mailenum", "conenum", "dnsenum", "portenum", "asnenum", "urlenum", "favscan", "cscan", "idscan", "subscan", "cvescan", "vulnscan", "portscan", "parascan", "endscan", "buckscan", "vizscan", "enum", "scan", "recon", "hunt", "remlog", "sync" ] print(YELLOW + "[*] KENZER is online" + CLEAR) print(YELLOW + "[*] {0} modules up & running".format(len(self.modules)) + CLEAR)
def zulip_client(): try: return zulip.Client(email=settings.ZULIP_MAIL, site=settings.ZULIP_URL, api_key=settings.ZULIP_KEY) except: return None
def get_zulip_client_by_org_id(org_id): try: session_local = SessionLocal() return_data = {} org_obj = org_get(db_session=session_local, org_id=org_id) if org_obj and org_obj.zulip_is_active: if org_id in all_zulip_client_dict: return_data = all_zulip_client_dict[org_id] else: all_zulip_client = {} config = get_api(org_obj.zulip_user_name, org_obj.zulip_password, org_obj.zulip_site) if config: client = zulip.Client(email=config.get('email'), api_key=config.get('api_key'), site=org_obj.zulip_site) all_zulip_client[org_obj.id] = { "org_obj": org_obj, "client": ZulipCore(org_obj, client), } return_data = all_zulip_client[org_obj.id] except Exception as e: log.error(f"get_zulip_client_by_org_id failure,msg={e}") finally: session_local.close() return return_data
def __init__(self, config_file="~/zuliprc"): config = configparser.ConfigParser() config.read(os.path.abspath(os.path.expanduser(config_file))) config = config["api"] self.bot_mail = config.get("email") self.client = zulip.Client(config_file=config_file) with open(Path(__file__).parents[1].joinpath("templates", "faq.json")) as file: self.faqs = json.load(file) with open( Path(__file__).parents[1].joinpath("templates", "replies.json")) as file: self.replies = json.load(file) with open( Path(__file__).parents[1].joinpath("templates", "projects.json")) as file: self.projects = json.load(file) self.flatprojects = {} idx = 1 for key in self.projects: for title in self.projects[key]: self.flatprojects[idx] = (title, self.projects[key][title]) idx += 1 with open(Path(__file__).parents[1].joinpath("config", "config.json")) as file: self.config = json.load(file) self.questions = list(question for question in self.faqs["questions"]) self.answers = self.faqs["answers"] self.greetings = self.replies["greetings"] self.stackoverflow = StackAPI("stackoverflow") self.stackoverflow.page_size = 3 # lesser, the faster self.stackoverflow.max_pages = 1 # will hit API only once self.subscribe_all() print("Bot init complete")
def get_zulip_client(): try: all_zulip_client = {} session_local = SessionLocal() org_list = get_all_org(db_session=session_local) for org_obj in org_list: if not org_obj.zulip_is_active: continue config = get_api(org_obj.zulip_user_name, org_obj.zulip_password, org_obj.zulip_site) client = zulip.Client(email=config.get('email'), api_key=config.get('api_key'), site=org_obj.zulip_site) all_zulip_client[org_obj.id] = { "org_obj": org_obj, "client": ZulipCore(org_obj, client), } all_zulip_client[org_obj.id]['client'].init_subcribe_team() except Exception as e: log.error(f"_get_workers failure,msg={e}") finally: try: session_local.close() except: pass return all_zulip_client
def generate_support_stats(): 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) if True: words = [ w for w in word_count.keys() if word_count[w] >= 10 and len(w) >= 5 ] words = sorted(words, key=lambda w: word_count[w], reverse=True) for word in words: print(word, word_count[word]) if False: emails = sorted(list(email_count.keys()), key=lambda w: email_count[w], reverse=True) for email in emails: print(email, email_count[email])
def posttozulip_cs(data, t): s = "***Contest Update***\nCS Academy " + data[0] + " of Duration " + data[ 2] + " to start at " + data[1] + "\n" s += "***Time Remaining: " if (int(t / (3600 * 24)) > 0): m = int(t / (3600 * 24)) s += str(m) + " day(s) " t -= m * 3600 * 24 if (int(t / 3600) > 0): m = int(t / 3600) s += str(m) + " hour(s) " t -= m * 3600 if (int(t / 60) > 0): m = int(t / 60) s += str(m) + " minute(s)" t -= m * 60 s += "***\n" print(s) client = zulip.Client(config_file="zuliprc") request = { "type": "stream", "to": "test here", "subject": "Script Testing", "content": s } result = client.send_message(request) print(result)
def __init__(self, configuration: Union[str, Path]): """Monitor new issues on Redmine and publish to Zulip configuration: toml configuration file """ conf = toml.load(configuration) self._db = dataset.connect(conf['DATABASE']['sql3_file']) self.issues = self._db['issues'] self.zulip = zulip.Client(config_file=conf['ZULIP']['bot']) self.zulip_admin = zulip.Client(config_file=conf['ZULIP']['admin']) self.stream = conf['ZULIP']['stream'] self.redmine = Redmine(conf['REDMINE']) self.feed = conf['REDMINE']['rss_feed']
def __init__(self): self.client = zulip.Client(site="https://chunkzz.zulipchat.com/api/") self.subscribe_all() self.chatbot = ChatBot( "Omega", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() self.tw = Twimega() self.motivate = Motivate() self.shortenedurl = Urlshortener() self.hacknews = Hackernews() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl" ]
def __init__(self): self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie = Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() # self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() # self.tw = Twimega() # self.motivate = Motivate() self.shortenedurl = Urlshortener() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() print("done init") self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl", "movie", "currency", "holiday", "lyrics" ]
def __init__(self, zulip_api, zulip_email, zulip_site): self.email = zulip_email self.site = zulip_site self.api = zulip_api self.client = zulip.Client(email=self.email, api_key=self.api, site=self.site)
def find_email(self, message: Dict[str, Any]) -> str: client = zulip.Client(config_file=Stalker.config_file) members = client.get_members() for member in members['members']: if not (member['is_bot']) and member['full_name'] in message: return member['email'] return 'no user found'
def __init__(self, running, zulip_username, zulip_api_key, key_word, subscribed_streams=None, zulip_site=None): self.running = running self.key_word = key_word.lower() self.subscribed_streams = subscribed_streams or [] self.client = zulip.Client(zulip_username, zulip_api_key, site=zulip_site) self.subscriptions = self.subscribe_to_streams() self.rsvp = rsvp.RSVP(key_word)
def __init__(self, botName, site, email, apiKey): bEmail = email bName = botName self.client = zulip.Client(site=site, email=email, api_key=apiKey) self.subscribe_all() print("done init -> "+str(botName)+' / '+site+' / '+email+' / '+apiKey)
def __init__(self): try: with open(properties, 'rt') as f: self.properties_load = f.read() self.properties_data = json.loads(self.properties_load) except: print('Error:', properties) sys.exit(1) try: with open(self.properties_data['welcome_file'], 'rt') as f: for welcome in f: print(welcome, end='', flush=True) except: print('Error:', self.properties_data['welcome_file']) sys.exit(1) self.lib = lib() if not self.properties_data['dialogflow']['status'] == 'enabled': self.dialog_status = False else: self.dialog = dialog( self.properties_data['dialogflow']['credentials'], self.properties_data['dialogflow']['project_id'], self.properties_data['dialogflow']['language_code'], self.properties_data['dialogflow']['session_id']) self.dialog_status = True self.log = logging.getLogger(__name__) self.log.setLevel(logging.INFO) self.handler = logging.FileHandler( self.properties_data['logging_file']) self.handler.setLevel(logging.INFO) self.formatter = logging.Formatter( self.properties_data['logging_format']) self.handler.setFormatter(self.formatter) self.log.addHandler(self.handler) try: self.client = zulip.Client( config_file=self.properties_data['zuliprc_file']) self.client.get_server_settings() # check connect except: self.log.error('Exception:', exc_info=True) print('Error:', self.properties_data['zuliprc_file']) sys.exit(1) self.log.info('__init__({0})'.format(self)) # self.subscribe_all() self.subscribe([x.lower() for x in self.properties_data['streams']])
def __init__(self): self.client = zulip.Client(site="https://bint.zulipchat.com/api/") self.subscribe_all() self.translate = Translate() self.location = Location() self.news = News() self.subKeys = ["hello", "sample"] self.todoList = []
def send_message(content: str) -> None: request = { "type": "stream", "to": os.environ["ONE_CLICK_ACTION_STREAM"], "topic": "digitalocean installer", "content": content, } zulip.Client().send_message(request)
def __init__(self): self.client = zulip.Client( site="https://merkalysis.zulipchat.com/api/") self.subscribe_all() self.market = Reach() print("done init") self.subkeys = ["reach"]
def _get_zulip_client(): username = os.environ['ZULIP_RSVP_EMAIL'] api_key = os.environ['ZULIP_RSVP_KEY'] site = os.getenv('ZULIP_RSVP_SITE', 'https://recurse.zulipchat.com') client = zulip.Client(username, api_key, site=site) client._register('get_users', method='GET', url='users') return client
def __init__(self, email, api_key): self.email = email # If string starts with "@led-bot" or "led-bot" self.bot_msg_prefix = '^(\\@\\*\\*)*led-bot(\\*\\*)*' self.api_key = api_key self.zulipClient = zulip.Client(email=email, api_key=api_key) self._subscribe_to_threads()
def make_feedback_client(): sys.path.append(os.path.join(os.path.dirname(__file__), '../../api')) import zulip return zulip.Client(client="ZulipFeedback/0.1", email=settings.DEPLOYMENT_ROLE_NAME, api_key=settings.DEPLOYMENT_ROLE_KEY, verbose=True, site=settings.FEEDBACK_TARGET)
def zulip_client(): try: return zulip.Client(email=settings.ZULIP_MAIL, site=settings.ZULIP_URL, api_key=settings.ZULIP_KEY) except: logger.exception( 'An error occurred trying to instantiate Zulip Client') return None
def __init__(self): self.client = zulip.Client(site="https://monbot.hopto.org") self.subscribe_all() print("done init") self.subkeys = [ "translate", "hackernews", "hn", "hotel", "HN", "askme", "cricnews", "movie", "currency", "holiday", "lyrics" ]
def make_feedback_client(): # type: () -> Any # Should be zulip.Client, but not necessarily importable sys.path.append(os.path.join(os.path.dirname(__file__), '../../api')) import zulip return zulip.Client(client="ZulipFeedback/0.1", email=settings.DEPLOYMENT_ROLE_NAME, api_key=settings.DEPLOYMENT_ROLE_KEY, verbose=True, site=settings.FEEDBACK_TARGET)
def __init__(self, zulip_username, zulip_api_key, key_word, search_string, captions=[], subscribed_streams=[]): self.username = zulip_username self.api_key = zulip_api_key self.key_word = key_word.lower() self.subscribed_streams = subscribed_streams self.search_string = search_string.lower() self.caption = captions self.client = zulip.Client(zulip_username, zulip_api_key) self.subscriptions = self.subscribe_to_streams()
def update_org( *, db_session: Session = Depends(get_db), org_id: int, org_in: OrganizationBase, current_user: DispatchUser = Depends(get_current_user), background_tasks: BackgroundTasks, ): """ Update an worker job. """ if current_user.role != UserRoles.OWNER: raise HTTPException( status_code=404, detail= "Normal user is not allowed to modify settings. Only Owner can modify it." ) org = get(db_session=db_session, org_id=org_id) old_org_code = copy.copy(org.code) if not org: raise HTTPException(status_code=404, detail="This organization is not found.") org_by_code_list = get_list(db_session=db_session, org_code=org_in.code) if [i for i in org_by_code_list if str(i.id) != str(org_id)]: raise HTTPException( status_code=404, detail=f"Organization code {org_in.code} does not match") # NOTE: Order matters we have to get the previous state for change detection org_update = update(db_session=db_session, org=org, org_in=org_in) # change auth org code if old_org_code != org_in.code: authService.update_by_org_code(db_session=db_session, org_id=org.id, org_code=org_in.code) try: # zulip change if org_update.id in all_zulip_client_dict: del all_zulip_client_dict[org_update.id] if org_update.zulip_is_active: refresh = False if org_update.zulip_user_name == org.zulip_user_name and org_update.zulip_password == org.zulip_password and org_update.zulip_site == org.zulip_site else True config = get_api(org_update.zulip_user_name, org_update.zulip_password, org_update.zulip_site, refresh=refresh) client = zulip.Client(email=config.get('email'), api_key=config.get('api_key'), site=org_update.zulip_site) all_zulip_client_dict[org_update.id] = { "org_obj": org_update, "client": ZulipCore(org_update, client), } except Exception as e: raise HTTPException(status_code=400, detail=f"zulip init error ,{e}") return org_update