Daily Dog с не запущенными функциями C#, WhatsApp и Azure - PullRequest
0 голосов
/ 06 мая 2020

Надеюсь, кто-то может мне помочь с этим:

Я пытался немного узнать о azure функциях для создания чат-бота с помощью twilio.

Я следил за этим блогом руководство:

https://www.twilio.com/blog/draft-daily-dog-with-c-whatsapp-and-azure-functions-2

Я выполнил все шаги правильно, но когда я пытаюсь запустить его, я получаю сообщение об ошибке ...

================================================== ===

2020-05-06T01:04:27.202 [Error] Function compilation error
Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed.
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken) at D:\a\1\s\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 314
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionLoader`1.GetFunctionTargetAsync[T](Int32 attemptCount) at D:\a\1\s\src\WebJobs.Script\Description\FunctionLoader.cs : 55
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetFunctionTargetAsync(Boolean isInvocation) at D:\a\1\s\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 183
2020-05-06T01:04:27.247 [Warning] D:\home\site\wwwroot\TimerTrigger1\sendMessage.csx(8,26): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
2020-05-06T01:04:27.273 [Error] run.csx(19,29): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
2020-05-06T01:04:27.324 [Error] run.csx(25,9): error CS0103: The name 'responseMessage' does not exist in the current context
2020-05-06T01:04:27.354 [Error] run.csx(27,31): error CS0103: The name 'responseMessage' does not exist in the current context
2020-05-06T01:04:27.395 [Error] run.csx(27,25): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
2020-05-06T01:04:27.430 [Error] run.csx(31,5): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
2020-05-06T01:04:27.478 [Error] Executed 'Functions.TimerTrigger1' (Failed, Id=24245bff-8b18-47e2-8019-fec74f735540)
Script compilation failed.

Я пишу "скопировать" следующие три файла ...


run.csx

#r "Newtonsoft.Json"
#load "sendMessage.csx"

using System;
using System.Net;
using System.Net.Http.Headers;
using Newtonsoft.Json;

public static void Run(TimerInfo myTimer, ILogger log)
{
    var imageUrl = "https://images.dog.ceo/breeds/pinscher-miniature/n02107312_4650.jpg";

    using(var client = new HttpClient())
    {
      var apiEndPoint = "https://dog.ceo/api/breeds/image/random";
      client.BaseAddress = new Uri(apiEndPoint);
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

      var responseMessage = await
          client
              .GetAsync(apiEndPoint);

    }

    if (responseMessage.IsSuccessStatusCode)
    {
      var jsonContent = await responseMessage.Content.ReadAsStringAsync();
      dynamic data = JsonConvert.DeserializeObject(jsonContent);
      imageUrl = data.message;       
    }
    await SendMessage(imageUrl);
}

sendMessage.csx


using System;
using System.Net;
using System.Net.Http.Headers;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static async Task SendMessage(string imageUrl)
{

   TwilioClient.Init(
              Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"),
              Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN")

        );

   var message =  MessageResource.Create(
        from: new PhoneNumber("whatsapp:+14155238886"),
        to: new PhoneNumber("whatsapp:" + Environment.GetEnvironmentVariable("MY_PHONE_NUMBER")),
        body: "Your daily cat!",
        mediaUrl: new List<Uri>{new Uri(imageUrl)}

        );

    Console.WriteLine("Message SID: " + message.Sid);

}

function.proj

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>  
    <ItemGroup>
        <PackageReference Include="twilio" Version="5.27.2"/>
    </ItemGroup>
</Project>

Не могли бы вы посоветовать мне, что я делаю не так?

Буду очень признателен за вашу помощь!

Спасибо !!

1 Ответ

0 голосов
/ 06 мая 2020

Есть много ошибок компиляции, как показано в сообщениях об ошибках,

  1. Вы можете использовать await только в асинхронном c методе
  2. вы должны объявить responseMessage глобально
...