Friday 24 November 2023

Web Tutorial: The Self-affirmations WordPress Plugin (Part 3/4)

The next funciton we need to deal with, is tt_generate_email(). Before we begin, you will need a CharGPT Developer Account, and an API key. It doesn't cost all that much, honestly, so I would absolutely recommend putting that credit card to good use.

We begin by adding in parameters for the function. We wat the email address ($id), the name, gender and birthday.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name, $gender, $dob)
{

}


For all the parameters other than the first, we will have default values. Thus, when you run this function without passing any values in, it will use these values.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name = "Teochew Thunder", $gender = "M", $dob = "01-01-1980")
{

}
-

We begin the function by declaring the variable terms, and running tt_get_terms() with the value of id passed in as an argument, to set terms to the returned value. Bear in mind that if there is no value given for id, tt_get_terms() will use "teochewthunder@gmail.com" as a default value.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name = "Teochew Thunder", $gender = "M", $dob = "01-01-1980")
{
    $terms = tt_get_terms($id);
}


We then declare interests as an empty string. And then we check if the interests array of terms is not empty. We'll only alter the value of interests if so.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name = "Teochew Thunder", $gender = "M", $dob = "01-01-1980")
{
    $terms = tt_get_terms($id);

    $interests = "";
    if (count($terms["interests"]) > 0)
    {
    
    }

}


Firstly, we use the value of gender to ensure that the string interests is correct in the gender sense.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name = "Teochew Thunder", $gender = "M", $dob = "01-01-1980")
{
    $terms = tt_get_terms($id);

    $interests = "";
    if (count($terms["interests"]) > 0)
    {
        $interests = ($gender == "M" ? "He" : "She") . " is interested in ";    
    }
}


Then we iterate through the interests array of the terms array using a For loop.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name = "Teochew Thunder", $gender = "M", $dob = "01-01-1980")
{
    $terms = tt_get_terms($id);

    $interests = "";
    if (count($terms["interests"]) > 0)
    {
        $interests = ($gender == "M" ? "He" : "She") . " is interested in ";
        for ($i = 0; $i < sizeof($terms["interests"]); $i++)
        {

        }    
    
    }
}


What we do next, is append the value of the current element to the interests string. Thus, if gender is "M" and the first element of interests is "rollerblading", the resultant string would be "He is interested in rollerblading". After that, we check if the current element is the final element of the interests array.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name = "Teochew Thunder", $gender = "M", $dob = "01-01-1980")
{
    $terms = tt_get_terms($id);

    $interests = "";
    if (count($terms["interests"]) > 0)
    {
        $interests = ($gender == "M" ? "He" : "She") . " is interested in ";
        for ($i = 0; $i < sizeof($terms["interests"]); $i++)
        {
            $interests .= $terms["interests"][$i];
            if ($i == sizeof($terms["interests"]) - 1)
            {

            }
            else
            {

            }
        }   
     
    }
}


If so, append a full-stop. If not, append the string "and" preceded and superseded by a space. Thus, if interests contains the values "jazz music". "spiders" and "surfing", and gender is "F", the resultant string would be "She is interested in jazz music and spiders and surfing". Not a perfect sentence, but it should make sense to ChatGPT.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
function tt_generate_mail($id, $name = "Teochew Thunder", $gender = "M", $dob = "01-01-1980")
{
    $terms = tt_get_terms($id);

    $interests = "";
    if (count($terms["interests"]) > 0)
    {
        $interests = ($gender == "M" ? "He" : "She") . " is interested in ";
        for ($i = 0; $i < sizeof($terms["interests"]); $i++)
        {
            $interests .= $terms["interests"][$i];
            if ($i == sizeof($terms["interests"]) - 1)
            {
                $interests .= ". ";
            }
            else
            {
                $interests .= " and ";
            }
        }        
    }
}


We'll do something similar for the descriptions array.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$interests = "";
if (count($terms["interests"]) > 0)
{
    $interests = ($gender == "M" ? "He" : "She") . " is interested in ";
    for ($i = 0; $i < sizeof($terms["interests"]); $i++)
    {
        $interests .= $terms["interests"][$i];
        if ($i == sizeof($terms["interests"]) - 1)
        {
            $interests .= ". ";
        }
        else
        {
            $interests .= " and ";
        }
    }        
}

$descriptions = "";
if (count($terms["descriptions"]) > 0)
{
    $descriptions = ($gender == "M" ? "He" : "She") . " is described as ";        
    for ($i = 0; $i < sizeof($terms["descriptions"]); $i++)
    {
        $descriptions .= $terms["descriptions"][$i];
        if ($i == sizeof($terms["descriptions"]) - 1)
        {
            $descriptions .= ". ";
        }
        else
        {
            $descriptions .= " and ";
        }
    }        
}



After that, we use name, gender and dob to formulate the string about.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$descriptions = "";
if (count($terms["descriptions"]) > 0)
{
    $descriptions = ($gender == "M" ? "He" : "She") . " is described as ";        
    for ($i = 0; $i < sizeof($terms["descriptions"]); $i++)
    {
        $descriptions .= $terms["descriptions"][$i];
        if ($i == sizeof($terms["descriptions"]) - 1)
        {
            $descriptions .= ". ";
        }
        else
        {
            $descriptions .= " and ";
        }
    }        
}

$about = ($gender == "M" ? "man" : "woman");
$about .= " named '" . $name . "'";
$about .= " born on " . explode("T", $dob)[0];



We then declare prompt and title as empty strings, and tokens as an integer with an initial value of 50. prompt_type is declared as a random number from 0 to 20. The future values of prompt, tokens and title will depend on the value of prompt_type.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$about = ($gender == "M" ? "man" : "woman");
$about .= " named '" . $name . "'";
$about .= " born on " . explode("T", $dob)[0];

$prompt_type = rand(0, 20);
$prompt = "";
$tokens = 50;
$title = "";



As you can see, in here I use a Switch statement on prompt_type and use that to determine values.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$prompt_type = rand(0, 20);
$prompt = "";
$tokens = 50;
$title = "";

switch($prompt_type)
{
    case 0: $prompt = "Generate a complimentary poem about"; $title = "A poem for you!"; $tokens = 3000; break;
    case 1: $prompt = "Generate some positive life advice for"; $title = "Some life advice"; $tokens = 1000; break;
    case 2: $prompt = "Generate a sample horoscope for"; $title = "Your Zodiac advice"; $tokens = 3000; break;
    case 3: $prompt = "Generate a Chinese zodiac horoscope for"; $title = "Your Zodiac advice"; $tokens = 3000; break;
    case 4: $prompt = "Generate an encouraging two paragraph letter to self for"; $title = "Your self-affirmation"; $tokens = 2000; break;
    case 5: $prompt = "Generate an encouraging one paragraph letter to self for"; $title = "Your self-affirmation"; $tokens = 1000; break;
    case 6: $prompt = "Generate an encouraging three paragraph letter to self for"; $title = "Your self-affirmation"; $tokens = 3000; break;            
    case 7: $prompt = "Generate a funny and uplifting short story about"; $title = "The Story of You"; $tokens = 3000; break;
    case 8: $prompt = "Generate five inspirational quotes from famous people for"; $title = "Five Quotes to make your day"; $tokens = 2500; break;
    case 9: $prompt = "Generate five fictitious short reviews from fictitious publications about"; $title = "Your reviews from public media"; $tokens = 2500; break;
    case 10: $prompt = "Generate five fictitious one-sentence reviews from fictitious people from diverse races and their occupations about"; $title = "Public Opinion About You"; $tokens = 2500; break;
    case 11: $prompt = "Generate five fictitious one-sentence reviews from fictitious people from diverse races complimenting the personality of"; $title = "Public Opinion About You"; $tokens = 2500; break;                
    case 12: $prompt = "Generate five corny pickup lines from random people for"; $title = "Pickup Lines For You"; $tokens = 2500; break;
    case 13: $prompt = "Generate a character testimonial (from self) for"; $title = "Your testimonial!"; $tokens = 3000; break;
    case 14: $prompt = "Write a love letter (from self) to"; $title = "Some self-love"; $tokens = 3000; break;
    case 15: $prompt = "Create a short movie synopsis with famous actors about"; $title = "A movie was made about you!"; $tokens = 3000; break;            
    case 16: $prompt = "Create a movie role, with famous co-stars, for"; $title = "A movie role for you"; $tokens = 3000; break;            
    case 17: $prompt = "Write a welcoming letter from the President of a Fan Club centered around"; $title = "Welcome Address From " . $name . " Fan Club"; $tokens = 1000; break;
    case 18: $prompt = "Generate a sensational and funny article from a fictitious publication about"; $title = "An article About You"; $tokens = 1000; break;            
    default: $prompt = "Generate a complimentary poem about"; $title = "A poem for you!"; $tokens = 3000; break;            
}



