zulip/tools/inject-messages/inject-messages

114 lines
3.5 KiB
Python
Executable File

#!/usr/bin/python
import sys
import os
import optparse
import re
usage = """inject-messages [options]
Sends a bunch of messages to the specified site.
"""
parser = optparse.OptionParser(usage=usage)
parser.add_option("--site",
dest="site",
default="http://localhost:9991",
action="store")
(options, args) = parser.parse_args()
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
import api.common
characters = {'othello': {'api-key': '4e5d97591bec64bf57d2698ffbb563e3', 'intro': ''},
'iago': {'api-key': 'd43b53c27a8106195b46781abc67901a', 'intro': ''}}
users = {}
def gen_next_user():
global users
user_list = users.keys()
user_list.sort()
while True:
for user in user_list:
yield user
next_user = gen_next_user()
def connect_all(users):
for user in users:
users[user]['client'] = api.common.HumbugAPI(email=user + '@humbughq.com',
api_key=users[user]['api-key'],
site=options.site,
verbose=True)
connect_all(characters)
connect_all(users)
def truncate(string, length):
if len(string) <= length:
return string
return string[:length - 3] + "..."
last_character = None
num_messages_sent = 0
def send_message(character, text, subject):
global characters
global last_character
global num_messages_sent
message = text
if character != last_character:
message = characters[character]['intro'] + message
client = characters[character]["client"]
request = {'type': 'stream',
'content': message,
'stream': 'othello',
'subject': truncate(subject, 60)}
response = client.send_message(request)
if response['result'] != 'success':
print "Could not send message (API Key " + characters[character]["api-key"] + "):"
print " Request:", request
print " Response:", response
exit(1)
last_character = character
num_messages_sent += 1
if num_messages_sent % 100 == 0:
print "Sent %s messages" % (num_messages_sent,)
def maybe_assign_character(character):
global characters
global users
if not character in characters:
user = next_user.next()
characters[character] = dict(users[user])
characters[character]['intro'] = '(as ' + character.title() + ")\n"
play = file(os.path.dirname(__file__) + os.path.sep + "othello")
next_character = None
next_message = ""
act = ""
subject = ""
for line in play:
if re.search('^\s*$', line):
continue
elif re.search('^ACT', line):
act = line.strip()
elif re.search('^SCENE', line):
subject = act + ", " + line.strip()
last_character = None
elif re.search('^\S', line):
next_character = line.strip().lower()
maybe_assign_character(next_character)
next_message = ""
elif re.search('^\s*\[\[', line):
maybe_assign_character('the narrator')
send_message('the narrator', line.strip().replace('[[', '').replace(']]', ''), subject)
else:
if next_message:
next_message += "\n"
next_message += line.strip()
if re.search('[\.|\?|!]$', next_message):
send_message(next_character, next_message, subject)
next_message = ''
print "Sent %s messages" % (num_messages_sent,)