From aa526d6d1b34113c2fdc6a97d6f46bc41b08713b Mon Sep 17 00:00:00 2001 From: jantuomi Date: Mon, 18 Jul 2016 09:22:59 +0300 Subject: Create shoutbox API communicator class --- botmanager.py | 36 ++++++++------------------------ mock_http_server.py | 51 ---------------------------------------------- mockshoutbox.py | 51 ++++++++++++++++++++++++++++++++++++++++++++++ shoutboxapicommunicator.py | 31 ++++++++++++++++++++++++++++ 4 files changed, 90 insertions(+), 79 deletions(-) delete mode 100644 mock_http_server.py create mode 100644 mockshoutbox.py create mode 100644 shoutboxapicommunicator.py diff --git a/botmanager.py b/botmanager.py index dc91a3b..2002b7e 100644 --- a/botmanager.py +++ b/botmanager.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + import json import random import sys @@ -6,6 +8,7 @@ import telepot import traceback import time import logging +import shoutboxapicommunicator class BotManager(object): @@ -14,6 +17,7 @@ class BotManager(object): def __init__(self, token): self.token = token + self.api_comm = shoutboxapicommunicator.Communicator() # Attempt to create a bot with telepot try: @@ -26,8 +30,6 @@ class BotManager(object): sys.exit(1) def start(self): - self.started = True - # Try fetching bot information from Telegram to check connection try: logging.info("Bot info: {}".format(self.bot.getMe())) @@ -36,37 +38,15 @@ class BotManager(object): sys.exit(1) self.bot.message_loop(self.handle) + logging.info("Listening for messages...") while True: - self.get_messages_from_shoutbox() + self.api_comm.fetch(self.shoutbox_api_url) time.sleep(10) - def get_messages_from_shoutbox(self): - try: - r = requests.get(self.shoutbox_api_url) - logging.info("Response from API OK.") - - except: - logging.warning("Failed to get response from API!") - traceback.print_exc(2) - return - - content = json.loads(r.text) - logging.info("Messages:") - for msg in content: - logging.info("{}: {}".format(msg["user"], msg["text"])) - def default_action(self, chat_id): self.bot.sendMessage(chat_id, "Radio palaa keväällä 2017!") - def send_to_shoutbox(self, chat_id, text, user): - data = {"message":text, "user":user} - try: - requests.post(self.shoutbox_api_url, data) - logging.info("Sent message from {} to shoutbox.".format(user)) - except: - logging.warning("Failed to send message from {} to shoutbox API!".format(user)) - # Placeholder action for testing commands def now_playing(self, chat_id): @@ -86,9 +66,9 @@ class BotManager(object): self.not_supported(chat_id) elif "/stop" in t: self.not_supported(chat_id) - else: + elif chat_id == self.telegram_chat_id: user_name = msg["from"]["first_name"] - self.send_to_shoutbox(chat_id, t, user_name) + self.api_comm.send(self.shoutbox_api_url, t, user_name) # Start parsing the incoming message if it is a text message def handle(self, msg): diff --git a/mock_http_server.py b/mock_http_server.py deleted file mode 100644 index 2399ba5..0000000 --- a/mock_http_server.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python - -import sys -import http.server -from http.server import SimpleHTTPRequestHandler - -''' -Mock HTTP server to test -shoutbox api requests. - -Copyright: linuxjournal.com -Source: http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python -''' - -class MyHandler(SimpleHTTPRequestHandler): - def do_HEAD(self): - self.send_response(200) - self.send_header("Content-type", "application/json") - self.end_headers() - - def do_GET(self): - """Respond to a GET request.""" - self.send_response(200) - self.send_header("Content-type", "application/json") - self.end_headers() - - body = """[ - { - \"text\":\"test message\", - \"user\":\"test user\" - } - ]""" - - self.wfile.write(body.encode()) - -HandlerClass = MyHandler -ServerClass = http.server.HTTPServer -Protocol = "HTTP/1.0" - -if sys.argv[1:]: - port = int(sys.argv[1]) -else: - port = 8000 -server_address = ('127.0.0.1', port) - -HandlerClass.protocol_version = Protocol -httpd = ServerClass(server_address, HandlerClass) - -sa = httpd.socket.getsockname() -print("Serving HTTP on", sa[0], "port", sa[1], "...") -httpd.serve_forever() diff --git a/mockshoutbox.py b/mockshoutbox.py new file mode 100644 index 0000000..2399ba5 --- /dev/null +++ b/mockshoutbox.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python + +import sys +import http.server +from http.server import SimpleHTTPRequestHandler + +''' +Mock HTTP server to test +shoutbox api requests. + +Copyright: linuxjournal.com +Source: http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python +''' + +class MyHandler(SimpleHTTPRequestHandler): + def do_HEAD(self): + self.send_response(200) + self.send_header("Content-type", "application/json") + self.end_headers() + + def do_GET(self): + """Respond to a GET request.""" + self.send_response(200) + self.send_header("Content-type", "application/json") + self.end_headers() + + body = """[ + { + \"text\":\"test message\", + \"user\":\"test user\" + } + ]""" + + self.wfile.write(body.encode()) + +HandlerClass = MyHandler +ServerClass = http.server.HTTPServer +Protocol = "HTTP/1.0" + +if sys.argv[1:]: + port = int(sys.argv[1]) +else: + port = 8000 +server_address = ('127.0.0.1', port) + +HandlerClass.protocol_version = Protocol +httpd = ServerClass(server_address, HandlerClass) + +sa = httpd.socket.getsockname() +print("Serving HTTP on", sa[0], "port", sa[1], "...") +httpd.serve_forever() diff --git a/shoutboxapicommunicator.py b/shoutboxapicommunicator.py new file mode 100644 index 0000000..57f6bc7 --- /dev/null +++ b/shoutboxapicommunicator.py @@ -0,0 +1,31 @@ +import json + +import requests +import logging + + +class Communicator(object): + + def fetch(self, url): + try: + r = requests.get(url) + logging.info("Response from API OK.") + + except: + logging.warning("Failed to get response from API!") + return + + content = json.loads(r.text) + logging.info("Messages:") + for msg in content: + logging.info("{}: {}".format(msg["user"], msg["text"])) + + return content + + def send(self, url, text, user): + data = {"text": text, "user": user} + try: + requests.post(url, data) + logging.info("Sent message from {} to shoutbox.".format(user)) + except: + logging.warning("Failed to send message from {} to shoutbox API!".format(user)) \ No newline at end of file -- cgit v1.3