Added a WooCommerce Coupon plugin

This plugin sets up a coupon on installation and sends this coupon to a
user that asks for it. The plugin supports an expiration period. After
this period, it will renew the coupon.
This commit is contained in:
Dennis Potter 2019-01-13 12:54:45 +01:00
parent 6388f5e104
commit 6cb3ecc373
6 changed files with 154 additions and 0 deletions

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,14 @@
{
"rest_api": {
"shop_url": "https://alcuinus.nl",
"consumer_key": "",
"consumer_secret": "",
"wp_api": true,
"version": "wc/v1"
},
"coupon": {
"max_days": 31,
"percentage":20
}
}

View File

@ -0,0 +1,2 @@
<h5><i>coupon</i></h5>
Als je me een bericht stuurt met het keyword <i>coupon</i> zal ik je de coupon sturen die voor 20% korting op de <a href="https://alcuinus.nl/shop">Alcuinus webshop</a> zorgt.

View File

@ -0,0 +1,5 @@
{
"coupon_message" : "De huidige code om {}% korting te krijgen is: <i><strong>{}</strong></i>. Ga meteen naar <a href=\"https://alcuinus.nl/shop\">de webshop</a> om hem te gebruiken!"
}

View File

@ -0,0 +1 @@
WooCommerce

View File

@ -0,0 +1,131 @@
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 <username>!".
"""
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)