tokens will need to be larger depending on how many values interests and descriptions have.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php

switch($prompt_type)
{
    case 0: $prompt = "Generate a complimentary poem about"; $title = "A poem for you!"; $tokens = 3000; break;
    case 1: $prompt = "Generate some positive life advice for"; $title = "Some life advice"; $tokens = 1000; break;
    case 2: $prompt = "Generate a sample horoscope for"; $title = "Your Zodiac advice"; $tokens = 3000; break;
    case 3: $prompt = "Generate a Chinese zodiac horoscope for"; $title = "Your Zodiac advice"; $tokens = 3000; break;
    case 4: $prompt = "Generate an encouraging two paragraph letter to self for"; $title = "Your self-affirmation"; $tokens = 2000; break;
    case 5: $prompt = "Generate an encouraging one paragraph letter to self for"; $title = "Your self-affirmation"; $tokens = 1000; break;
    case 6: $prompt = "Generate an encouraging three paragraph letter to self for"; $title = "Your self-affirmation"; $tokens = 3000; break;            
    case 7: $prompt = "Generate a funny and uplifting short story about"; $title = "The Story of You"; $tokens = 3000; break;
    case 8: $prompt = "Generate five inspirational quotes from famous people for"; $title = "Five Quotes to make your day"; $tokens = 2500; break;
    case 9: $prompt = "Generate five fictitious short reviews from fictitious publications about"; $title = "Your reviews from public media"; $tokens = 2500; break;
    case 10: $prompt = "Generate five fictitious one-sentence reviews from fictitious people from diverse races and their occupations about"; $title = "Public Opinion About You"; $tokens = 2500; break;
    case 11: $prompt = "Generate five fictitious one-sentence reviews from fictitious people from diverse races complimenting the personality of"; $title = "Public Opinion About You"; $tokens = 2500; break;                
    case 12: $prompt = "Generate five corny pickup lines from random people for"; $title = "Pickup Lines For You"; $tokens = 2500; break;
    case 13: $prompt = "Generate a character testimonial (from self) for"; $title = "Your testimonial!"; $tokens = 3000; break;
    case 14: $prompt = "Write a love letter (from self) to"; $title = "Some self-love"; $tokens = 3000; break;
    case 15: $prompt = "Create a short movie synopsis with famous actors about"; $title = "A movie was made about you!"; $tokens = 3000; break;            
    case 16: $prompt = "Create a movie role, with famous co-stars, for"; $title = "A movie role for you"; $tokens = 3000; break;            
    case 17: $prompt = "Write a welcoming letter from the President of a Fan Club centered around"; $title = "Welcome Address From " . $name . " Fan Club"; $tokens = 1000; break;
    case 18: $prompt = "Generate a sensational and funny article from a fictitious publication about"; $title = "An article About You"; $tokens = 1000; break;            
    default: $prompt = "Generate a complimentary poem about"; $title = "A poem for you!"; $tokens = 3000; break;            
}

