You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Actions Trivia模板项目中根据答对次数发送HTTP请求?

Hey there! Great question—yes, you absolutely can send HTTP requests from your Google Actions Trivia app, and tying that trigger to the number of correct answers is totally feasible. Let me walk you through the details and implementation steps.

Can You Send HTTP Requests from Google Actions Trivia Apps?

Absolutely. Google Actions (whether you're using the Trivia template with Actions SDK, Dialogflow, or Actions Builder) supports making HTTP calls via your webhook logic. Most developers use Node.js for their webhooks, where you can leverage built-in APIs like fetch (available in Node.js 18+) or popular libraries like axios to send requests to external APIs.

How to Trigger HTTP Requests Based on Correct Answer Count

Here's a step-by-step breakdown to implement this:

1. Track Correct Answer Count

First, you need to persist the number of correct answers across user interactions. Google Actions provides two storage options:

  • conv.sessionStorage: Stores data only for the current conversation session (resets when the user ends the chat).
  • conv.user.storage: Persists data across multiple sessions for the same user (requires user consent if storing sensitive info, but a simple count is low-risk).

Every time the user answers correctly, increment this count in your handler.

2. Define Trigger Conditions

Decide on a threshold (e.g., 5 correct answers) that will trigger the HTTP request. Check this count right after confirming a correct answer.

3. Implement the HTTP Request

Use async/await to handle the asynchronous HTTP call—critical, since webhooks need to wait for the request to complete before sending a response to Google Assistant.

Example Code Snippet (Node.js Actions SDK)

// Handler for the "correct answer" intent (adjust based on your Trivia template's intent names)
app.intent('Answer Correct', async (conv) => {
  // Initialize or increment the correct answer count
  conv.user.storage.correctAnswers = (conv.user.storage.correctAnswers || 0) + 1;
  
  // Send a positive response to the user
  conv.add('Perfect! That\'s the right answer.');
  
  // Check if we've hit our trigger threshold (e.g., 3 correct answers)
  const TRIGGER_THRESHOLD = 3;
  if (conv.user.storage.correctAnswers === TRIGGER_THRESHOLD) {
    try {
      // Send HTTP POST request to your external endpoint
      const apiResponse = await fetch('https://your-api-url.com/your-endpoint', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          // Add any auth headers if your API requires them, e.g.:
          // 'Authorization': 'Bearer YOUR_API_TOKEN'
        },
        body: JSON.stringify({
          userId: conv.user.id,
          totalCorrect: conv.user.storage.correctAnswers,
          timestamp: new Date().toISOString()
        })
      });
      
      if (apiResponse.ok) {
        conv.add(`Wow, you've got ${TRIGGER_THRESHOLD} correct answers in a row! We've sent your progress to our system. Keep it up!`);
      } else {
        // Handle non-successful API responses
        console.error('API request failed:', apiResponse.statusText);
        conv.add(`You just hit ${TRIGGER_THRESHOLD} correct answers! We had a small issue updating our system, but you're crushing this trivia.`);
      }
    } catch (error) {
      // Handle network errors or exceptions
      console.error('Error sending HTTP request:', error);
      conv.add(`You nailed ${TRIGGER_THRESHOLD} correct answers! We ran into a tiny glitch, but don't let that stop you—you're doing amazing.`);
    }
  }
});

Key Notes to Remember

  • Error Handling: Always wrap HTTP calls in try/catch blocks to avoid crashing your webhook if the API is down or unreachable.
  • Storage Consent: If using conv.user.storage for persistent data, ensure compliance with Google's privacy policies—though a simple answer count is generally fine.
  • API Authentication: If your external API requires auth, include necessary headers (like bearer tokens) in your request.
  • Actions Builder Users: If using the visual Actions Builder, create a webhook (via Cloud Functions or your own server), link it to the "correct answer" intent, then implement the count tracking and HTTP logic in that webhook.

内容的提问来源于stack exchange,提问作者Suzuki Yoshihisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:20:31