浏览代码

Merge branch 'test-echo-bot' of blezz-tech/sharix-open-webservice-running into unstable

共有 4 个文件被更改,包括 153 次插入0 次删除
  1. 30 0
      handlers/EchoBot.py
  2. 3 0
      handlers/config.py
  3. 53 0
      handlers/handlers/open_basic_bot.py
  4. 67 0
      handlers/main.py

+ 30 - 0
handlers/EchoBot.py

@@ -0,0 +1,30 @@
+import logging
+import slixmpp
+import config
+from datetime import datetime
+
+
+class JabberBot(slixmpp.ClientXMPP):
+    """
+    JabberBot
+    """
+
+    def __init__(self, jid, password):
+        slixmpp.ClientXMPP.__init__(self, jid, password)
+
+        # Register plugins
+        self.register_plugin('xep_0030') # Service Discovery
+        self.register_plugin('xep_0004') # Data Forms
+        self.register_plugin('xep_0060') # PubSub
+        self.register_plugin('xep_0199') # XMPP Ping
+
+    def log(self, message):
+        # надо строчку лога сделать более информативной
+        logfile = open("logs/" + datetime.now().strftime('%Y-%m-%d') + "-" + self.user + ".log", "a")
+        logfile.write(message)
+        logfile.close()
+        print(message)
+
+    def stop(self):
+        self.disconnect()
+

+ 3 - 0
handlers/config.py

@@ -30,3 +30,6 @@ JSERVER = "ej.sharix-app.org"
 PASSWORD = "12345"
 PORT = 5222
 API_URL = "https://testopen.sharix-app.org/"
+
+# LOG_DIR = "/var/log/"
+LOG_DIR = "./log/"

+ 53 - 0
handlers/handlers/open_basic_bot.py

@@ -0,0 +1,53 @@
+import hashlib
+from datetime import datetime
+import config
+import jsonAndRequest as jsreq
+from BotClass import JabberBot
+
+botname = "open_basic_bot"
+operating_status = 0
+
+JID = botname + "@" + config.JSERVER
+PORT = config.PORT
+PASSWORD = hashlib.md5((botname + config.PASSWORD).encode('utf-8')).hexdigest()
+
+# таким образом хранится список jid, от которых можно получать сообщения этому боту
+listen_to = [
+    "test_user@ej.sharix-app.org"
+]
+
+# тут хранится список jid, кому бот может отправлять сообщения в результате обработки заявки
+proceed_to = [
+    "another_bot@ej.sharix-app.org"
+]
+
+def message_handler(msg):
+    """обработчик входящих сообщений"""
+
+    print(msg)
+    # text = msg.
+    # if msg['type'] in ('chat', 'normal'):
+    #     msg.reply("Thanks for sending\n%(body)s" % msg).send()
+
+    # text = msg.getBody()  # текст сообщения боту
+    # user = msg.getFrom()  # отправитель сообщения
+    # if (str(user).split("/")[0]) in listen_to:
+    #     if text is not None:
+    #         msg = jsreq.msg_to_text(text)
+    #         bot.bot_log(str(datetime.now()) + " Сообщение получено\n")
+
+def start_handler(bot):
+    """Событие запуска обработчика."""
+
+    print(JID, PASSWORD)
+
+    bot.send_message(JID, f"message send: {datetime.now()}")
+
+    # bot.proceed_status(listen_to[0], {'msg': 'some_info'})
+    # bot.bot_log(botname + " " + str(datetime.now()) + " " + "Сообщение отправлено\n")
+
+# START CUSTOM FUNCTIONS
+
+
+
+# END CUSTOM FUNCTIONS

+ 67 - 0
handlers/main.py

@@ -0,0 +1,67 @@
+import config
+from EchoBot import JabberBot
+import sys
+import logging
+from argparse import ArgumentParser
+import importlib
+import asyncio
+
+if __name__ == '__main__':
+    # Setup the command line arguments.
+    parser = ArgumentParser(description=JabberBot.__doc__)
+
+    # Output verbosity options.
+    parser.add_argument("-q", "--quiet", help="set logging to ERROR",
+                        action="store_const", dest="loglevel",
+                        const=logging.ERROR, default=logging.INFO)
+    parser.add_argument("-d", "--debug", help="set logging to DEBUG",
+                        action="store_const", dest="loglevel",
+                        const=logging.DEBUG, default=logging.INFO)
+
+    # JID and password options.
+    parser.add_argument("-b", "--bot", dest="bot",
+                        help="Bot name")
+
+    args = parser.parse_args()
+
+    # Setup logging.
+    logging.basicConfig(level=args.loglevel,
+                        format='%(levelname)-8s %(message)s')
+
+
+    if args.bot and args.bot in config.BOTLIST:
+        module = importlib.import_module("handlers." + args.bot)
+
+        JID = module.JID
+        PASSWORD = module.PASSWORD
+
+        start_handler = module.start_handler
+        message_handler = module.message_handler        
+
+
+        bot = JabberBot(JID, PASSWORD)
+        
+        # Отправляет информацию о присутствии бота, чтобы показать,
+        # что он онлайн и готов к взаимодействию.
+        bot.send_presence()
+        # bot.get_roster() # TODO: Возможно не нужно
+
+        logging.info(f"Bot {bot.jid} started!")
+
+        bot.add_event_handler("message", message_handler)
+
+        # Connect to the XMPP server and start processing XMPP stanzas.
+        bot.connect()
+        
+        start_handler(bot)
+
+        # TODO: Сделать корректную обработку остановки программы;
+        # Ctrl+C, Ctrl+Z
+        # systemctl stop с последующей отправкой кодов и корректной остановкой программы
+
+        # bot.stop()
+        asyncio.get_event_loop().run_forever()
+    else:
+        print("Select using -n flag for select availible bot from botlist:\n")
+        for botname in config.BOTLIST:
+            print(f"- {botname}")