Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/SampleApp/Sample/ConsoleRenderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System.Runtime.CompilerServices;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;

namespace Devlooped.WhatsApp;

static class ConsoleRenderExtensions
{
/// <summary>
/// Renders text message and responses to the console as JSON for
/// troubleshooting.
/// </summary>
public static WhatsAppHandlerBuilder UseConsoleRender(this WhatsAppHandlerBuilder builder)
=> builder.Use((inner, services)
=> new ConsoleRenderHandler(inner, services.GetRequiredService<IWhatsAppClient>()));

/// <summary>
/// Checks whether the given service number ID is a CLI local endpoint.
/// </summary>
static bool IsCLI(this string serviceId)
=> serviceId.StartsWith("http://localhost", StringComparison.OrdinalIgnoreCase);

class ConsoleRenderHandler(IWhatsAppHandler inner, IWhatsAppClient client) : DelegatingWhatsAppHandler(inner)
{
public override async IAsyncEnumerable<Response> HandleAsync(IEnumerable<IMessage> messages, [EnumeratorCancellation] CancellationToken cancellation = default)
{
var user = messages.OfType<UserMessage>().LastOrDefault();
if (user != null && user.Service.Id.IsCLI())
{
await client.SendAsync(user,
$"""
```
{JsonSerializer.Serialize(
messages.Where(x => x is UserMessage || x is TextResponse),
JsonContext.DefaultOptions)}
```
""");
}

var responses = new List<Response>();

await foreach (var response in base.HandleAsync(messages, cancellation))
{
if (response is TextResponse)
responses.Add(response);

yield return response;
}

if (user != null && user.Service.Id.IsCLI())
{
await client.SendAsync(user,
$"""
```
{JsonSerializer.Serialize(responses, JsonContext.DefaultOptions)}
```
""");
}
}
}
}
2 changes: 2 additions & 0 deletions src/SampleApp/Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@
.Use(EchoAndHandle)
.UseConversation(conversationWindowSeconds: 300 /* default */)
.UseConsole();
// Uncomment next line to render a JSON of text message/responses
//.UseConsoleRender();

// If event grid is set up, switch to processing messages using that
if (builder.Configuration["EventGrid:Topic"] is { Length: > 0 } topic &&
Expand Down