Work Anniversary Image – Skype Bot using AWS Lambda

At Qxf2 services, we get to pick and work on any problem area (eg: Onboarding, Training, etc.) based on our interest. The one I take care of is ‘Employee Engagement. As a part of this initiative, I started congratulating employees on their work anniversary in the form of a Work Anniversary Image.


Why Work Anniversary Image Skype Bot using AWS Lambda?

Prior to the development of the Work Anniversary Image Skype Bot, the entire process was manual right from finding out which employee has a Work Anniversary, designing Work Anniversary Image and finally posting it on skype. This approach started to consume a lot of my work time as Qxf2 started to grow bigger. Therefore, I felt the need to automate the process in the form of a Work Anniversary Image Skype Bot. I thought of using the same AWS Lambda tech which we found useful to automate a couple of our internal tasks, one of them being the Holiday Reminder blog.


How I solved the problem?

Breaking down the problem into mini problems

I began breaking down my problem into 4 sub problems and found respective solutions for each which were :-

1. Maintaining and polling employees data to look for upcoming work anniversary

Firstly, the problem was maintaining and polling employee details to find out which employee has a work anniversary. However, a major part of it was already solved by my colleague Arunkumar by building an employee web service to aid in the development of our internal applications which would return employees data at any given point in time.

2. Get Work Anniversary Images designed

Secondly, designing work anniversary images on the fly along with specific text overlapped on top of it had to be tackled. For this, I found an image processing python package called Pillow to be useful.

3. Posting Image on the skype channel on the day of Work Anniversary

Thirdly, and most importantly the major hurdle I had to overcome was posting these images on the Skype channel. We had an existing skype sender web service designed using Skypy but it could only send the text messages. As a result, I skimmed through Skypy documentation to check if it can offer a capability to send images as well. I found out an API method documented sendFile. Accordingly we updated our skype sender web service with the capability to send images to skype.

4. Base template design & work anniversary quotes

After that, I was left with two one-time tasks of getting a work anniversary base template image designed in coordination with our illustrator Edward and creating a list of work anniversary quotes.

When all the pieces were integrated, the entire flow looked likeWork Anniversary image flow

Code Implementation

Work Anniversary Image Creation lambda function is subdivided into 4 major methods:
1. Fetching employees data
2. Calculating Work Anniversary
3. Generating Work Anniversary Image
4. Sending Image to Skype Channel

1. Fetching employees data from our internal employees service
def get_all_employees():
    "Query allEmployees"
    query = """query
    findAllEmployees{
        allEmployees{
            edges{
                node{
                    email
                    firstname
                    lastname
                    dateJoined
                    isActive
                }
            }
        }
    }"""
    access_token = authenticate()
    headers = {'Authorization': f'Bearer {access_token}'}
    response = requests.get(url = BASE_URL, json = {'query': query}, headers =\
        headers)
    all_employees = response.json().get('data', {}).get('allEmployees', {}).get('edges', [])
    return all_employees
2. Calculating Work Anniversary

– Employee data is looped through to check if a given employee has a work anniversary. After that, an anniversary quote is fetched from predefined list saved in work_anniversary_quotes.txt file.

def calculate_work_anniversary(emp_joined_date, current_date, emp_name):
    "Calculate the difference"
    msg,quote_string = None,None
    if (emp_joined_date.month == current_date.month and emp_joined_date.day == current_date.day):
        difference_in_years = inflect_obj.ordinal(relativedelta(current_date, emp_joined_date).years)
        msg = f'Happy {difference_in_years} work anniversary {emp_name}'
        with open('anniversary_quotes.txt',encoding="utf8") as json_file:
            data = json.load(json_file)
 
        if emp_name in data.keys() :
            if len(data[emp_name]) >= 1:
                quote_string = random.choice(data[emp_name])
            else:
                quote_string = get_default_quotes(data,difference_in_years)
        else:
            quote_string = get_default_quotes(data,difference_in_years)    
    final_quote_string = '\n'.join(textwrap.wrap(quote_string, 70, break_long_words=False,subsequent_indent='\n')) if quote_string is not None else ''
    return msg,final_quote_string
3. Generating Work Anniversary Image

– Employees name , anniversary quote is superimposed on a base Work Anniversary template image and saved to /tmp/ location with employees name prefixed to it. This involved use of Pillow and textwrap python packages for image processing and text formatting respectively.

def add_text_to_image(message,emp_name,quote_string):
    image = Image.open('Work_anniversary_template.png')
    draw = ImageDraw.Draw(image)
    font1 = ImageFont.truetype('Casanova_Font_Free.ttf', size=130)
    font2 = ImageFont.truetype('Casanova_Font_Free.ttf', size=95)
 
    # starting position of the message
    (x, y) = (650, 500)
    color = 'rgb(128, 0, 128)' # purple color
    draw.text((x, y), message, fill=color, font=font1)
 
    (x, y) = (400, 700)
    color = 'rgb(255, 69, 0)' # orange color
    draw.text((x, y), quote_string, fill=color, font=font2)
 
    filepath = '/tmp/' +emp_name+ '_greeting_card.png'
    image.save(filepath,quality=95)
    return filepath

Generated Work Anniversary Image looks like this Work Anniversary Image

4. Sending Image to Skype

– Generated Work Anniversary Image from step 3 is then sent to Skype channel via skype image sender web service hosted on EC2 instance by our Qxf2Bot skype user. Post sending the image to skype channel, image is deleted from ‘/tmp’ location.

def send_image(img, img_name, channel_id = credentials.CHANNEL_ID):
    data = {'API_KEY' : credentials.API_KEY,
    'img_name' : img_name,
    'channel' : channel_id}
    files = [
        ('document', (img_name, open(img, 'rb'), 'application/octet')),
        ('data', ('data', json.dumps(data), 'application/json')),
        ]
    response = requests.post(SKYPE_URL, files = files)
    time.sleep(2)
    return response.status_code

You can view the complete code on Github.


Triggering the event

Work Anniversary Image lambda function gets triggered everyday via a Cloudwatch event which results in posting the image on Skype channel by our Qxf2 bot skype userQxf2 bot work anniversary image

Hope you liked this blog post !! If you have any questions then please leave your comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *