🚀 Executive Summary

TL;DR: Remote teams often struggle with maintaining spontaneous connections, leading to disconnection. This guide provides a Python script integrated with Slack to automatically pair team members for weekly random coffee chats, effectively boosting morale and cross-functional communication.

🎯 Key Takeaways

  • Leverage `slack_sdk` and specific Slack Bot Token Scopes (`chat:write`, `users:read.email`) to enable direct messaging and user ID lookup via email.
  • Implement secure API token management using `python-dotenv` to load `SLACK_BOT_TOKEN` from a `config.env` file, preventing hardcoding sensitive credentials.
  • Design a robust pairing algorithm that shuffles employees, creates two-person pairs, and gracefully handles an odd number of participants by forming one group of three.

Create a Random Coffee Chat pairing script for Remote Teams

Create a Random Coffee Chat pairing script for Remote Teams

Hey there, Darian Vance here. As a Senior DevOps Engineer at TechResolve, I spend a lot of my time automating processes to save time and reduce errors. But some of the most valuable automations I’ve built have nothing to do with deployments or monitoring. They’re about people.

When my team went fully remote, we lost those spontaneous “water cooler” moments. It was efficient, but we started feeling a bit disconnected. I built a simple Python script to automatically pair team members for a random coffee chat each week. It took about an hour to set up, and the boost in team morale and cross-functional communication has been incredible. This isn’t just a “nice-to-have”; it’s a vital tool for maintaining a cohesive remote culture. Let me show you how to build it.

Prerequisites

Before we dive in, make sure you have a few things ready. I’m assuming you’re comfortable with basic Python and managing your environment.

  • Python 3.6 or newer installed.
  • A Slack workspace where you have permissions to create an app.
  • A list of your team members’ email addresses (the ones they use for Slack).

The Step-by-Step Guide

Step 1: Project Setup and Dependencies

First, get your project directory and Python virtual environment sorted. I’ll skip the standard `mkdir` and `venv` commands since you likely have your own workflow for that. The important part is to get the necessary libraries installed. In your activated virtual environment, you’ll need to run pip to install two key packages: `python-dotenv` for managing our secret token and `slack_sdk` for interacting with the Slack API. I trust you can handle that part.

Step 2: Get Your Slack Bot Token

This is the most crucial part of the setup. We need to tell Slack that our script is allowed to perform actions in our workspace.

  1. Go to api.slack.com/apps and click “Create New App”. Choose “From scratch”.
  2. Give it a name like “Coffee Bot” and select your workspace.
  3. In the sidebar, navigate to “OAuth & Permissions”.
  4. Scroll down to the “Scopes” section. Under “Bot Token Scopes”, you’ll need to add two permissions:
    • chat:write: This allows the bot to send messages.
    • users:read.email: This allows the bot to find users by their email address.
  5. Scroll back to the top and click “Install to Workspace”. Authorize it.
  6. You’ll now see a “Bot User OAuth Token” that starts with xoxb-. This is your golden ticket. Copy it.

Pro Tip: Never, ever hardcode this token in your script. We’re going to store it in an environment file. Create a file in your project directory named config.env. Inside it, add this line:

SLACK_BOT_TOKEN="xoxb-your-token-goes-here"

Step 3: Create Your Team List

In your project folder, create a simple text file named employees.txt. List one team member’s email per line. Make sure these are the emails associated with their Slack accounts.

alice@techresolve.com
bob@techresolve.com
charlie@techresolve.com
dave@techresolve.com
eve@techresolve.com

Step 4: Writing the Python Script

Alright, let’s get to the code. The logic is straightforward: read the emails, shuffle them, create pairs (or a group of three if there’s an odd number), find their Slack IDs, and send them a friendly message.

Here’s the complete script. I’ve added comments to explain each part.


import os
import random
import logging
from dotenv import load_dotenv
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

# --- Configuration ---
# Set up basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Load environment variables from config.env file
load_dotenv('config.env')
SLACK_TOKEN = os.getenv("SLACK_BOT_TOKEN")
EMPLOYEE_FILE = "employees.txt"

# --- Main Logic ---

def get_employees(filename):
    """Reads a list of employees from a text file."""
    try:
        with open(filename, 'r') as f:
            employees = [line.strip() for line in f if line.strip()]
        logging.info(f"Successfully read {len(employees)} employees from {filename}.")
        return employees
    except FileNotFoundError:
        logging.error(f"Error: The file {filename} was not found.")
        return []

def create_pairings(employees):
    """Shuffles and pairs employees. Handles an odd number by creating one group of three."""
    if not employees:
        logging.warning("Employee list is empty. No pairings to create.")
        return []
    
    random.shuffle(employees)
    pairings = []
    
    while len(employees) > 3:
        pair = (employees.pop(), employees.pop())
        pairings.append(pair)
    
    # If 2 or 3 employees remain, they form the final group
    if employees:
        pairings.append(tuple(employees))
        
    logging.info(f"Created {len(pairings)} pairings/groups.")
    return pairings

def get_slack_user_id(client, email):
    """Fetches a Slack user's ID by their email."""
    try:
        response = client.users_lookupByEmail(email=email)
        return response['user']['id']
    except SlackApiError as e:
        logging.error(f"Error fetching user ID for {email}: {e.response['error']}")
        return None

def send_pairing_message(client, user_ids, pair_members):
    """Sends a direct message to a group of users."""
    try:
        # Open a multi-person direct message channel
        conversation_response = client.conversations_open(users=user_ids)
        channel_id = conversation_response['channel']['id']
        
        # Format the message
        names = [f"<@{uid}>" for uid in user_ids]
        if len(names) == 2:
            message_intro = f"Hey {names[0]} and {names[1]}!"
        else: # For groups of 3
            message_intro = f"Hey {', '.join(names)}!"

        message_text = (
            f"{message_intro}\n\n"
            "Welcome to this week's random coffee chat! :coffee:\n\n"
            "Please find a time in the next week to connect for 15-20 minutes. "
            "Talk about anything you like—work, hobbies, or weekend plans. The goal is just to connect. Have fun!"
        )
        
        client.chat_postMessage(channel=channel_id, text=message_text)
        logging.info(f"Successfully sent message to: {', '.join(pair_members)}")
    except SlackApiError as e:
        logging.error(f"Error sending message to {', '.join(pair_members)}: {e.response['error']}")

def main():
    """Main function to run the pairing process."""
    if not SLACK_TOKEN:
        logging.error("SLACK_BOT_TOKEN not found. Please check your config.env file.")
        return

    client = WebClient(token=SLACK_TOKEN)
    employees = get_employees(EMPLOYEE_FILE)
    
    if len(employees) < 2:
        logging.warning("Not enough employees to form a pair. Exiting.")
        return

    pairings = create_pairings(employees)

    for pair in pairings:
        user_ids = [get_slack_user_id(client, email) for email in pair]
        # Filter out any Nones in case a user lookup failed
        valid_user_ids = [uid for uid in user_ids if uid]
        
        if len(valid_user_ids) > 1:
            send_pairing_message(client, valid_user_ids, pair)
        else:
            logging.warning(f"Could not create a valid pair for {pair}. One or more users not found in Slack.")

if __name__ == "__main__":
    main()

Step 5: Automating the Script

The final step is to make this run automatically. On any Linux-based system, the classic tool for this is cron. You can set up a cron job to execute your script every Monday morning, for example.

You’ll need to edit your crontab. I won’t specify the command to do that, as it varies, but once you’re editing it, you can add a line like this to run the script every Monday at 2 AM:

0 2 * * 1 python3 script.py

Pro Tip: When running a script from cron, it’s often better to use full paths to your Python interpreter and script to avoid any ambiguity. However, for security reasons in this guide, I’ve kept it generic. In my production setups, I’d provide the full, unambiguous path to both the interpreter within the virtual environment and the script itself.

Where I Usually Mess Up (Common Pitfalls)

  • Incorrect Slack Scopes: The number one issue I run into is forgetting a permission scope. If your script fails with an error like `missing_scope`, double-check the “OAuth & Permissions” page in your Slack app settings. You must reinstall the app to the workspace after adding new scopes!
  • Inactive Users: If someone leaves the company, their email will still be in your employees.txt. The Slack API call will fail, and a pairing might not get created. It’s good practice to periodically audit your list and remove anyone who is no longer active.
  • Environment Variables Not Loading: If you get a “token not found” error, make sure your config.env file is in the same directory where you’re running the script, and that it’s named correctly.

Conclusion

And that’s it. With a simple text file and a Python script, you’ve built a powerful tool for fostering connection on a remote team. It’s a small investment of time that pays huge dividends in team culture and happiness. In my experience, these are the kinds of thoughtful automations that separate a good DevOps practice from a great one. Give it a try, and let me know how it works for your team.

Darian Vance - Lead Cloud Architect

Darian Vance

Lead Cloud Architect & DevOps Strategist

With over 12 years in system architecture and automation, Darian specializes in simplifying complex cloud infrastructures. An advocate for open-source solutions, he founded TechResolve to provide engineers with actionable, battle-tested troubleshooting guides and robust software alternatives.


🤖 Frequently Asked Questions

âť“ What are the essential steps to deploy a random coffee chat bot for a remote team using Python and Slack?

To deploy, first set up a Python virtual environment with `python-dotenv` and `slack_sdk`. Create a Slack app, define `chat:write` and `users:read.email` bot token scopes, and obtain your `xoxb-` token. Store this token in `config.env`, list team emails in `employees.txt`, and then run the provided Python script, optionally automating it with cron.

âť“ How does this custom Python script solution compare to using existing third-party coffee chat apps?

This custom Python script offers a self-hosted, open-source alternative, providing full control over the pairing logic and data. Unlike many third-party apps, it avoids subscription costs and allows for tailored modifications, though it requires initial setup and maintenance expertise.

âť“ What is a common pitfall when setting up the Slack integration for this coffee chat script?

A common pitfall is incorrect Slack Bot Token Scopes. If the script fails with a `missing_scope` error, ensure `chat:write` and `users:read.email` permissions are added in the Slack app’s ‘OAuth & Permissions’ settings, and the app is reinstalled to the workspace.

Leave a Reply

Discover more from TechResolve - SaaS Troubleshooting & Software Alternatives

Subscribe now to keep reading and get access to the full archive.

Continue reading