Skip to content
This repository has been archived by the owner on Jan 1, 2022. It is now read-only.

Commit

Permalink
Fix #5 Use message entities to find commands
Browse files Browse the repository at this point in the history
  • Loading branch information
poulad committed Aug 20, 2017
1 parent 5a254be commit ebf0458
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 44 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,6 @@ ModelManifest.xml

# Settings for development time
appsettings.*.json

# Rider IDE
.idea
2 changes: 1 addition & 1 deletion sample/SampleBots/Bots/EchoBot/EchoerBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public EchoerBot(IOptions<BotOptions<EchoerBot>> botOptions, ILogger<EchoerBot>
_logger = logger;
}

public override async Task HandleUnknownMessage(Update update)
public override async Task HandleUnknownUpdate(Update update)
{
_logger.LogWarning("Unable to handle an update");

Expand Down
2 changes: 1 addition & 1 deletion sample/SampleBots/Bots/GreeterBot/GreeterBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public GreeterBot(IOptions<BotOptions<GreeterBot>> botOptions, ILogger<GreeterBo
_logger = logger;
}

public override async Task HandleUnknownMessage(Update update)
public override async Task HandleUnknownUpdate(Update update)
{
_logger.LogWarning("Unable to handle an update");

Expand Down
38 changes: 33 additions & 5 deletions sample/SampleEchoBot/EchoBot.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,55 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Telegram.Bot.Framework;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace SampleEchoBot
{
public class EchoBot : BotBase<EchoBot>
{
public EchoBot(IOptions<BotOptions<EchoBot>> botOptions)
private readonly ILogger<EchoBot> _logger;

public EchoBot(IOptions<BotOptions<EchoBot>> botOptions, ILogger<EchoBot> logger)
: base(botOptions)
{

_logger = logger;
}

public override Task HandleUnknownMessage(Update update)
public override async Task HandleUnknownUpdate(Update update)
{
return Task.CompletedTask;
_logger.LogWarning("Unable to handle update of type `{0}`", update.Type);

string text;
int replyToMesageId = default(int);

switch (update.Type)
{
case UpdateType.MessageUpdate when
new[] {ChatType.Private, ChatType.Group, ChatType.Supergroup}.Contains(update.Message.Chat.Type):
text = $"Unable to handle message update of type `{update.Message.Type}`.";
replyToMesageId = update.Message.MessageId;
break;
default:
text = null;
break;
}

if (text != null)
{
await Client.SendTextMessageAsync(update.Message.Chat.Id, text, ParseMode.Markdown,
replyToMessageId: replyToMesageId);
}
}

public override Task HandleFaultedUpdate(Update update, Exception e)
{
_logger.LogError($"Exception occured in handling update of type `{0}`: {1}", update.Type, e.Message);

return Task.CompletedTask;
}
}
}
}
4 changes: 1 addition & 3 deletions sample/SampleEchoBot/SampleEchoBot.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
Expand All @@ -11,5 +10,4 @@
<ItemGroup>
<ProjectReference Include="..\..\src\Telegram.Bot.Framework\Telegram.Bot.Framework.csproj" />
</ItemGroup>

</Project>
</Project>
2 changes: 1 addition & 1 deletion sample/SampleGames/Bots/CrazyCircle/CrazyCircleBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public CrazyCircleBot(IOptions<BotOptions<CrazyCircleBot>> botOptions,
_logger = logger;
}

public override Task HandleUnknownMessage(Update update)
public override Task HandleUnknownUpdate(Update update)
{
_logger.LogWarning("Don't know how to handle update of type `{0}`", update.Type);
return Task.CompletedTask;
Expand Down
2 changes: 1 addition & 1 deletion src/Telegram.Bot.Framework/BotBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ protected BotBase(IOptions<BotOptions<TBot>> botOptions)
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
public abstract Task HandleUnknownMessage(Update update);
public abstract Task HandleUnknownUpdate(Update update);

/// <summary>
/// Receives the update when the hanlding process throws an exception for the update
Expand Down
3 changes: 1 addition & 2 deletions src/Telegram.Bot.Framework/BotManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Microsoft.Extensions.Options;
using Telegram.Bot.Framework.Abstractions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace Telegram.Bot.Framework
{
Expand Down Expand Up @@ -96,7 +95,7 @@ public async Task HandleUpdateAsync(Update update)

if (!anyHandlerExists)
{
await _bot.HandleUnknownMessage(update);
await _bot.HandleUnknownUpdate(update);
}
}
catch (Exception e)
Expand Down
29 changes: 22 additions & 7 deletions src/Telegram.Bot.Framework/CommandBase.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System.Text.RegularExpressions;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Telegram.Bot.Framework.Abstractions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace Telegram.Bot.Framework
{
Expand Down Expand Up @@ -72,7 +74,7 @@ protected virtual TCommandArgs ParseInput(Update update)
RegexOptions.IgnoreCase);
if (argsInputMatch.Success)
{
args.ArgsInput = argsInputMatch.Groups[1].Value; // todo unit test
args.ArgsInput = argsInputMatch.Groups[1].Value; // ToDo unit test
}

return args;
Expand All @@ -85,12 +87,25 @@ protected virtual TCommandArgs ParseInput(Update update)
/// <returns><value>true</value> if this command should handle the update; otherwise <value>false</value></returns>
protected virtual bool CanHandleCommand(Update update)
{
var canHandle = false;
if (!string.IsNullOrEmpty(update.Message?.Text))
bool canHandle = false;

var zippedMessageEntity = update.Message.Entities
.Zip(update.Message.EntityValues, (entity, val) => new
{
MessageEntity = entity,
Value = val
})
.SingleOrDefault(zipped =>
zipped.MessageEntity.Type == MessageEntityType.BotCommand &&
zipped.MessageEntity.Offset == 0
);

if (zippedMessageEntity != null)
{
canHandle = Regex.IsMatch(update.Message.Text,
$@"^\s*/{Name}(?:(?:@{Bot.UserName}(?:\s+.*)?)|\s+.*|)\s*$", RegexOptions.IgnoreCase);
canHandle = Regex.IsMatch(zippedMessageEntity.Value,
$@"^/{Name}(?:@{Bot.UserName})?$", RegexOptions.IgnoreCase);
}

return canHandle;
}

Expand All @@ -102,4 +117,4 @@ protected virtual bool CanHandleCommand(Update update)
/// <returns>Result of handling this update</returns>
public abstract Task<UpdateHandlingResult> HandleCommand(Update update, TCommandArgs args);
}
}
}
4 changes: 2 additions & 2 deletions src/Telegram.Bot.Framework/SetGameScoreDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Telegram.Bot.Framework
/// Data transfer object containing user's score
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class SetGameScoreDto // todo make it internal
public class SetGameScoreDto // ToDo make it internal
{
/// <summary>
/// Encoded and encrypted player id
Expand All @@ -18,6 +18,6 @@ public class SetGameScoreDto // todo make it internal
/// User's score
/// </summary>
[JsonProperty(Required = Required.Always)]
public int Score { get; set; } // todo make nullable. and add validations
public int Score { get; set; } // ToDo make nullable. and add validations
}
}
10 changes: 2 additions & 8 deletions src/Telegram.Bot.Framework/Telegram.Bot.Framework.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<PackageId>Telegram.Bot.Framework</PackageId>
<TargetFramework>netstandard1.6</TargetFramework>
Expand All @@ -21,15 +20,12 @@
<Product>Telegram.Bot.Framework</Product>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>bin\Debug\netstandard1.6\Telegram.Bot.Framework.xml</DocumentationFile>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DocumentationFile>bin\Release\netstandard1.6\Telegram.Bot.Framework.xml</DocumentationFile>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.DataProtection.Abstractions" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="1.1.2" />
Expand All @@ -38,11 +34,9 @@
<PackageReference Include="Microsoft.Extensions.Options" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.2" />
<PackageReference Include="System.ValueTuple" Version="4.3.1" />
<PackageReference Include="Telegram.Bot" Version="13.1.0" />
<PackageReference Include="Telegram.Bot.Core" Version="13.2.1" />
</ItemGroup>

<ItemGroup>
<!--<ProjectReference Include="..\..\..\telegram.bot-fork\src\Telegram.Bot\Telegram.Bot.csproj" />-->
</ItemGroup>

</Project>
</Project>
37 changes: 25 additions & 12 deletions test/Telegram.Bot.Framework.Tests/CommandBaseTests.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
using Moq;
using System;
using System.Collections.Generic;
using Moq;
using Telegram.Bot.Framework.Abstractions;
using Telegram.Bot.Framework.Tests.Helpers;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Xunit;

namespace Telegram.Bot.Framework.Tests
{
public class CommandBaseTests
{
[Theory(DisplayName = "Accept handling specific commands")]
[InlineData("/test")]
[InlineData("/test ")]
[InlineData("/test abc")]
[InlineData("/test@test_bot")]
[InlineData("/test@test_bot ")]
[InlineData("/test@test_bot !")]
public void ShouldAcceptHandlingAll(string text)
[InlineData("/test", "/test")]
[InlineData("/test ", "/test")]
[InlineData("/test abc", "/test")]
[InlineData("/TesT", "/tESt")]
[InlineData("/test@test_bot", "/test@test_bot")]
[InlineData("/test@test_bot ", "/test@test_bot")]
[InlineData("/test@test_bot !", "/test@test_bot")]
public void Should_Accept_Handling_All(string text, string commandValue)
{
const string botUsername = "Test_Bot";
var mockBot = new Mock<IBot>();
Expand All @@ -27,7 +31,16 @@ public void ShouldAcceptHandlingAll(string text)
Message = new Message
{
Text = text,
}
Entities = new List<MessageEntity>
{
new MessageEntity
{
Type = MessageEntityType.BotCommand,
Offset = text.IndexOf(commandValue, StringComparison.OrdinalIgnoreCase),
Length = commandValue.Length
},
},
},
};
var sut = new TestCommand("Test");

Expand All @@ -45,7 +58,7 @@ public void ShouldAcceptHandlingAll(string text)
[InlineData("/testt")]
[InlineData("/@test_bot")]
[InlineData("/tes@test_bot")]
public void ShouldRefuseHandlingTextMessages(string text)
public void Should_Refuse_Handling_Text_Messages(string text)
{
const string botUsername = "Test_Bot";
var mockBot = new Mock<IBot>();
Expand All @@ -57,7 +70,7 @@ public void ShouldRefuseHandlingTextMessages(string text)
Message = new Message
{
Text = text,
}
},
};
var sut = new TestCommand("Test");

Expand All @@ -66,4 +79,4 @@ public void ShouldRefuseHandlingTextMessages(string text)
Assert.False(actual);
}
}
}
}
2 changes: 1 addition & 1 deletion test/Telegram.Bot.Framework.Tests/Helpers/TestBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public TestBot(IOptions<BotOptions<TestBot>> botOptions)

}

public override Task HandleUnknownMessage(Update update)
public override Task HandleUnknownUpdate(Update update)
{
throw new NotImplementedException();
}
Expand Down

0 comments on commit ebf0458

Please sign in to comment.