mirror of
https://github.com/nikdoof/smsbot.git
synced 2025-12-15 22:12:18 +00:00
Add Prometheus metrics
This commit is contained in:
@@ -2,3 +2,4 @@ flask
|
|||||||
waitress
|
waitress
|
||||||
twilio
|
twilio
|
||||||
python-telegram-bot
|
python-telegram-bot
|
||||||
|
prometheus_client
|
||||||
@@ -20,6 +20,7 @@ install_requires =
|
|||||||
waitress
|
waitress
|
||||||
twilio
|
twilio
|
||||||
python-telegram-bot
|
python-telegram-bot
|
||||||
|
prometheus_client
|
||||||
|
|
||||||
[options.entry_points]
|
[options.entry_points]
|
||||||
console_scripts =
|
console_scripts =
|
||||||
|
|||||||
@@ -4,13 +4,16 @@ from setuptools import Command
|
|||||||
from telegram.ext import CommandHandler, Updater
|
from telegram.ext import CommandHandler, Updater
|
||||||
|
|
||||||
from smsbot.utils import get_smsbot_version
|
from smsbot.utils import get_smsbot_version
|
||||||
|
from prometheus_client import make_wsgi_app, Counter, Summary
|
||||||
|
|
||||||
|
REQUEST_TIME = Summary('telegram_request_processing_seconds', 'Time spent processing request')
|
||||||
|
COMMAND_COUNT = Counter('telegram_command_count', 'Total number of commands processed')
|
||||||
|
|
||||||
class TelegramSmsBot(object):
|
class TelegramSmsBot(object):
|
||||||
|
|
||||||
def __init__(self, token, allow_subscribing=False, owner=None, subscribers=None):
|
def __init__(self, telegram_token, allow_subscribing=False, owner=None, subscribers=None):
|
||||||
self.logger = logging.getLogger(self.__class__.__name__)
|
self.logger = logging.getLogger(self.__class__.__name__)
|
||||||
self.bot_token = token
|
self.bot_token = telegram_token
|
||||||
self.subscriber_ids = subscribers or []
|
self.subscriber_ids = subscribers or []
|
||||||
self.set_owner(owner)
|
self.set_owner(owner)
|
||||||
|
|
||||||
@@ -33,6 +36,7 @@ class TelegramSmsBot(object):
|
|||||||
def stop(self):
|
def stop(self):
|
||||||
self.updater.stop()
|
self.updater.stop()
|
||||||
|
|
||||||
|
@REQUEST_TIME.time()
|
||||||
def help_handler(self, update, context):
|
def help_handler(self, update, context):
|
||||||
"""Send a message when the command /help is issued."""
|
"""Send a message when the command /help is issued."""
|
||||||
self.logger.info('/help command received in chat: %s', update.message.chat)
|
self.logger.info('/help command received in chat: %s', update.message.chat)
|
||||||
@@ -42,7 +46,9 @@ class TelegramSmsBot(object):
|
|||||||
commands.extend(['/{0}'.format(x) for x in command.command])
|
commands.extend(['/{0}'.format(x) for x in command.command])
|
||||||
|
|
||||||
update.message.reply_markdown('Smsbot v{0}\n\n{1}'.format(get_smsbot_version(), '\n'.join(commands)))
|
update.message.reply_markdown('Smsbot v{0}\n\n{1}'.format(get_smsbot_version(), '\n'.join(commands)))
|
||||||
|
COMMAND_COUNT.inc()
|
||||||
|
|
||||||
|
@REQUEST_TIME.time()
|
||||||
def subscribe_handler(self, update, context):
|
def subscribe_handler(self, update, context):
|
||||||
self.logger.info('/subscribe command received')
|
self.logger.info('/subscribe command received')
|
||||||
if update.message.chat['id'] not in self.subscriber_ids:
|
if update.message.chat['id'] not in self.subscriber_ids:
|
||||||
@@ -52,7 +58,9 @@ class TelegramSmsBot(object):
|
|||||||
update.message.reply_markdown('You have been subscribed to SMS notifications')
|
update.message.reply_markdown('You have been subscribed to SMS notifications')
|
||||||
else:
|
else:
|
||||||
update.message.reply_markdown('You are already subscribed to SMS notifications')
|
update.message.reply_markdown('You are already subscribed to SMS notifications')
|
||||||
|
COMMAND_COUNT.inc()
|
||||||
|
|
||||||
|
@REQUEST_TIME.time()
|
||||||
def unsubscribe_handler(self, update, context):
|
def unsubscribe_handler(self, update, context):
|
||||||
self.logger.info('/unsubscribe command received')
|
self.logger.info('/unsubscribe command received')
|
||||||
if update.message.chat['id'] in self.subscriber_ids:
|
if update.message.chat['id'] in self.subscriber_ids:
|
||||||
@@ -62,6 +70,7 @@ class TelegramSmsBot(object):
|
|||||||
update.message.reply_markdown('You have been unsubscribed to SMS notifications')
|
update.message.reply_markdown('You have been unsubscribed to SMS notifications')
|
||||||
else:
|
else:
|
||||||
update.message.reply_markdown('You are not subscribed to SMS notifications')
|
update.message.reply_markdown('You are not subscribed to SMS notifications')
|
||||||
|
COMMAND_COUNT.inc()
|
||||||
|
|
||||||
def error_handler(self, update, context):
|
def error_handler(self, update, context):
|
||||||
"""Log Errors caused by Updates."""
|
"""Log Errors caused by Updates."""
|
||||||
|
|||||||
@@ -8,6 +8,13 @@ from waitress import serve
|
|||||||
|
|
||||||
from smsbot.utils import get_smsbot_version
|
from smsbot.utils import get_smsbot_version
|
||||||
|
|
||||||
|
from werkzeug.middleware.dispatcher import DispatcherMiddleware
|
||||||
|
from prometheus_client import make_wsgi_app, Counter, Summary
|
||||||
|
|
||||||
|
REQUEST_TIME = Summary('webhook_request_processing_seconds', 'Time spent processing request')
|
||||||
|
MESSAGE_COUNT = Counter('webhook_message_count', 'Total number of messages processed')
|
||||||
|
CALL_COUNT = Counter('webhook_call_count', 'Total number of calls processed')
|
||||||
|
|
||||||
|
|
||||||
def validate_twilio_request(func):
|
def validate_twilio_request(func):
|
||||||
"""Validates that incoming requests genuinely originated from Twilio"""
|
"""Validates that incoming requests genuinely originated from Twilio"""
|
||||||
@@ -47,15 +54,26 @@ class TwilioWebhookHandler(object):
|
|||||||
self.app.add_url_rule('/message', 'message', self.message, methods=['POST'])
|
self.app.add_url_rule('/message', 'message', self.message, methods=['POST'])
|
||||||
self.app.add_url_rule('/call', 'call', self.call, methods=['POST'])
|
self.app.add_url_rule('/call', 'call', self.call, methods=['POST'])
|
||||||
|
|
||||||
|
# Add prometheus wsgi middleware to route /metrics requests
|
||||||
|
self.app.wsgi_app = DispatcherMiddleware(self.app.wsgi_app, {
|
||||||
|
'/metrics': make_wsgi_app(),
|
||||||
|
})
|
||||||
|
|
||||||
def set_bot(self, bot): # noqa: WPS615
|
def set_bot(self, bot): # noqa: WPS615
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
def index(self):
|
def index(self):
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
@REQUEST_TIME.time()
|
||||||
def health(self):
|
def health(self):
|
||||||
return '<h1>Smsbot v{0}</h1><p><b>Owner</b>: {1}</p><p><b>Subscribers</b>: {2}</p>'.format(get_smsbot_version(), self.bot.owner_id, self.bot.subscriber_ids)
|
return {
|
||||||
|
'version': get_smsbot_version(),
|
||||||
|
'owner': self.bot.owner_id,
|
||||||
|
'subscribers': self.bot.subscriber_ids,
|
||||||
|
}
|
||||||
|
|
||||||
|
@REQUEST_TIME.time()
|
||||||
@validate_twilio_request
|
@validate_twilio_request
|
||||||
def message(self):
|
def message(self):
|
||||||
current_app.logger.info('Received SMS from {From}: {Body}'.format(**request.values.to_dict()))
|
current_app.logger.info('Received SMS from {From}: {Body}'.format(**request.values.to_dict()))
|
||||||
@@ -64,14 +82,17 @@ class TwilioWebhookHandler(object):
|
|||||||
self.bot.send_subscribers(message)
|
self.bot.send_subscribers(message)
|
||||||
|
|
||||||
# Return a blank response
|
# Return a blank response
|
||||||
|
MESSAGE_COUNT.inc()
|
||||||
return '<response></response>'
|
return '<response></response>'
|
||||||
|
|
||||||
|
@REQUEST_TIME.time()
|
||||||
@validate_twilio_request
|
@validate_twilio_request
|
||||||
def call(self):
|
def call(self):
|
||||||
current_app.logger.info('Received Call from {From}'.format(**request.values.to_dict()))
|
current_app.logger.info('Received Call from {From}'.format(**request.values.to_dict()))
|
||||||
self.bot.send_subscribers('Received Call from {From}, rejecting.'.format(**request.values.to_dict()))
|
self.bot.send_subscribers('Received Call from {From}, rejecting.'.format(**request.values.to_dict()))
|
||||||
|
|
||||||
# Always reject calls
|
# Always reject calls
|
||||||
|
CALL_COUNT.inc()
|
||||||
return '<Response><Reject/></Response>'
|
return '<Response><Reject/></Response>'
|
||||||
|
|
||||||
def serve(self, host='0.0.0.0', port=80, debug=False):
|
def serve(self, host='0.0.0.0', port=80, debug=False):
|
||||||
|
|||||||
Reference in New Issue
Block a user