from matrix_bot_api.mregex_handler import MRegexHandler from woocommerce import API from base64 import b64encode import os import json import datetime as dt MESSAGE_DIR = os.path.join(os.path.dirname(__file__), 'messages') DATA_DIR = os.path.join(os.path.dirname(__file__),'../../data/woocommerce') CONFIG_LOCATION = os.path.join(os.path.dirname(__file__), 'config.json') DATA_LOCATION = DATA_DIR + '/id.json' HELP_LOCATION = MESSAGE_DIR + '/help' MESSAGES_LOCATION = MESSAGE_DIR + '/messages.dutch.json' class Plugin: """ This is an example plugin with only a single callback. When a user says "Hello bot" in a room in which te bot is present, the user replies with "Hello !". """ def __init__(self, bot): # Load the configuration with open(CONFIG_LOCATION) as json_data: self.config = json.load(json_data) # Load ID of coupon with open(DATA_LOCATION) as json_data: self.coupon_id = json.load(json_data) # Load all messages for this plugin with open(MESSAGES_LOCATION) as json_data: self.messages = json.load(json_data) # Define sensitivity self.handler = [] self.handler.append(MRegexHandler("Peter coupon", self.grab_coupon_callback)) # initialize WooCommerce connection self.wcapi = API( url=self.config['rest_api']['shop_url'], consumer_key=self.config['rest_api']['consumer_key'], consumer_secret=self.config['rest_api']['consumer_secret'], wp_api=self.config['rest_api']['wp_api'], version=self.config['rest_api']['version'], query_string_auth=True ) # Save parent bot self.bot = bot def grab_coupon_callback(self, room, event): coupon_json = self.wcapi.get(f"coupons/{self.coupon_id}").json() datetime_now = dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") if coupon_json['expiry_date'] < datetime_now: # Refresh coupon # Create random token and determine max validity vld_days = self.config['coupon']['max_days'] token = b64encode(os.urandom(8)).decode('utf-8').lower()[0:-1] expires_dat = (dt.datetime.now() + dt.timedelta(days = vld_days)).strftime( "%Y-%m-%dT%H:%M:%S") data = { "code": token, "amount": self.config['coupon']['percentage'], "expiry_date": expires_dat, } self.wcapi.put(f"coupons/{self.coupon_id}", data) room.send_html(self.messages['coupon_message'].format( coupon_json["amount"].split('.')[0], token)) else: room.send_html(self.messages['coupon_message'].format( coupon_json["amount"].split('.')[0], coupon_json["code"])) def help(self): return open(HELP_LOCATION, mode="r").read() def setup(): """This function initializes a coupon with a given percentage""" # Load the configuration with open(CONFIG_LOCATION) as json_data: config = json.load(json_data) # Create random token and determine max validity vld_days = config['coupon']['max_days'] token = b64encode(os.urandom(8)).decode('utf-8').lower()[0:-1] expires_dat = (dt.datetime.now() + dt.timedelta(days = vld_days)).strftime( "%Y-%m-%dT%H:%M:%S") data = { "code": token, "discount_type": "percent", "amount": config['coupon']['percentage'], "individual_use": True, "exclude_sale_items": True, "expiry_date": expires_dat, } wcapi = API( url=config['rest_api']['shop_url'], consumer_key=config['rest_api']['consumer_key'], consumer_secret=config['rest_api']['consumer_secret'], wp_api=config['rest_api']['wp_api'], version=config['rest_api']['version'], query_string_auth=True ) # Send to shop ret = wcapi.post("coupons", data) # Create data directory os.mkdir(DATA_DIR) # Write to JSON file to save ID with open(DATA_LOCATION, 'w') as json_data: json.dump(ret['id'], json_data)