$tokens += (100 * count($terms["interests"]));
$tokens += (100 * count($terms["descriptions"]));



And here, we declare final_prompt. We use the values of the strings prompt, about, interests and descriptions. Thus, a typical string would be "Generate a complimentary poem about a woman named 'Venus Chen', born on 02-11-1988. She is interested in positive thinking and flowers. She is described as happy and optimistic and emotional.". Add a line that displays final_prompt on screen.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$tokens += (100 * count($terms["interests"]));
$tokens += (100 * count($terms["descriptions"]));

$final_prompt = $prompt . " " . $about . ". " . $interests . $descriptions;

echo $final_prompt;


Test this!


This was the text returned. Because we first ran tt_get_terms(), it returned us the list of terms. Then you see that we have the prompt at the end.
{"items":[{"type":"DESCRIPTIONS","term":"acidic"},{"type":"DESCRIPTIONS","term":"cynical"},{"type":"DESCRIPTIONS","term":"jolly"},{"type":"DESCRIPTIONS","term":"patient"},{"type":"DESCRIPTIONS","term":"pragmatic"},{"type":"INTERESTS","term":"comedy"},{"type":"INTERESTS","term":"programming"},{"type":"INTERESTS","term":"soccer"},{"type":"INTERESTS","term":"superheroes"}],"hasMore":false,"limit":25,"offset":0,"count":9,"links":[{"rel":"self","href":"https://apex.oracle.com/pls/apex/teochewthunder/mailinglist/terms/teochewthunder@gmail.com"},{"rel":"describedby","href":"https://apex.oracle.com/pls/apex/teochewthunder/metadata-catalog/mailinglist/terms/item"},{"rel":"first","href":"https://apex.oracle.com/pls/apex/teochewthunder/mailinglist/terms/teochewthunder@gmail.com"}]}Generate a Chinese zodiac horoscope for man named 'Teochew Thunder' born on 01-01-1980. He is interested in programming and soccer. He is described as acidic and cynical and jolly and pragmatic.


Now that you have a prompt, it's time to send it to ChatGPT. For this, you will need an account and a key, Declare the variables key, org and url. key is the key provided for your ChatGPT developer account. org is the account id. url is the endpoint for ChatGPT. Of course your key isn't going to be "sk=xxx", but I'm not about to share my key in public. That would defeat the entire purpose of having a key, amirite?

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$final_prompt = $prompt . " " . $about . ". " . $interests . $descriptions;

echo $final_prompt;

$key = "sk-xxx";
$org = "org-FUOhDblZb1pxvaY6YylF54gl";
$url = "https://api.openai.com/v1/chat/completions";



Declare headers as an array with three strings. The first string is for authorization and includes key. The next one is to identify the account, and includes org. And the last line explicitly states that the content type is JSON.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$key = "sk-xxx";
$org = "org-FUOhDblZb1pxvaY6YylF54gl";
$url = "https://api.openai.com/v1/chat/completions";

$headers = [
    "Authorization: Bearer " . $key,
    "OpenAI-Organization: " . $org,
    "Content-Type: application/json"
];



Declare messages and obj as empty arrays. Declare keys role and content in obj. The value of role should be "user", while the value of content should be final_prompt. And then make obj the first element of messages.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php

$headers = [
    "Authorization: Bearer " . $key,
    "OpenAI-Organization: " . $org,
    "Content-Type: application/json"
];

$messages = [];
$obj = [];
$obj["role"] = "user";
$obj["content"] = $final_prompt;
$messages[] = $obj;



Then declare data as an empty array. Add keys model, messages and max_tokens. The value of model is the ChatGPT version. The value of messages is messages. The value of max_tokens is tokens, which we defined earlier based on the amount of information given.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$messages = [];
$obj = [];
$obj["role"] = "user";
$obj["content"] = $final_prompt;
$messages[] = $obj;

