怎么使用Python工厂模式实现封装Webhook群聊机器人

其他教程   发布日期:2023年07月05日   浏览次数:438

本文小编为大家详细介绍“怎么使用Python工厂模式实现封装Webhook群聊机器人”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么使用Python工厂模式实现封装Webhook群聊机器人”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

飞书自定义机器人

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # @Author: Hui
  4. # @Desc: { webhook机器人模块 }
  5. # @Date: 2023/02/19 19:48
  6. import hmac
  7. import base64
  8. import hashlib
  9. import time
  10. from urllib.parse import quote_plus
  11. import requests
  12. from exceptions.base import SendMsgException
  13. class BaseChatBot(object):
  14. """群聊机器人基类"""
  15. def __init__(self, webhook_url: str, secret: str = None):
  16. """
  17. 初始化机器人
  18. Args:
  19. webhook_url: 机器人webhook地址
  20. secret: 安全密钥
  21. """
  22. self.webhook_url = webhook_url
  23. self.secret = secret
  24. def _get_sign(self, timestamp: str, secret: str):
  25. """
  26. 获取签名(NotImplemented)
  27. Args:
  28. timestamp: 签名时使用的时间戳
  29. secret: 签名时使用的密钥
  30. Returns:
  31. """
  32. raise NotImplementedError
  33. def send_msg(self, content: str, timeout=10):
  34. """
  35. 发送消息(NotImplemented)
  36. Args:
  37. content: 消息内容
  38. timeout: 发送消息请求超时时间 默认10秒
  39. Returns:
  40. """
  41. raise NotImplementedError
  42. class FeiShuChatBot(BaseChatBot):
  43. """飞书机器人"""
  44. def _get_sign(self, timestamp: str, secret: str) -> str:
  45. """
  46. 获取签名
  47. 把 timestamp + "
  48. " + 密钥 当做签名字符串,使用 HmacSHA256 算法计算签名,再进行 Base64 编码
  49. Args:
  50. timestamp: 签名时使用的时间戳
  51. secret: 签名时使用的密钥
  52. Returns: sign
  53. """
  54. string_to_sign = '{}
  55. {}'.format(timestamp, secret)
  56. hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
  57. # 对结果进行base64处理
  58. sign = base64.b64encode(hmac_code).decode('utf-8')
  59. return sign
  60. def send_msg(self, content: str, timeout=10):
  61. """
  62. 发送消息
  63. Args:
  64. content: 消息内容
  65. timeout: 发送消息请求超时时间 默认10秒
  66. Raises:
  67. SendMsgException
  68. Returns:
  69. """
  70. msg_data = {
  71. "msg_type": "text",
  72. "content": {
  73. "text": f"{content}"
  74. }
  75. }
  76. if self.secret:
  77. timestamp = str(round(time.time()))
  78. sign = self._get_sign(timestamp=timestamp, secret=self.secret)
  79. msg_data["timestamp"] = timestamp
  80. msg_data["sign"] = sign
  81. try:
  82. resp = requests.post(url=self.webhook_url, json=msg_data, timeout=timeout)
  83. resp_info = resp.json()
  84. if resp_info.get("code") != 0:
  85. raise SendMsgException(f"FeiShuChatBot send msg error, {resp_info}")
  86. except Exception as e:
  87. raise SendMsgException(f"FeiShuChatBot send msg error {e}") from e

钉钉自定义机器人

  1. class DingTalkChatBot(BaseChatBot):
  2. """钉钉机器人"""
  3. def _get_sign(self, timestamp: str, secret: str):
  4. """
  5. 获取签名
  6. 把 timestamp + "
  7. " + 密钥当做签名字符串,使用 HmacSHA256 算法计算签名,
  8. 然后进行 Base64 encode,最后再把签名参数再进行 urlEncode,得到最终的签名(需要使用UTF-8字符集)
  9. Args:
  10. timestamp: 签名时使用的时间戳
  11. secret: 签名时使用的密钥
  12. Returns: sign
  13. """
  14. secret_enc = secret.encode('utf-8')
  15. string_to_sign = '{}
  16. {}'.format(timestamp, secret)
  17. string_to_sign_enc = string_to_sign.encode('utf-8')
  18. hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
  19. sign = quote_plus(base64.b64encode(hmac_code))
  20. return sign
  21. def send_msg(self, content: str, timeout=10):
  22. """
  23. 发送消息
  24. Args:
  25. content: 消息内容
  26. timeout: 发送消息请求超时时间 默认10秒
  27. Raises:
  28. SendMsgException
  29. Returns:
  30. """
  31. timestamp = str(round(time.time() * 1000))
  32. sign = self._get_sign(timestamp=timestamp, secret=self.secret)
  33. params = {
  34. "timestamp": timestamp,
  35. "sign": sign
  36. }
  37. msg_data = {
  38. "msgtype": "text",
  39. "text": {
  40. "content": content
  41. }
  42. }
  43. try:
  44. resp = requests.post(url=self.webhook_url, json=msg_data, params=params, timeout=timeout)
  45. resp_info = resp.json()
  46. if resp_info.get("errcode") != 0:
  47. raise SendMsgException(f"DingTalkChatBot send msg error, {resp_info}")
  48. except Exception as e:
  49. raise SendMsgException(f"DingTalkChatBot send msg error {e}") from e

使用的时候

  1. feishu = FeiShuChatBot(webhook_url="xxx", secret="xxxx")
  2. feishu.send_msg("test msg")
  3. dingtalk = DingTalkChatBot(webhook_url="xxx", secret="xxxx")
  4. feishu.send_msg("test msg")

但这样使用有点不好的一点就是如果我突然从钉钉换成飞书或者企微,业务中的所有使用的代码就要全部替换。但一般也不会随便换平台,我这里就是想引出工厂模式。

工厂模式封装

工厂模式是一种常见的设计模式,它可以帮助我们创建对象,而无需显式地指定其具体类型。在这种模式下,我们通过使用一个工厂来创建对象,并将对象的创建和使用分离开来,从而提高了代码的可维护性和可扩展性.

对于Webhook群聊机器人,我们可以将其实现为一个工厂类,该工厂类负责创建不同类型的机器人对象。我们可以通过定义一个机器人接口或抽象类,来规范所有机器人的通用方法和属性。然后,我们可以根据需要创建具体的机器人类,并实现其特定的方法和属性。代码如下

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # @Author: Hui
  4. # @Desc: { 机器人工厂模块 }
  5. # @Date: 2023/02/19 20:03
  6. from typing import Dict, Type
  7. from chatbot import DingTalkChatBot, FeiShuChatBot, BaseChatBot
  8. class ChatBotType:
  9. """群聊机器人类型"""
  10. FEISHU_CHATBOT = "feishu"
  11. DINGTALK_CHATBOT = "dingtalk"
  12. class ChatBotFactory(object):
  13. """
  14. 消息机器人工厂
  15. 支持 飞书、钉钉、自定义机器人消息发送
  16. """
  17. # 群聊机器人处理类映射
  18. CHATBOT_HANDLER_CLS_MAPPING: Dict[str, Type[BaseChatBot]] = {
  19. ChatBotType.FEISHU_CHATBOT: FeiShuChatBot,
  20. ChatBotType.DINGTALK_CHATBOT: DingTalkChatBot,
  21. }
  22. def __init__(self, chatbot_type: str):
  23. if chatbot_type not in self.CHATBOT_HANDLER_CLS_MAPPING:
  24. raise ValueError(f"不支持 {chatbot_type} 类型的机器人")
  25. self.chatbot_type = chatbot_type
  26. def build(self, webhook_url: str, secret: str = None) -> BaseChatBot:
  27. """
  28. 构造具体的机器人处理类
  29. Args:
  30. webhook_url: 机器人webhook地址
  31. secret: 机器人密钥
  32. Returns: 根据 robot_type 返回对应的机器人处理类
  33. """
  34. chatbot_handle_cls = self.CHATBOT_HANDLER_CLS_MAPPING.get(self.chatbot_type)
  35. return chatbot_handle_cls(webhook_url=webhook_url, secret=secret)

通过字典的方式把机器人类型(平台)与具体处理类关联起来,这样构造的时候就不用写 if else

使用的时候直接用工厂创建具体的实例出来就行

  1. def main():
  2. feishu_webhook = "xxx"
  3. feishu_webhook_secret = "xxx"
  4. dingtalk_webhook = "xxx"
  5. dingtalk_webhook_secret = "xxx"
  6. feishu_chatbot = ChatBotFactory(chatbot_type=ChatBotType.FEISHU_CHATBOT).build(
  7. webhook_url=feishu_webhook,
  8. secret=feishu_webhook_secret
  9. )
  10. content = "飞书自定义机器人使用指南:
  11. https://open.feishu.cn/document/ukTMukTMukTM/ucTM5YjL3ETO24yNxkjN"
  12. feishu_chatbot.send_msg(content)
  13. dingtalk_chatbot = ChatBotFactory(chatbot_type=ChatBotType.DINGTALK_CHATBOT).build(
  14. webhook_url=dingtalk_webhook,
  15. secret=dingtalk_webhook_secret
  16. )
  17. content = "钉钉自定义机器人使用指南:
  18. https://open.dingtalk.com/document/robots/custom-robot-access"
  19. dingtalk_chatbot.send_msg(content)
  20. if __name__ == '__main__':
  21. main()

新增企微机器人

需要切换的时候直接替换掉 chatbot_type 就可以。把chatbot_type、webhook_url、secret放到配置文件即可在不改动代码的情况直接切换。工厂模式也方便扩展,例如再新增一个企微等。

  1. class WeComChatbot(BaseChatBot):
  2. """企业微信机器人"""
  3. def _get_sign(self, timestamp: str, secret: str):
  4. """企业微信暂不支持签名加密"""
  5. pass
  6. def send_msg(self, content: str, timeout=10):
  7. """
  8. 发送消息
  9. Args:
  10. content: 消息内容
  11. timeout: 发送消息请求超时时间 默认10秒
  12. Raises:
  13. SendMsgException
  14. Returns:
  15. """
  16. msg_data = {
  17. "msgtype": "text",
  18. "text": {
  19. "content": content
  20. }
  21. }
  22. try:
  23. resp = requests.post(self.webhook_url, json=msg_data)
  24. resp_info = resp.json()
  25. if resp.status_code != 200:
  26. raise ValueError(f"WeComChatbot send message error, {resp_info}")
  27. except Exception as e:
  28. raise SendMsgException(e) from e

工厂类中只要新增一个企微群聊机器人处理类的映射就可以

  1. from typing import Dict, Type
  2. from chatbot import DingTalkChatBot, FeiShuChatBot, WeComChatbot, BaseChatBot
  3. class ChatBotType:
  4. """群聊机器人类型"""
  5. FEISHU_CHATBOT = "feishu"
  6. DINGTALK_CHATBOT = "dingtalk"
  7. WECOM_CHATBOT = "wecom"
  8. class ChatBotFactory(object):
  9. """
  10. 消息机器人工厂
  11. 支持 飞书、钉钉、企微自定义机器人消息发送
  12. """
  13. # 群聊机器人处理类映射
  14. CHATBOT_HANDLER_CLS_MAPPING: Dict[str, Type[BaseChatBot]] = {
  15. ChatBotType.FEISHU_CHATBOT: FeiShuChatBot,
  16. ChatBotType.DINGTALK_CHATBOT: DingTalkChatBot,
  17. ChatBotType.WECOM_CHATBOT: WeComChatbot
  18. }
  19. def __init__(self, chatbot_type: str):
  20. if chatbot_type not in self.CHATBOT_HANDLER_CLS_MAPPING:
  21. raise ValueError(f"不支持 {chatbot_type} 类型的机器人")
  22. self.chatbot_type = chatbot_type
  23. def build(self, webhook_url: str, secret: str = None) -> BaseChatBot:
  24. """
  25. 构造具体的机器人处理类
  26. Args:
  27. webhook_url: 机器人webhook地址
  28. secret: 机器人密钥
  29. Returns: 根据 robot_type 返回对应的机器人处理类
  30. """
  31. chatbot_handle_cls = self.CHATBOT_HANDLER_CLS_MAPPING.get(self.chatbot_type)
  32. return chatbot_handle_cls(webhook_url=webhook_url, secret=secret)

看看读取配置文件的话该如何使用

  1. # settings.py
  2. # chatbot_type = "feishu"
  3. # chatbot_type = "dingtalk"
  4. chatbot_type = "wecom"
  5. webhook_url = "xxx"
  6. secret = ""
  7. # xxx_logic.py
  8. import settings
  9. chatbot = ChatBotFactory(chatbot_type=settings.chatbot_type).build(
  10. webhook_url=settings.webhook_url,
  11. secret=settings.secret
  12. )
  13. chatbot.send_msg("test msg")

以上就是怎么使用Python工厂模式实现封装Webhook群聊机器人的详细内容,更多关于怎么使用Python工厂模式实现封装Webhook群聊机器人的资料请关注九品源码其它相关文章!