top of page

What is ChatOps? Integrating Slack, Opsdroid, and Lambda


chatops-configurated

ChatOps refers to people, bots, processes, and automated programming, all combining efforts to provide integrated solutions that further optimize output. ChatOps is a great solution to automate routine tasks and provide quick access to information across teams and team members.


In this post, you’ll learn:


What is ChatOps?

ChatOps is a collaborative approach combining chat platforms with DevOps practices, allowing teams to streamline workflows, improve communication, and enhance productivity. It involves using chat tools as a central hub for real-time communication, collaboration, and automation to manage and coordinate tasks, deployments, and incident response.


In ChatOps environments, chat rooms become dynamic spaces where conversation-driven collaboration takes center stage. The benefits of ChatOps become evident as team members seamlessly interact in these virtual environments, leveraging specialized ChatOps tools to navigate through workflows and enhance overall productivity.


That's how the essence of group chat transforms into a collaborative powerhouse, providing a comprehensive full view of ongoing processes, from initial ideation to the final stages of code deployment. With the integration of scripts and plugins, tasks are automated, amplifying the efficiency of operations within these collaborative chat rooms.


Whether using popular platforms like Microsoft Teams or other chat tools, the cohesive integration of ChatOps not only enhances team collaboration but also empowers teams with a holistic approach to managing tasks and optimizing their collective efforts.


About Opsdroid

Opsdroid is an open-source chatbot framework written in Python and designed to simplify the development and management of conversational agents. It provides a flexible and extensible platform for building chatbots that can interact with users across various messaging platforms like Telegram, Facebook, Slack, and many others.


Key Features:


  • Support for multiple messaging platforms like Slack, Telegram, Gitter, and more.

  • Allows you to take events from chat services and other sources and execute Python functions called Skills, based on their contents

  • Leveraging natural language processing (NLP) libraries for message interpretation.

  • Automation capabilities for complex conversations and state management.

  • Suitable for both simple command-based bots and sophisticated chatbot applications.


How to build ChatOps

As we said before, ChatOps is a collaboration between several parts, like people, bots, processes, and automation. In this case, we’ll integrate Opsdroid chatbot on Slack to execute Skills through messages on a Slack channel.


Step # 1: Configure Slack

The first step will be creating a new Slack App here (you must have an account), give it a name, and select the workspace you’d like to work in. Select the “Bots” option inside the “Add features and functionality” tab.


Step # 2: Add scopes

2) Click “Review Scopes to Add” and add the following scopes under “Bot Token Scopes”:

  • channels:history View messages and other content in public channels that TMC has been added to

  • channels:read View basic information about public channels in a workspace

  • chat:write Send messages as BOT

  • chat:write.customize Send messages as BOT with a customized username and avatar

  • commands Add shortcuts and/or slash commands that people can use

  • groups:read View basic information about private channels that BOT has been added to

  • im:read View basic information about direct messages that BOT has been added to

  • incoming-webhook Post messages to specific channels in Slack

  • mpim:read View basic information about group direct messages that BOT has been added to

  • reactions:write Add and edit emoji reactions

  • users:read View people in a workspace

With these scopes you’ll allow the chatbot access to the channel, give thread responses, and execute commands. Depending on what you want to do you’ll need to enable or disable more scopes.


Step # 3: Install workspace

Navigate to “OAuth Tokens for Your Workspace” and click the Install to Workspace button and select which channel the Bot has access to post. After this take note of the Bot User OAuth Access Token as this will be used later for Opsdroid as a bot-token:

example-of-aouth-token-shown


Step # 4: Name your token  

4) From the menu on the left select “Socket Mode”. Enable it and it will ask for a name for the Token, then will show you the token generated, copy it as this will be used later for Opsdroid as an app-token:


example-of-token-generated


Step # 5: Subscribe to events

Now we must subscribe to events in your new Slack App, so Opsdroid can receive those events. From the menu on the left select “Event Subscriptions”:


events-suscription-on

And bellow you need to subscribe to the bot to message:channels and save the changes.


suscribe-message-channels-to-your-bot

How to work around Opsdroid

Step # 1: Install and configure Opsdroid

Opsdroid is a FOSS project written in Python and to get installed it's as simple as:


$ pip3 install opsdroid[all]


It's not necessary, but you can start it to automatically create the configuration files.

$ opsdroid start

If you want or need some personalization on the installation you can watch this video.


Step # 2: Connect to Slack

Once installed we will need to configure a connector for Slack, this is through the file called configuration.yaml. To see where is located execute:


$ opsdroid config path/home/facu/.config/opsdroid/configuration.yaml


Open it with your favorite editor or with the command opsdroid config edit



Step # 3: Configure Opsdroid Options 

Here you will see that Opsdroid offers a lot of configuration options that you can customize, like the default room (the channel), or answer creating a thread, but for the moment we just want to paste the tokens that we generated in Slack as values for the bot-token and app-token:

welcome-message: true


connectors:  slack:# # required    bot-token: "xoxb-9876543210-5265939284067-MyFantasyToken"# # optional    socket-mode: true    app-token: "xapp-1-TOKENAPP-7685941351-02030874446290d9128631e59a1cf163c1ea45ba5a"    start-thread: true    bot-name: "mybot"    default-room: "#test"



Step # 4: Give Opsdroid skills 

What makes Opsdroid a very powerful tool is that you can create Skills, which are Python functions that you write which describe how the bot should behave when it receives new events like Slack commands that we want. Above in the same configuration.yaml file you will find the Skills section where you can add entries with the path to your skill file or folder:


## Skill modulesskills:  ## Hello (https://github.com/opsdroid/skill-hello)  hello:    name: helloskill    path: /home/facu/Escritorio/ops/helloskill.py


Now let’s create our first “hello” skill that will be based on the hello skill from the Opsdroid documentation.


from opsdroid.skill import Skillfrom opsdroid.matchers import match_regexfrom opsdroid.events import Reaction, Messageclass HelloSkill(Skill):    @match_regex(r"Hello, I'm (?P<name>\w+)")    async def hello(self, message):        name = message.entities["name"]["value"]        await message.respond("Hi " + name + ", I'm a bot, how can I help you?")


Notice how we made use of match_regex, this will help us match the message from the user against a regular expression.


Opsdroid has a huge variety of other matchers like crontab that allows you to schedule skills to be called on an interval instead of being triggered by events or other matchers that aim to get a more natural communication like IBM Watson or SAP Conversational AI.


Step # 5: Test your Opsdroid skills

To test it you must start Opsdroid with the command opsdroid start and write in the channel that you specify before and get a response from the bot. You should get a response like this:


bot-tested

From here, you can continue creating Skills that fit your needs like implementing skills that automate routine tasks and provide quick access to information. For example, it can retrieve data from databases, execute scripts, or interact with APIs based on user commands. Or you can create a skill that interacts with infrastructure management tools like Terraform or Ansible, executing infrastructure provisioning or configuration changes, providing updates on the status of infrastructure operations, and simplifying communication between teams.


If you work with AWS you can even create a skill that makes use of the AWS SDK for Python (Boto3) to create, configure, and manage AWS services! Here is an example of a generic skill that triggers an AWS Lambda function:


from opsdroid.skill import Skillfrom opsdroid.matchers import match_regeximport boto3class AWSLambdaSkill(Skill):   def __init__(self, opsdroid):       super().__init__(opsdroid)       self.lambda_client = boto3.client('lambda', region_name='your-aws-region')   def invoke_lambda_function(self, function_name, payload):       response = self.lambda_client.invoke(           FunctionName=function_name,           Payload=payload       )       # Process the response as per your requirements       # You can access the response data using response['Key']       return response  @match_regex(r'^invoke lambda function')async def invoke_lambda_function_message(self, message):   function_name = 'your-lambda-function-name'   payload = '{"key": "value"}' # Replace with your payload data   response = self.invoke_lambda_function(function_name, payload)   # Process the response or send a reply to the user   await message.respond(f"AWS Lambda function invoked. Response: {response}")



Note that this is a basic implementation, and you may need to handle exceptions, authentication, and other aspects based on your specific use case. Additionally, you'll need to configure AWS credentials for boto3 to access your AWS account.


Make sure to replace 'your-aws-region', 'your-lambda-function-name', and '{"key": "value"}' with your actual AWS Region, Lambda function name, and payload data, respectively, and also add the Skill in your Opsdroid configuration.yaml file.


Final Thoughts

This is just one example of how Opsdroid can be used. Its flexibility and extensibility through plugins and adapters allow you to tailor its use to your specific needs and integrate it with various tools and systems within your infrastructure.



photo-of-facundo-montero






Facundo Montero


Cloud Engineer


Teracloud








If you want to know more about our tips, we suggest checking Why you should use IMDSv2

If you are interested in learning more about our TeraTips or our blog's content, we invite you to see all the content entries that we have created just for you.



Comments


Entradas recientes
Buscar por tags
Síguenos
  • Twitter Basic Square
bottom of page