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

Pdding Robot Laravel Package

aping/pdding-robot

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require aping/pdding-robot
    

    or add to composer.json:

    "require": {
        "aping/pdding-robot": "^1.0"
    }
    
  2. First Usage: Initialize the client with your DingTalk robot token and secret:

    use Aping\PddingRobot\Fast;
    
    $robot = Fast::new('your_robot_token', 'your_signature_secret');
    
  3. Send First Message:

    $response = $robot->sendText('Hello, this is my first DingTalk message!');
    

Where to Look First

  • README.md: For basic usage examples and message types.
  • Fast class: Core class for sending messages.
  • DingTalk API Docs: Official Reference for message structure and validation rules.

Implementation Patterns

Common Workflows

  1. Sending Notifications:

    $robot->sendText("Deployment failed on staging! Check logs: [link](https://example.com/logs)");
    
  2. Structured Alerts (Markdown):

    $robot->sendMarkdown(
        "System Alert",
        "#### **Database Connection Issue**\n\n- **Status**: Critical\n- **Time**: " . now() . "\n- **Action**: Restart service or check config\n\n> ![warning](https://example.com/warning.png)"
    );
    
  3. Interactive Cards (ActionCard):

    $robot->sendSingleActionCard(
        "New Feature Release",
        "The v2.0 release is live! Key improvements:\n- Faster API responses\n- New dashboard UI\n\n![screenshot](@lADOpwk3K80C0M0FoA)",
        "View Changelog",
        "https://example.com/changelog"
    );
    
  4. Multi-Option Cards:

    $robot->sendMultiActionCard(
        "Deploy Options",
        "Select environment for deployment:",
        [
            ['title' => 'Staging', 'actionURL' => 'https://staging.example.com/deploy'],
            ['title' => 'Production', 'actionURL' => 'https://prod.example.com/deploy'],
        ]
    );
    
  5. Feed Cards (Multiple Items):

    $robot->sendFeedCard([
        [
            'title' => 'Server #1',
            'messageUrl' => 'https://monitor.example.com/server/1',
            'picUrl' => 'https://example.com/server1.png',
        ],
        [
            'title' => 'Server #2',
            'messageUrl' => 'https://monitor.example.com/server/2',
            'picUrl' => 'https://example.com/server2.png',
        ],
    ]);
    

Integration Tips

  1. Environment Configuration: Store tokens/secrets in .env:

    DINGTALK_ROBOT_TOKEN=your_token_here
    DINGTALK_SECRET=your_secret_here
    

    Load via Laravel's config() helper:

    $robot = Fast::new(config('services.dingtalk.token'), config('services.dingtalk.secret'));
    
  2. Error Handling:

    try {
        $response = $robot->sendText("Critical Alert");
        if (!$response->isOk()) {
            Log::error("DingTalk Error: " . $response->getError());
        }
    } catch (\Exception $e) {
        Log::error("DingTalk SDK Error: " . $e->getMessage());
    }
    
  3. Rate Limiting:

    • DingTalk robots have rate limits. Cache responses or batch messages:
    $messages = collect([...]);
    $messages->chunk(5)->each(function ($chunk) use ($robot) {
        foreach ($chunk as $message) {
            $robot->sendText($message);
        }
        sleep(1); // Avoid hitting rate limits
    });
    
  4. Dynamic Content: Use Laravel Blade or templating for dynamic messages:

    $robot->sendMarkdown(
        "Build Status",
        view('notifications.dingtalk.build_status', ['build' => $build])->render()
    );
    
  5. Webhook Integration: Trigger messages from Laravel events or jobs:

    // In an Event Listener
    public function handle(DeploymentFailed $event) {
        $robot = app(Fast::class);
        $robot->sendText("Deployment failed: " . $event->error);
    }
    

Gotchas and Tips

Pitfalls

  1. Secret Validation:

    • The SDK requires a secret for signing requests. If omitted, DingTalk will reject the message.
    • Fix: Always pass the secret, even if unused (e.g., Fast::new(token, '')).
  2. Message Length Limits:

    • Text: Max 2048 characters.
    • Markdown: Max 2048 characters (including headers/images).
    • ActionCard: Title (40 chars), description (2048 chars), buttons (2 buttons max).
    • FeedCard: 8 items max, each with 1000 chars for messageUrl.
    • Fix: Truncate content or split into multiple messages.
  3. Image URLs:

    • DingTalk only supports internal or public URLs for images (e.g., @lADOpwk3K80C0M0FoA for internal files).
    • Fix: Use https:// for public images or upload to DingTalk’s internal file system.
  4. Response Handling:

    • isOk() returns true for HTTP 200, but DingTalk may still return a non-success payload (e.g., errcode: 1).
    • Fix: Check $response->getRaw() for DingTalk’s errcode field:
    $data = json_decode($response->getRaw(), true);
    if ($data['errcode'] !== 0) {
        // Handle DingTalk-specific errors
    }
    
  5. Deprecation:

    • The package is unmaintained (last release: 2020). Features like Rich Media may not be supported.
    • Fix: Fork the repo or use the official PHP SDK for newer DingTalk APIs.

Debugging Tips

  1. Enable Verbose Logging:

    $robot = Fast::new(token, secret, [
        'debug' => true, // Enable if supported (check source)
    ]);
    
    • Alternative: Inspect raw requests/responses:
    $response = $robot->sendText("Test");
    Log::debug("DingTalk Response:", $response->getRaw());
    
  2. Test with Postman:

    • Replicate the SDK’s request structure to verify payloads:
    POST https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN
    Headers:
      Content-Type: application/json
    Body:
      {
        "msgtype": "text",
        "text": { "content": "Hello" }
      }
    
  3. Common Errors:

    • errcode: 8: Invalid access_token (check token permissions in DingTalk admin).
    • errcode: 14: Invalid signature (ensure secret matches DingTalk settings).
    • errcode: 10001: Rate limit exceeded (add delays between requests).

Extension Points

  1. Custom Message Types:

    • Extend the Fast class to add unsupported message types (e.g., sendFile):
    class ExtendedFast extends Fast {
        public function sendFile($fileUrl) {
            $payload = [
                'msgtype' => 'file',
                'file' => ['file_url' => $fileUrl],
            ];
            return $this->send($payload);
        }
    }
    
  2. Middleware for Requests:

    • Wrap the SDK to add headers or logging:
    class DingTalkMiddleware {
        public function send(Fast $robot, $payload) {
            $payload['agent_id'] = 1; // Add custom fields
            return $robot->send($payload);
        }
    }
    
  3. Queue Jobs:

    • Offload messages to Laravel queues to avoid timeouts:
    class SendDingTalkJob implements ShouldQueue {
        public function handle() {
            $robot = new Fast(config('dingtalk.token'), config('dingtalk.secret'));
            $robot->sendText("Queued Message");
        }
    }
    
  4. **F

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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky