python-zulip-api/bots/feedback-bot
Luke Faraone 518da346e3 Enable absolute imports for non-third-party code where it was omitted previously
(imported from commit 34856ac32c6b94b614273a6fe46c87a314058d9b)
2013-10-25 14:13:30 -04:00

93 lines
2.8 KiB
Python
Executable file

#!/usr/bin/env python
from __future__ import absolute_import
import sys
from os import path
import logging
sys.path.append(path.join(path.dirname(__file__), '../api'))
import zulip
sys.path.append(path.join(path.dirname(__file__), '../zproject'))
import local_settings
class StreamLogger(object):
"""
Give a file-like interface to a logger instance.
"""
def __init__(self, logger, log_level=logging.INFO):
self.logger = logger
self.log_level = log_level
self.buffer = ""
def write(self, message):
self.buffer += message
if message[-1] == "\n":
self.logger.log(self.log_level, self.buffer.rstrip())
self.buffer = ""
logging.basicConfig(filename="/var/log/zulip/feedback-bot.log",
level=logging.DEBUG, format="%(asctime)s %(levelname)s\t%(message)s")
# The API prints to stdout, so capture and format those messages as well.
stdout_logger = StreamLogger(logging.getLogger("stdout"), logging.INFO)
sys.stdout = stdout_logger
stderr_logger = StreamLogger(logging.getLogger("stderr"), logging.ERROR)
sys.stderr = stderr_logger
prod_client = zulip.Client(
email="feedback@zulip.com",
api_key=local_settings.FEEDBACK_BOT_KEY,
verbose=True,
site="https://api.zulip.com")
staging_client = zulip.Client(
email="feedback@zulip.com",
api_key=local_settings.FEEDBACK_BOT_KEY,
verbose=True,
site="https://staging.zulip.com/api")
def get_ticket_number():
fn = '/var/tmp/.feedback-bot-ticket-number'
try:
ticket_number = int(open(fn).read()) + 1
except:
ticket_number = 1
open(fn, 'w').write('%d' % ticket_number)
return ticket_number
def forward_message(message):
if message["type"] != "private" or len(message["display_recipient"]) != 2:
return
if "sender_domain" in message:
subject = "feedback: %s (%s)" % (message["sender_email"], message["sender_domain"])
else:
subject = "feedback from %s" % message["sender_email"],
if len(subject) > 60:
subject = subject[:57].rstrip() + "..."
ticket_number = get_ticket_number()
content = '@support, Please ack this new request.'
content += '\n~~~'
content += '\nticket Z%03d' % (ticket_number,)
content += '\nsender: %s' % (message['sender_full_name'],)
content += '\nemail: %s' % (message['sender_email'],)
if 'sender_domain' in message:
content += '\nrealm: %s' % (message['sender_domain'],)
content += '\n~~~'
content += '\n\n'
content += message['content']
forwarded_message = {
"type": "stream",
"to": "support",
"subject": subject,
"content": content,
}
staging_client.send_message(forwarded_message)
logging.info("Forwarded feedback from %s" % (message["sender_email"],))
prod_client.call_on_each_message(forward_message)