Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Ding Robot Laravel Package

aping/laravel-ding-robot

Laravel DingTalk Robot SDK for sending messages via one or multiple DingTalk robots. Provides a Ding facade/app('ding') helpers to send Text, Link, Markdown, ActionCard (single/multi), and FeedCard message types, with response helpers to check success and errors.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aping/laravel-ding-robot
    

    Publish the config file:

    php artisan vendor:publish --provider="Aping\DingRobot\DingRobotServiceProvider"
    
  2. Configuration Edit config/ding-robot.php with your DingTalk (DingTalk is a Chinese enterprise messaging platform) credentials:

    'access_token' => env('DING_ROBOT_ACCESS_TOKEN'),
    'webhook' => env('DING_ROBOT_WEBHOOK'),
    
  3. First Use Case Send a simple text message via Tinker or a controller:

    use Aping\DingRobot\Facades\DingRobot;
    
    DingRobot::send([
        'text' => 'Hello, DingTalk! This is my first message.',
        'isAtAll' => false,
    ]);
    

Where to Look First

  • Facade: Aping\DingRobot\Facades\DingRobot – The primary entry point for sending messages.
  • Config File: config/ding-robot.php – Centralized configuration for tokens, webhooks, and defaults.
  • Service Provider: Aping\DingRobot\DingRobotServiceProvider – Registers the facade and binds the service.

Implementation Patterns

Core Workflows

1. Sending Messages

Use the facade to send different types of messages (text, markdown, link, etc.):

// Text message
DingRobot::send([
    'text' => 'Build <font color=\"warning\">#123</font> failed.',
    'isAtAll' => true,
]);

// Markdown message
DingRobot::send([
    'markdown' => '### Alert\n> Build failed for project `example`.',
    'isAtAll' => false,
]);

// Link message
DingRobot::send([
    'link' => [
        'text' => 'Click to view',
        'url' => 'https://example.com',
        'picUrl' => 'https://example.com/image.png',
    ],
]);

2. Sending Actions (e.g., Alerts)

Trigger actions like alerts or reminders:

DingRobot::send([
    'action' => 'alert',
    'text' => 'Server down!',
    'isAtAll' => true,
]);

3. Sending to Specific Users

Use atMobiles to mention specific users:

DingRobot::send([
    'text' => 'Hey @13800000000, check this out!',
    'isAtAll' => false,
    'atMobiles' => ['13800000000', '13900000000'],
]);

4. Sending Files

Attach files to messages:

DingRobot::send([
    'text' => 'Log file attached.',
    'file' => [
        'name' => 'error.log',
        'path' => storage_path('logs/error.log'),
    ],
]);

Integration Tips

1. Queueing Messages

Offload DingTalk notifications to a queue (e.g., ding-robot queue) to avoid blocking the request:

DingRobot::queueSend([
    'text' => 'This will be sent later.',
]);

2. Logging Failures

Wrap calls in a try-catch block to log failures:

try {
    DingRobot::send(['text' => 'Critical alert!']);
} catch (\Exception $e) {
    \Log::error('DingTalk notification failed: ' . $e->getMessage());
}

3. Dynamic Configuration

Override defaults per message:

DingRobot::send([
    'text' => 'Custom message',
    'isAtAll' => false,
], [
    'webhook' => 'https://oapi.dingtalk.com/robot/special_webhook',
]);

4. Event-Based Notifications

Trigger DingTalk messages from Laravel events (e.g., job.failed):

use Illuminate\Queue\Events\JobFailed;

Event::listen(JobFailed::class, function (JobFailed $event) {
    DingRobot::send([
        'text' => 'Job failed: ' . $event->job->payload['command'],
    ]);
});

5. Testing

Mock the facade in tests:

$this->mock(DingRobot::class)->shouldReceive('send')->once();

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • DingTalk access tokens expire. If messages suddenly stop working, regenerate the token in the DingTalk robot settings and update config/ding-robot.php.
    • Fix: Implement a token refresh mechanism or monitor token validity.
  2. Webhook URL Limits

    • DingTalk webhooks may have rate limits (e.g., 1 message per second). Exceeding this will fail silently.
    • Fix: Queue messages and implement retries with exponential backoff.
  3. Markdown Formatting

    • DingTalk’s markdown supports limited formatting. Complex HTML or unsupported tags (e.g., <script>) will break rendering.
    • Fix: Test markdown in DingTalk’s web interface first.
  4. File Size Limits

    • Attached files must be < 10MB. Larger files will fail.
    • Fix: Compress files or split them into chunks.
  5. At-All vs. At-Mobiles

    • isAtAll mentions all users subscribed to the robot, while atMobiles mentions specific users. Misusing these can spam unintended recipients.
    • Fix: Double-check atMobiles arrays before sending.

Debugging Tips

  1. Enable Debugging Add this to config/ding-robot.php to log raw responses:

    'debug' => env('APP_DEBUG', false),
    
  2. Check Raw Responses Inspect the HTTP response from DingTalk to diagnose issues:

    try {
        $response = DingRobot::send(['text' => 'Test']);
        \Log::debug('DingTalk response:', ['response' => $response]);
    } catch (\Exception $e) {
        \Log::error('DingTalk error:', ['error' => $e->getMessage()]);
    }
    
  3. Validate Webhook URL Ensure the webhook URL in config/ding-robot.php is correct and accessible. Test it manually via curl:

    curl -X POST \
      -H 'Content-Type: application/json' \
      -d '{"text":"{\"text\":\"Test\"}"}' \
      https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN
    

Extension Points

  1. Custom Message Types Extend the package by adding new message types (e.g., feedCard):

    // In a service or trait
    public function feedCard(array $data)
    {
        return $this->send(array_merge($data, ['msgtype' => 'feedCard']));
    }
    
  2. Middleware for Messages Add validation or transformation logic before sending:

    DingRobot::extend(function ($message) {
        if (isset($message['text']) && strpos($message['text'], 'URGENT') !== false) {
            $message['isAtAll'] = true;
        }
        return $message;
    });
    
  3. Custom HTTP Client Override the default Guzzle client for logging or retry logic:

    // In a service provider
    $this->app->bind('dingRobot.httpClient', function () {
        return new \GuzzleHttp\Client([
            'timeout' => 10,
            'on_stats' => function ($event) {
                \Log::debug('DingTalk HTTP request', $event->getStats());
            },
        ]);
    });
    
  4. Local Testing with Mock Webhooks Use a local DingTalk mock server (e.g., ding-mock) to test messages without hitting DingTalk’s API.


Config Quirks

  1. Environment Variables Ensure .env has:

    DING_ROBOT_ACCESS_TOKEN=your_token_here
    DING_ROBOT_WEBHOOK=https://oapi.dingtalk.com/robot/send
    
  2. Default Values Override defaults in config/ding-robot.php:

    'defaults' => [
        'isAtAll' => false, // Default to not @all users
        'atMobiles' => [],  // No default @mobiles
    ],
    
  3. Secure Token Storage Avoid hardcoding tokens. Use Laravel’s .env

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity