pymsteams

repository·master·Indexed 19 days ago

https://github.com/rveachkc/pymsteams

A Python wrapper library for sending Microsoft Teams Connector Card messages via Webhook URLs. It supports synchronous and asynchronous message sending (via async_connectorcard), as well as complex card layouts using cardsection for content blocks and potentialaction for interactive elements like buttons and input forms.

Tokens
3.3K
Snippets
12
Records
14
Agent score
16%

What's inside pymsteams

  1. Send a basic ConnectorCard message

    master

    The simplest way to use pymsteams is to create a connectorcard object with your Microsoft Webhook URL, add text, and call .send(). This sends a message containing plain text.

    import pymsteams
    
    # Create the object with the Microsoft Webhook URL
    myTeamsMessage = pymsteams.connectorcard("<Microsoft Webhook URL>")
    
    # Add text to the message
    myTeamsMessage.text("this is my text")
    
    # Send the message
    myTeamsMessage.send()
  2. Install pymsteams

    master

    Install the standard library using pip:

    pip install pymsteams

    To enable asynchronous capabilities (requires Python 3.6+), install with the [async] extra:

    pip install pymsteams[async]

    Note: For Python 2 support, you must use version 0.1.16 or earlier.

    pip install pymsteams
  3. Configure SSL Certificate Validation

    master

    When initializing a connectorcard, you can control SSL certificate verification via the verify parameter:

    • To use a custom CA bundle: Pass the file path as a string.
    • To disable validation: Pass False.
    import pymsteams
    
    # Use custom CA bundle
    msg = pymsteams.connectorcard("<URL>", verify="/path/to/file")
    
    # Disable CA validation
    msg = pymsteams.connectorcard("<URL>", verify=False)
    msg = pymsteams.connectorcard("<Microsoft Webhook URL>", verify="/path/to/file")
  4. Troubleshoot HTTP responses

    master

    If messages are not appearing in Teams, you can inspect the last HTTP response from the Microsoft API. The connectorcard class stores the response in the last_http_response attribute.

    import pymsteams
    
    myTeamsMessage = pymsteams.connectorcard("<Microsoft Webhook URL>")
    myTeamsMessage.text("test")
    myTeamsMessage.send()
    
    # Access the status code
    last_status_code = myTeamsMessage.last_http_response.status_code
    last_status_code = myTeamsMessage.last_http_response.status_code
  5. Send messages using an async loop

    master

    To send messages asynchronously, use the async_connectorcard class. The formatting methods are identical to the standard connectorcard. You must pass the .send() coroutine to an asyncio event loop.

    import asyncio
    import pymsteams
    
    loop = asyncio.get_event_loop()
    
    # Use async_connectorcard instead of connectorcard
    myTeamsMessage = pymsteams.async_connectorcard("<Microsoft Webhook URL>")
    
    myTeamsMessage.text("This is my message")
    
    # Pass the send coroutine to the event loop
    loop.run_until_complete(myTeamsMessage.send())
  6. Add interactive potential actions to cards

    master

    You can add potentialaction objects to allow users to interact with the card in MS Teams.

    Workflow:

    1. Create a potentialaction object with a _name.
    2. Use .addInput(type, id, label, is_required) to add input fields (e.g., TextInput, DateInput, MultichoiceInput).
    3. Use .addAction(method, label, url, [payload]) to define the action (e.g., HttpPost).
    4. For HttpPost actions using inputs, use the syntax {{id.value}} in the payload to pass the input value to your backend.
    5. Add the action to the card using .addPotentialAction(action).

    Example with Input:

    myTeamsPotentialAction1 = pymsteams.potentialaction(_name = "Add a comment")
    # 'comment' is the ID used in the payload
    myTeamsPotentialAction1.addInput("TextInput", "comment", "Add a comment here", False)
    # The payload {{comment.value}} maps to the input ID
    myTeamsPotentialAction1.addAction("HttpPost", "Add Comment", "https://...", "{{comment.value}}")
    
    myTeamsMessage.addPotentialAction(myTeamsPotentialAction1)
    myTeamsPotentialAction1 = pymsteams.potentialaction(_name = "Add a comment")
    myTeamsPotentialAction1.addInput("TextInput","comment","Add a comment here",False)
    myTeamsPotentialAction1.addAction("HttpPost","Add Comment","https://...", "{{comment.value}}")
    myTeamsMessage.addPotentialAction(myTeamsPotentialAction1)
  7. Add sections to a ConnectorCard

    master

    To create complex messages, use cardsection objects. You can add multiple sections to a single connectorcard using .addSection(section_object).

    CardSection features:

    • title(text): Section title.
    • activityTitle(text), activitySubtitle(text), activityImage(url), activityText(text): Elements for the activity area.
    • addFact(key, value): Adds key-value pairs displayed as a list.
    • text(text): Main section text.
    • addImage(url, ititle=None): Adds an image with an optional title.

    Example:

    # Create a section
    myMessageSection = pymsteams.cardsection()
    myMessageSection.title("Section title")
    myMessageSection.addFact("key", "value")
    myMessageSection.text("Section text")
    
    # Add section to the main card
    myTeamsMessage.addSection(myMessageSection)
    myMessageSection = pymsteams.cardsection()
    myMessageSection.title("Section title")
    myMessageSection.activityTitle("my activity title")
    myMessageSection.activitySubtitle("my activity subtitle")
    myMessageSection.activityImage("http://i.imgur.com/c4jt321l.png")
    myMessageSection.activityText("This is my activity Text")
    myMessageSection.addFact("this", "is fine")
    myMessageSection.text("This is my section text")
    myMessageSection.addImage("http://i.imgur.com/c4jt321l.png", ititle="This Is Fine")
    
    myTeamsMessage.addSection(myMessageSection)
  8. Format ConnectorCard messages

    master

    You can enhance your connectorcard with various formatting methods:

    • title(text): Adds a title to the card.
    • addLinkButton(text, url): Adds a button that links to a URL.
    • color(hex_code_or_string): Sets the theme color. Use a hex code without the # (e.g., "FF0000") or a color string like "red".
    • newhookurl(url): Changes the webhook URL, useful for posting the same message to multiple rooms.
    • printme(): Prints the connector card message object for debugging.
    • summary(text): Sets a summary for the message.
    myTeamsMessage.title("This is my message title")
    myTeamsMessage.addLinkButton("This is the button Text", "https://github.com/rveachkc/pymsteams/")
    myTeamsMessage.color("FF0000")
    myTeamsMessage.newhookurl("<My New URL>")
    myTeamsMessage.printme()
  9. Configure message sections with cardsection

    master

    The cardsection class allows you to define specific content blocks within a connectorcard. Each section can contain its own title, text, facts, and images.

    Methods:

    • title(stitle): Sets the section title.
    • activityTitle(sactivityTitle): Sets the title of the event/actor.
    • activitySubtitle(sactivitySubtitle): Sets a subtitle for the event.
    • activityImage(sactivityImage): Sets an image URL or base64 data URI.
    • activityText(sactivityText): Sets the full description of the action.
    • addFact(factname, factvalue): Adds a key-value pair to the section's facts list.
    • addImage(simage, ititle=None): Adds an image with an optional title.
    • text(stext): Sets the main text of the section.
    • linkButton(buttontext, buttonurl): Adds a single link button to the section.
    • enableMarkdown() / disableMarkdown(): Toggles markdown support for the section.
    • dumpSection(): Returns the dictionary representation of the section payload.
    from pymsteams import cardsection
    
    section = cardsection()
    section.title("System Status")
    section.addFact("Server", "Production-01")
    section.addFact("Status", "Online")
    section.text("All systems are operational.")
  10. Add interactive actions with potentialaction

    master

    The potentialaction class is used to create interactive elements like buttons or input forms within a Teams message. These are added to a connectorcard using addPotentialAction().

    Methods:

    • addAction(_type, _name, _target, _body=None): Adds a generic action.
    • addOpenURI(_name, _targets): Creates an OpenUri action. _targets must be a list of dictionaries, e.g., [{"os": "default", "uri": "https://..."}].
    • addInput(_type, _id, title, isMultiline=None): Adds an input field. Supports adding choices via the internal choice mechanism.
    • dumpPotentialAction(): Returns the dictionary representation of the action payload.
    from pymsteams import potentialaction
    
    # Example of an OpenURI action
    action = potentialaction("Open Dashboard")
    action.addOpenURI("View Logs", [{"os": "default", "uri": "https://logs.example.com"}])
    
    # Note: This object is then passed to connectorcard.addPotentialAction(action)
  11. Send asynchronous messages with async_connectorcard

    master

    If you are working in an asynchronous environment, use async_connectorcard to avoid blocking the event loop. This class requires the httpx library.

    Requirement: You must install the async extra for pymsteams:

    pip install pymsteams[async]

    Usage:

    • Inherits all methods from connectorcard (e.g., title, addSection).
    • Use await card.send() to dispatch the message.
    • Raises TeamsWebhookException if the response is not successful.
    import asyncio
    from pymsteams import async_connectorcard, cardsection
    
    async def send_async_msg():
        card = async_connectorcard()
        card.newhookurl("YOUR_WEBHOOK_URL")
        card.title("Async Alert")
        
        section = cardsection()
        section.text("This was sent asynchronously.")
        card.addSection(section)
        
        await card.send()
    
    asyncio.run(send_async_msg())