blezz-tech 1 ماه پیش
والد
کامیت
6965c6b220
3فایلهای تغییر یافته به همراه78 افزوده شده و 33 حذف شده
  1. 6 9
      handlers/EchoBot.py
  2. 51 0
      handlers/handlers/open_basic_bot.py
  3. 21 24
      handlers/main.py

+ 6 - 9
handlers/EchoBot.py

@@ -12,21 +12,18 @@ class JabberBot(slixmpp.ClientXMPP):
     def __init__(self, jid, password):
         slixmpp.ClientXMPP.__init__(self, jid, password)
 
+    def run(self):
+        # TODO: Нужно ли
+        self.send_presence()
+        self.get_roster()
+
         # 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 register_handler(self, name, handler):
-        self.add_event_handler(name, handler)
-
-    async def start(self, event):
-        # TODO: Нужно ли
-        # self.send_presence()
-        # await self.get_roster()
-
-        logging.info("Bot started!")
+        logging.info(f"Bot {self.jid} started!")
 
         # Connect to the XMPP server and start processing XMPP stanzas.
         self.connect()

+ 51 - 0
handlers/handlers/open_basic_bot.py

@@ -0,0 +1,51 @@
+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):
+    """Событие запуска обработчика."""
+    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

+ 21 - 24
handlers/main.py

@@ -1,19 +1,8 @@
-import hashlib
-from datetime import datetime
 import config
-import jsonAndRequest as jsreq
 from EchoBot import JabberBot
-
+import sys
 import logging
-from getpass import getpass
 from argparse import ArgumentParser
-import asyncio
-
-botname = "open_basic_bot"
-operating_status = 0
-
-JID = botname + "@" + config.JSERVER
-PASSWORD = hashlib.md5((botname + config.PASSWORD).encode('utf-8')).hexdigest()
 
 if __name__ == '__main__':
     # Setup the command line arguments.
@@ -28,8 +17,8 @@ if __name__ == '__main__':
                         const=logging.DEBUG, default=logging.INFO)
 
     # JID and password options.
-    # parser.add_argument("-b", "--bot", dest="bot",
-    #                     help="Bot name")
+    parser.add_argument("-b", "--bot", dest="bot",
+                        help="Bot name")
 
     args = parser.parse_args()
 
@@ -37,17 +26,25 @@ if __name__ == '__main__':
     logging.basicConfig(level=args.loglevel,
                         format='%(levelname)-8s %(message)s')
 
-    # if args.jid is None:
-    #     args.jid = input("Username: ")
-    # if args.password is None:
-    #     args.password = getpass("Password: ")
 
-    # Setup the EchoBot and register plugins. Note that while plugins may
-    # have interdependencies, the order in which you register them does
-    # not matter.
+    if args.bot and args.bot in config.BOTLIST:
+        module = __import__("handlers." + args.bot)
+
+        print(module.JID)
+
+        JID = module.JID
+        PASSWORD = module.PASSWORD
 
-    xmpp = JabberBot(JID, PASSWORD)
+        fn_start_handler = module.start_handler
+        fn_message = module.message        
 
-    xmpp.send_message(JID, f"message send: {datetime.now()}")
 
-    asyncio.get_event_loop().run_forever()
+        bot = JabberBot(JID, PASSWORD)
+        bot.add_event_handler("message", fn_message)
+        bot.run()
+        fn_start_handler(bot)
+        bot.stop()
+    else:
+        print("Select using -n flag for select availible bot from botlist:\n")
+        for botname in config.BOTLIST:
+            print(f"- {botname}")