$data = [];
$data["model"] = "gpt-3.5-turbo";
$data["messages"] = $messages;
$data["max_tokens"] = $tokens;


Now begin cURL. It should be using the POST method. We send in data in JSON string format using the json_encode() function. We also set the headers to headers, and ensure that it returns a value.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php

$data = array();
$data["model"] = "gpt-3.5-turbo";
$data["messages"] = $messages;
$data["max_tokens"] = $tokens;

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);



Then we run curl_exec() passing in curl as an argument, and assign the returned value to result. If there's an error, display it. If there's no error, print result. Finally, clean up using curl_close().

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($curl);
if (curl_errno($curl))
{
    echo "Error:" . curl_error($curl);
}
else
{
    echo print_r($result);
}

curl_close($curl);    



Now test this!


Try it again! Is the prompt and result different?


That's it for the test, but we still need to return a value. So use json_decode() on result.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
curl_close($curl);    
    
$result = json_decode($result);


Then declare sanitized_content. It should be the value of the content property of the message object of the first element in choices, of result. If that sounds convoluted, refer to the displayed printout on screen earlier and you'll see the hierarchy.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
curl_close($curl);    

$result = json_decode($result);
$sanitized_content = $result->choices[0]->message->content;


And then we use str_replace() to replace all the template strings in the output with reasonable data. There's no real exhaustive list of this.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
curl_close($curl);    

$result = json_decode($result);
$sanitized_content = $result->choices[0]->message->content;
$sanitized_content = str_replace("[Your Name]", $name, $sanitized_content);
$sanitized_content = str_replace("[President's Name]", $name, $sanitized_content);
$sanitized_content = str_replace("[Fan Club Name]", $name . " Fan Club", $sanitized_content);
$sanitized_content = str_replace("[Date]", date("j F Y"), $sanitized_content);
$sanitized_content = str_replace("[Insert Date]", date("j F Y"), $sanitized_content);
$sanitized_content = str_replace("[President's Logo]", "", $sanitized_content);
$sanitized_content = str_replace("[P.O Box]", "", $sanitized_content);
$sanitized_content = str_replace("[City, State, Zip Code]", "", $sanitized_content);
$sanitized_content = str_replace("[Email Address]", "", $sanitized_content);
$sanitized_content = str_replace("[Website]", "", $sanitized_content);
$sanitized_content = str_replace("[Social Media Handles]", "", $sanitized_content);    


And finally, return an array with two keys - title and body. The value of title is title, which we defined earlier. And the value of body is sanitized_content.

wp-content/plugins/tt_selfaffirmations/tt_selfaffirmations.php
$result = json_decode($result);
$sanitized_content = $result->choices[0]->message->content;
$sanitized_content = str_replace("[Your Name]", $name, $sanitized_content);
$sanitized_content = str_replace("[President's Name]", $name, $sanitized_content);
$sanitized_content = str_replace("[Fan Club Name]", $name . " Fan Club", $sanitized_content);
$sanitized_content = str_replace("[Date]", date("j F Y"), $sanitized_content);
$sanitized_content = str_replace("[Insert Date]", date("j F Y"), $sanitized_content);
$sanitized_content = str_replace("[President's Logo]", "", $sanitized_content);
$sanitized_content = str_replace("[P.O Box]", "", $sanitized_content);
$sanitized_content = str_replace("[City, State, Zip Code]", "", $sanitized_content);
$sanitized_content = str_replace("[Email Address]", "", $sanitized_content);
$sanitized_content = str_replace("[Website]", "", $sanitized_content);
$sanitized_content = str_replace("[Social Media Handles]", "", $sanitized_content);    

return ["title" => $title, "body" => $sanitized_content];


We have written a function to generate email content. Now we need to send the email, and schedule the task!

Next

Setting up the CRON job.

No comments:

Post a Comment