Queer European MD passionate about IT
Prechádzať zdrojové kódy

Chosen inline result handler written

Davte 5 rokov pred
rodič
commit
12bc2eba44
1 zmenil súbory, kde vykonal 27 pridanie a 4 odobranie
  1. 27 4
      davtelepot/bot.py

+ 27 - 4
davtelepot/bot.py

@@ -423,10 +423,33 @@ class Bot(TelegramBot, ObjectWithDatabase):
 
     async def chosen_inline_result_handler(self, update):
         """Handle Telegram `chosen_inline_result` update."""
-        logging.info(
-            f"The following update was received: {update}\n"
-            "However, this chosen_inline_result handler does nothing yet."
-        )
+        user_id = update['from']['id']
+        if user_id in self.chosen_inline_result_handlers:
+            result_id = update['result_id']
+            handlers = self.chosen_inline_result_handlers[user_id]
+            if result_id in handlers:
+                func = handlers[result_id]
+                if asyncio.iscoroutinefunction(func):
+                    await func(update)
+                else:
+                    func(update)
+        return
+
+    def set_inline_result_handler(self, user_id, result_id, func):
+        """Associate a func to a result_id.
+
+        When an inline result is chosen having that id, function will
+            be passed the update as argument.
+        """
+        if type(user_id) is dict:
+            user_id = user_id['from']['id']
+        assert type(user_id) is int, "user_id must be int!"
+        # Query result ids are parsed as str by telegram
+        result_id = str(result_id)
+        assert callable(func), "func must be a callable"
+        if user_id not in self.chosen_inline_result_handlers:
+            self.chosen_inline_result_handlers[user_id] = {}
+        self.chosen_inline_result_handlers[user_id][result_id] = func
         return
 
     async def callback_query_handler(self, update):