Skip to content

Commit

Permalink
Add Keyboard Builders, clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
Eptagone committed Feb 3, 2024
1 parent 329ff1b commit 0259beb
Show file tree
Hide file tree
Showing 369 changed files with 5,200 additions and 4,088 deletions.
2 changes: 1 addition & 1 deletion src/examples/BotTemplate/BotTemplateSample.csproj
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>BotTemplateSample</RootNamespace>
<Nullable>annotations</Nullable>
</PropertyGroup>
Expand Down
141 changes: 77 additions & 64 deletions src/examples/BotTemplate/MyBot.cs
Expand Up @@ -12,77 +12,90 @@

namespace BotTemplateSample
{
public sealed class MyBot : SimpleTelegramBotBase
{
public static readonly TelegramBotClient Bot = new("<BOT TOKEN>");
public static readonly User Me = Bot.GetMe();
public sealed class MyBot : SimpleTelegramBotBase
{
public static readonly TelegramBotClient Bot = new("<BOT TOKEN>");
public static readonly User Me = Bot.GetMe();

public override void OnUpdate(Update update)
{
Console.WriteLine("New update with id: {0}. Type: {1}", update?.UpdateId, update.GetUpdateType());
base.OnUpdate(update);
}
public MyBot()
{
// Provides a better way to extract commands using regular expressions.
this.SetCommandExtractor(Me.Username, true);
}

protected override void OnMessage(Message message)
{
// Ignore user 777000 (Telegram)
if (message?.From.Id == TelegramConstants.TelegramId)
{
return;
}
public override void OnUpdate(Update update)
{
Console.WriteLine(
"New update with id: {0}. Type: {1}",
update?.UpdateId,
update.GetUpdateType()
);
base.OnUpdate(update);
}

Console.WriteLine("New message from chat id: {0}", message.Chat.Id);
Console.WriteLine("Message Text: {0}", message.Text ?? "|:O");
protected override void OnMessage(Message message)
{
// Ignore user 777000 (Telegram)
if (message?.From.Id == TelegramConstants.TelegramId)
{
return;
}

if (message.Chat.Type == ChatType.Private) // Private Chats
{
// Make something
}
else // Group chats
{
Console.WriteLine("New message from chat id: {0}", message.Chat.Id);
Console.WriteLine("Message Text: {0}", message.Text ?? "|:O");

}
// Check if the message contains a command
if (message.Entities.Any(e => e.Type == "bot_command"))
{
// If the command includes a mention, you should verify that it is for your bot, otherwise you will need to ignore the command.
var pattern = string.Format(@"^\/(?<COMMAND>\w*)(?:|@{0})(?:$|\s(?<PARAMETERS>.*))", Me.Username);
var match = Regex.Match(message.Text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
var command = match.Groups.Values.Single(v => v.Name == "COMMAND").Value; // Get command name
var @params = match.Groups.Values.SingleOrDefault(v => v.Name == "PARAMETERS")?.Value;
if (message.Chat.Type == ChatTypes.Private) // Private Chats
{
// Make something
}
else // Group chats
{ }
// Check if the message contains a command
if (message.Entities.Any(e => e.Type == "bot_command"))
{
// If the command includes a mention, you should verify that it is for your bot, otherwise you will need to ignore the command.
var pattern = string.Format(
@"^\/(?<COMMAND>\w*)(?:|@{0})(?:$|\s(?<PARAMETERS>.*))",
Me.Username
);
var match = Regex.Match(message.Text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
var command = match.Groups.Values.Single(v => v.Name == "COMMAND").Value; // Get command name
var @params = match
.Groups.Values.SingleOrDefault(v => v.Name == "PARAMETERS")
?.Value;

Console.WriteLine("New command: {0}", command);
this.OnCommand(message, command, @params);
}
}
}
Console.WriteLine("New command: {0}", command);
this.OnCommand(message, command, @params);
}
}
}

protected override void OnCommand(Message message, string cmd, string parameters)
{
var args = parameters.Split(' ', StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Params: {0}", args.Length);
switch (cmd)
{
case "hello":
var hello = string.Format("Hello World, {0}!", message.From.FirstName);
Bot.SendMessage(message.Chat.Id, hello);
break;
}
}
protected override void OnCommand(Message message, string cmd, string parameters)
{
var args = parameters.Split(' ', StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Params: {0}", args.Length);
switch (cmd)
{
case "hello":
var hello = string.Format("Hello World, {0}!", message.From.FirstName);
Bot.SendMessage(message.Chat.Id, hello);
break;
}
}

protected override void OnBotException(BotRequestException exp)
{
Console.WriteLine("New BotException: {0}", exp?.Message);
Console.WriteLine("Error Code: {0}", exp.ErrorCode);
Console.WriteLine();
}
protected override void OnBotException(BotRequestException exp)
{
Console.WriteLine("New BotException: {0}", exp?.Message);
Console.WriteLine("Error Code: {0}", exp.ErrorCode);
Console.WriteLine();
}

protected override void OnException(Exception exp)
{
Console.WriteLine("New Exception: {0}", exp?.Message);
Console.WriteLine();
}
}
protected override void OnException(Exception exp)
{
Console.WriteLine("New Exception: {0}", exp?.Message);
Console.WriteLine();
}
}
}
58 changes: 29 additions & 29 deletions src/examples/BotTemplate/Program.cs
Expand Up @@ -9,34 +9,34 @@

namespace BotTemplateSample
{
class Program
{
static void Main()
{
Console.WriteLine("Start!");
class Program
{
static void Main()
{
Console.WriteLine("Start!");

MyBot.Bot.SetMyCommands(new BotCommand("hello", "Hello World!!"));
MyBot.Bot.DeleteWebhook();
// Long Polling: Start
var updates = MyBot.Bot.GetUpdates();
while (true)
{
if (updates.Any())
{
foreach (var update in updates)
{
var botInstance = new MyBot();
botInstance.OnUpdate(update);
}
var offset = updates.Last().UpdateId + 1;
updates = MyBot.Bot.GetUpdates(offset);
}
else
{
updates = MyBot.Bot.GetUpdates();
}
}
// Long Polling: End
}
}
MyBot.Bot.SetMyCommands([new BotCommand("hello", "Hello World!!")]);
MyBot.Bot.DeleteWebhook();
// Long Polling: Start
var updates = MyBot.Bot.GetUpdates();
while (true)
{
if (updates.Any())
{
foreach (var update in updates)
{
var botInstance = new MyBot();
botInstance.OnUpdate(update);
}
var offset = updates.Last().UpdateId + 1;
updates = MyBot.Bot.GetUpdates(offset);
}
else
{
updates = MyBot.Bot.GetUpdates();
}
}
// Long Polling: End
}
}
}
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>CallbackQueryButton01</RootNamespace>
</PropertyGroup>

Expand Down
102 changes: 53 additions & 49 deletions src/examples/Callback query button 01/Program.cs
Expand Up @@ -11,55 +11,59 @@

namespace CallbackQueryButton01
{
class Program
{
static void Main()
{
Console.WriteLine("Start!");
class Program
{
static void Main()
{
Console.WriteLine("Start!");

var bot = new TelegramBotClient("<your bot token>");
bot.SetMyCommands(new BotCommand("callback", "new callback"));
var bot = new TelegramBotClient("<your bot token>");
bot.SetMyCommands([new BotCommand("callback", "new callback")]);

// Long Polling
var updates = bot.GetUpdates();
while (true)
{
if (updates.Length > 0)
{
foreach (var update in updates)
{
if (update.Message != null)
{
var message = update.Message;
if (message.Text.Contains("/callback"))
{
var replyMarkup = new InlineKeyboardMarkup
{
InlineKeyboard = new InlineKeyboardButton[][]{
new InlineKeyboardButton[] {
new("Callback") {
CallbackData = "callback_data"
}
}
}
};
bot.SendMessage(message.Chat.Id, "Message with callback data", replyMarkup: replyMarkup);
}
}
else if (update.CallbackQuery != null)
{
var query = update.CallbackQuery;
bot.AnswerCallbackQuery(query.Id, "HELLO");
bot.EditMessageText(query.Message.Chat.Id, query.Message.MessageId, $"Click!\n\n{query.Data}");
}
}
updates = updates = bot.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1);
}
else
{
updates = bot.GetUpdates();
}
}
}
}
// Long Polling
var updates = bot.GetUpdates();
while (true)
{
if (updates.Any())
{
foreach (var update in updates)
{
if (update.Message != null)
{
var message = update.Message;
if (message.Text.Contains("/callback"))
{
var replyMarkup = new InlineKeyboardMarkup(
new InlineKeyboardButton[][]
{
[new("Callback") { CallbackData = "callback_data" }]
}
);
bot.SendMessage(
message.Chat.Id,
"Message with callback data",
replyMarkup: replyMarkup
);
}
}
else if (update.CallbackQuery != null)
{
var query = update.CallbackQuery;
bot.AnswerCallbackQuery(query.Id, "HELLO");
bot.EditMessageText(
query.Message.Chat.Id,
query.Message.MessageId,
$"Click!\n\n{query.Data}"
);
}
}
updates = updates = bot.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1);
}
else
{
updates = bot.GetUpdates();
}
}
}
}
}
9 changes: 8 additions & 1 deletion src/examples/Examples.sln
Expand Up @@ -23,7 +23,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Library", "Library", "{ADD4
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI", "..\library\Telegram.BotAPI\Telegram.BotAPI.csproj", "{7885DD73-1782-4D0E-826E-C60C27C7648D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloBotNET.AppService", "HelloBotNET.AppService\HelloBotNET.AppService.csproj", "{40F07F65-6DF5-48D2-9C11-0D970BFA31A0}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HelloBotNET.AppService", "HelloBotNET.AppService\HelloBotNET.AppService.csproj", "{40F07F65-6DF5-48D2-9C11-0D970BFA31A0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI.Extensions", "..\library\Telegram.BotAPI.Extensions\Telegram.BotAPI.Extensions.csproj", "{5E7D52AF-3914-47AA-9136-A87520D8119D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -67,6 +69,10 @@ Global
{40F07F65-6DF5-48D2-9C11-0D970BFA31A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{40F07F65-6DF5-48D2-9C11-0D970BFA31A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{40F07F65-6DF5-48D2-9C11-0D970BFA31A0}.Release|Any CPU.Build.0 = Release|Any CPU
{5E7D52AF-3914-47AA-9136-A87520D8119D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5E7D52AF-3914-47AA-9136-A87520D8119D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5E7D52AF-3914-47AA-9136-A87520D8119D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5E7D52AF-3914-47AA-9136-A87520D8119D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -81,6 +87,7 @@ Global
{4A7EC7DA-03F3-40B5-8993-DA90C5CC589C} = {7A82B466-5509-490E-A490-D64D871CBA06}
{7885DD73-1782-4D0E-826E-C60C27C7648D} = {ADD476C3-7C77-421E-8A5F-F5DC41886727}
{40F07F65-6DF5-48D2-9C11-0D970BFA31A0} = {7A82B466-5509-490E-A490-D64D871CBA06}
{5E7D52AF-3914-47AA-9136-A87520D8119D} = {ADD476C3-7C77-421E-8A5F-F5DC41886727}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {936E7344-448B-4497-970E-1AC2EC609933}
Expand Down
2 changes: 1 addition & 1 deletion src/examples/Hello World/Hello World.csproj
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>HelloWorld</RootNamespace>
</PropertyGroup>

Expand Down

0 comments on commit 0259beb

Please sign in to comment.