Skip to content

Instantly share code, notes, and snippets.

@shinenelson
Last active November 22, 2019 15:28
Show Gist options
  • Save shinenelson/2861380e2ecb5f4e14d8b42ac231cc74 to your computer and use it in GitHub Desktop.
Save shinenelson/2861380e2ecb5f4e14d8b42ac231cc74 to your computer and use it in GitHub Desktop.
Slack Bot that wishes your team mates on their Birthdays

Birthday Slackbot

This bot wishes your team mates on their birthdays on Slack. It can send a message to a Slack channel of your choosing. You can even mention the user and send a custom greeting message.

The bot is designed to run as a cronjob. It has no dependencies on any external packages. It is also designed to work with both python versions - 2 and 3.

Setup

  1. Configure an Incoming Webhook URL on Slack
  2. Make a copy of the birthdays.example.json file naming it to birthdays.json.
  3. Populate your birthdays database with the birthdays of your team members.
    • NB : You can either use their real names or their usernames. Just remember to configure the mention configuration correctly.
  4. Make a copy of the configurations.json.example file naming it configurations.json. Update the configuration values according to your preferences
    {
       "birthdays_path"         : "birthdays.json",                     # you may change the database filename
                                                                        # according to your preference.
       "mention"                : <true | false>,                       # depends on your database configuration format
                                                                        # if you're using real names, set this value to false
                                                                        # if you're using usernames, set this value to true
       "slack_url"              : "https://hooks.slack.com/...",        # the webhook URL you configured in step 1.
       "channel_name"           : "<channel_name>",                     # the channel you want your wishes to be sent to
       "greeting_message"       : "Happy birthday!"                     # the wish you would like the bot to send
       "bot_name"               : "Birthday Bot"                        # the name of the bot sending the wish
       "bot_emoji"              : ":tada:"                              # the emoji the bot should use as it's icon
    }

Deploy

  1. Run crontab -e to edit your crontab
  2. Add this line to the crontab and save it: @daily cd /clone/location && python Birthday-slackbot.py
    • replace /clone/location with the location where you cloned the repo)
    • the @daily cron shorthand might vary among servers and/or distributions. Replace @daily with a time of your preference according to the cron syntax.
    • Remember to verify the timezone setting of your server or you won't get the expected result.

Contributors

This script was originally written in Ruby from which @shinenelson ported it into Python. The reasoning behind the port was to reduce the barriers to entry for deployment. A python runtime is generally available on *NIX-based systems out-of-the-box making it easier to deploy with minimal effort compared to Ruby which would require a ruby runtime to be installed on the system the script is being deployed on. The idea was to get it running with no dependency installs ( whatsoever ).

License

This script is released into the public domain. See the attached LICENSE file for more information.

#!/usr/bin/env python
import os
from datetime import date
import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
dirname = os.path.dirname( __file__ )
config_file_path = os.path.join( dirname, 'configurations.json' )
with open( config_file_path ) as config_file:
config = json.load( config_file )
birthdays_file_path = os.path.join( dirname, config[ 'birthdays_path' ] )
with open( birthdays_file_path ) as birthdays_file:
birthdays = json.load( birthdays_file )
try:
birthdays_today = birthdays[ date.today().strftime( "%m" ) ][ date.today().strftime( "%d" ) ]
if len( birthdays_today ) == 1:
users = "<@" + birthdays_today[0] + ">" if config[ 'mention' ] else birthdays_today[0]
else:
users = ', '.join( [ "<@" + user + ">" if config[ 'mention' ] else user for user in birthdays_today[:-1] ])
users += ' and ' + ( "<@" + birthdays_today[-1] + ">" if config[ 'mention' ] else birthdays_today[-1] )
if not config[ 'personal_only' ]:
message = users + " " + config[ 'greeting_message' ]
payload = { "channel": config[ 'channel_name' ], "username": config[ 'bot_name' ], "text": message, "icon_emoji": config[ 'bot_emoji' ] }
urlopen( config[ 'slack_url' ], data = json.dumps( payload ).encode() )
if config[ 'mention' ] and config[ 'personal_message' ]:
for user in birthdays_today:
personal_message = "Hey <@" + user + ">, we heard it's your birthday today! :tada: :confetti_ball: \n\nWe'd like to wish you a very happy birthday from the cores of our kernels and CPU ( because, you know, we're just bots running on machines ) :robot_face: :nerd_face: :raised_hands: \n\nHave lots of fun on this special day of your life :dancer: \nWe hope you have many more. \n\nCheers :clinking_glasses:"
personal_payload = { "channel": user, "text": personal_message, "username": "slackbot" }
urlopen( config[ 'slack_url' ], data = json.dumps( personal_payload ).encode() )
except KeyError:
print( "Today is a day that no one was born" )
{
"01" :
{
"01" : [ "elvina.slovak" ]
},
"08" :
{
"02" : [ "john.doe", "jane.doe" ],
"28" : [ "chris.nolan" ],
},
"11" :
{
"15" : [ "erwin.down", "leora.pontious", "randy.young" ]
}
}
{
"birthdays_path" : "birthdays.json",
"slack_url" : "https://hooks.slack.com/...",
"mention" : true,
"personal_message" : true,
"personal_only" : true,
"channel_name" : "general",
"greeting_message" : "Happy birthday !",
"bot_name" : "Birthday Bot",
"bot_emoji" : ":tada:"
}
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
@kishorviswanathan
Copy link

Good job @shinenelson 👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment