39传奇素材网 发表于 2025-7-20 16:25:55

如何通过脚本实现传奇系统随机给验证码

要通过脚本实现传奇系统随机给验证码,主要需要完成以下几个核心功能:生成随机验证码、存储验证码与用户的关联、发送验证码给用户、验证用户输入的验证码。以下是一个完整的解决方案:
验证码生成与验证系统
下面是一个完整的 Python 脚本,实现了传奇游戏中的验证码功能,支持邮箱和短信发送方式:
import random
import string
import time
import os
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import logging
import json

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='captcha.log'
)
logger = logging.getLogger('LegendCaptcha')

class CaptchaConfig:
    """验证码配置类"""
    def __init__(self, config_file="captcha_config.json"):
      self.config_file = config_file
      self.config = self._load_config()

    def _load_config(self):
      """加载配置文件"""
      if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                  return json.load(f)
            except Exception as e:
                logger.error(f"加载配置文件失败: {e}")
      return self._create_default_config()

    def _create_default_config(self):
      """创建默认配置"""
      default_config = {
            "captcha_length": 6,
            "use_numbers": True,
            "use_letters": True,
            "case_sensitive": False,
            "expiration_time": 300,# 5分钟
            "storage_type": "memory",# memory或file
            "storage_file": "captchas.json",
            "email_config": {
                "smtp_server": "smtp.example.com",
                "smtp_port": 587,
                "sender_email": "your_email@example.com",
                "sender_password": "your_password",
                "email_subject": "【传奇系统】验证码"
            },
            "sms_config": {
                "api_key": "your_api_key",
                "api_secret": "your_api_secret",
                "sms_template": "您的验证码是:{code},有效期5分钟。"
            }
      }
      self.save_config(default_config)
      return default_config

    def save_config(self, config):
      """保存配置文件"""
      try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=4, ensure_ascii=False)
      except Exception as e:
            logger.error(f"保存配置文件失败: {e}")

class CaptchaStorage:
    """验证码存储类"""
    def __init__(self, config):
      self.config = config
      self.storage_type = config["storage_type"]
      self.storage_file = config["storage_file"]
      self.captchas = {}
      if self.storage_type == "file" and os.path.exists(self.storage_file):
            self._load_from_file()

    def _load_from_file(self):
      """从文件加载验证码数据"""
      try:
            with open(self.storage_file, 'r', encoding='utf-8') as f:
                self.captchas = json.load(f)
      except Exception as e:
            logger.error(f"从文件加载验证码失败: {e}")
            self.captchas = {}

    def save_to_file(self):
      """保存验证码数据到文件"""
      if self.storage_type == "file":
            try:
                with open(self.storage_file, 'w', encoding='utf-8') as f:
                  json.dump(self.captchas, f, indent=4, ensure_ascii=False)
            except Exception as e:
                logger.error(f"保存验证码到文件失败: {e}")

    def add_captcha(self, user_id, captcha):
      """添加验证码"""
      timestamp = time.time()
      self.captchas = {
            "code": captcha,
            "timestamp": timestamp
      }
      self.save_to_file()

    def get_captcha(self, user_id):
      """获取验证码"""
      if user_id in self.captchas:
            # 检查是否过期
            if time.time() - self.captchas["timestamp"] <= self.config["expiration_time"]:
                return self.captchas["code"]
            else:
                # 已过期,删除
                self.delete_captcha(user_id)
      return None

    def delete_captcha(self, user_id):
      """删除验证码"""
      if user_id in self.captchas:
            del self.captchas
            self.save_to_file()

class CaptchaGenerator:
    """验证码生成器"""
    def __init__(self, config):
      self.config = config

    def generate(self):
      """生成随机验证码"""
      characters = ''
      if self.config["use_numbers"]:
            characters += string.digits
      if self.config["use_letters"]:
            if self.config["case_sensitive"]:
                characters += string.ascii_letters
            else:
                characters += string.ascii_uppercase

      if not characters:
            raise ValueError("至少需要启用数字或字母中的一种")

      return ''.join(random.choice(characters) for _ in range(self.config["captcha_length"]))

class NotificationSender:
    """通知发送器"""
    def __init__(self, config):
      self.config = config

    def send_email(self, email, captcha):
      """发送邮件验证码"""
      email_config = self.config["email_config"]
      message = MIMEText(
            f"您的传奇系统验证码是:{captcha}\n验证码有效期为5分钟,请尽快完成验证。",
            'plain', 'utf-8'
      )
      message['From'] = Header(email_config["sender_email"], 'utf-8')
      message['To'] = Header(email, 'utf-8')
      message['Subject'] = Header(email_config["email_subject"], 'utf-8')

      try:
            # 创建SMTP对象并连接服务器
            smtp_obj = smtplib.SMTP(email_config["smtp_server"], email_config["smtp_port"])
            # 开启安全连接
            smtp_obj.starttls()
            # 登录发件人邮箱
            smtp_obj.login(email_config["sender_email"], email_config["sender_password"])
            # 发送邮件
            smtp_obj.sendmail(email_config["sender_email"], , message.as_string())
            smtp_obj.quit()
            logger.info(f"已发送邮件验证码到: {email}")
            return True
      except Exception as e:
            logger.error(f"发送邮件失败: {e}")
            return False

    def send_sms(self, phone, captcha):
      """发送短信验证码(示例,需集成实际短信服务)"""
      sms_config = self.config["sms_config"]
      # 这里需要集成实际的短信服务API
      # 示例代码仅作演示
      try:
            # 实际应用中替换为真实的短信API调用
            logger.info(f"模拟发送短信验证码到: {phone},验证码: {captcha}")
            return True
      except Exception as e:
            logger.error(f"发送短信失败: {e}")
            return False

class LegendCaptchaSystem:
    """传奇系统验证码管理"""
    def __init__(self):
      self.config = CaptchaConfig()
      self.generator = CaptchaGenerator(self.config.config)
      self.storage = CaptchaStorage(self.config.config)
      self.sender = NotificationSender(self.config.config)

    def request_captcha(self, user_id, contact_type, contact):
      """请求验证码"""
      # 生成验证码
      captcha = self.generator.generate()

      # 存储验证码
      self.storage.add_captcha(user_id, captcha)

      # 发送验证码
      if contact_type == "email":
            return self.sender.send_email(contact, captcha)
      elif contact_type == "sms":
            return self.sender.send_sms(contact, captcha)
      else:
            logger.error(f"不支持的联系方式类型: {contact_type}")
            return False

    def verify_captcha(self, user_id, user_input):
      """验证验证码"""
      stored_captcha = self.storage.get_captcha(user_id)
      if not stored_captcha:
            return False

      # 检查验证码是否匹配(考虑大小写敏感设置)
      if self.config.config["case_sensitive"]:
            is_valid = user_input == stored_captcha
      else:
            is_valid = user_input.upper() == stored_captcha.upper()

      # 如果验证成功,删除验证码
      if is_valid:
            self.storage.delete_captcha(user_id)

      return is_valid

# 使用示例
if __name__ == "__main__":
    # 创建验证码系统实例
    captcha_system = LegendCaptchaSystem()

    # 示例:用户注册时请求验证码
    user_id = "player_12345"
    email = "player@example.com"

    # 请求验证码
    if captcha_system.request_captcha(user_id, "email", email):
      print(f"验证码已发送至 {email},请注意查收")

      # 模拟用户输入验证码
      user_input = input("请输入收到的验证码: ")

      # 验证验证码
      if captcha_system.verify_captcha(user_id, user_input):
            print("验证成功!")
      else:
            print("验证失败!")
    else:
      print("发送验证码失败,请稍后再试")   

页: [1]
查看完整版本: 如何通过脚本实现传奇系统随机给验证码