Skip to content

Commit

Permalink
refactor: Update examples. Closes #49
Browse files Browse the repository at this point in the history
  • Loading branch information
Eptagone committed Nov 17, 2024
1 parent 5730a1b commit ef99ee8
Show file tree
Hide file tree
Showing 36 changed files with 1,176 additions and 1,137 deletions.
27 changes: 15 additions & 12 deletions src/.editorconfig
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
[*.cs]
csharp_indent_braces=false
insert_final_newline=true
dotnet_diagnostic.CA1200.severity=suggestion
dotnet_diagnostic.CA1805.severity=suggestion
csharp_indent_braces = false
insert_final_newline = true
dotnet_diagnostic.ca1200.severity = suggestion
dotnet_diagnostic.ca1805.severity = suggestion

dotnet_diagnostic.CS8766.severity=silent
dotnet_diagnostic.cs8766.severity = silent
csharp_using_directive_placement = outside_namespace:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_prefer_braces = true:silent
csharp_style_namespace_declarations = block_scoped:silent
csharp_style_namespace_declarations = file_scoped:suggestion
csharp_style_prefer_method_group_conversion = true:silent
csharp_style_prefer_top_level_statements = true:silent
csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_methods = true:none
csharp_style_expression_bodied_constructors = true:none
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_indexers = true:silent
Expand Down Expand Up @@ -53,11 +53,14 @@ csharp_style_prefer_primary_constructors = true:suggestion
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent

# ReSharper properties
resharper_local_function_body = expression_body

[*.{cs,vb}]
dotnet_diagnostic.CA1707.severity=suggestion
dotnet_diagnostic.CA1710.severity=silent
dotnet_diagnostic.CA1713.severity=suggestion
dotnet_diagnostic.CA1727.severity=warning
dotnet_diagnostic.ca1707.severity = suggestion
dotnet_diagnostic.ca1710.severity = silent
dotnet_diagnostic.ca1713.severity = suggestion
dotnet_diagnostic.ca1727.severity = warning

[*.{cs,vb}]
#### Naming styles ####
Expand Down
2 changes: 1 addition & 1 deletion src/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,4 @@ FodyWeavers.xsd
*.msp

# JetBrains Rider
*.sln.iml
*.sln.iml
53 changes: 27 additions & 26 deletions src/examples/BotTemplate/MyBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@ namespace BotTemplateSample
public sealed class MyBot : SimpleTelegramBotBase
{
public static readonly TelegramBotClient Bot = new("<BOT TOKEN>");
public static readonly User Me = Bot.GetMe();
private static readonly User Me = Bot.GetMe();

public MyBot()
{
// Provides a better way to extract commands using regular expressions.
this.SetCommandExtractor(Me.Username, true);
this.SetCommandExtractor(Me.Username!);
}

public override void OnUpdate(Update update)
{
Console.WriteLine(
"New update with id: {0}. Type: {1}",
update?.UpdateId,
update.UpdateId,
update.GetUpdateType()
);
base.OnUpdate(update);
Expand All @@ -36,7 +36,7 @@ public override void OnUpdate(Update update)
protected override void OnMessage(Message message)
{
// Ignore user 777000 (Telegram)
if (message?.From.Id == TelegramConstants.TelegramId)
if (message.From?.Id == TelegramConstants.TelegramId)
{
return;
}
Expand All @@ -48,53 +48,54 @@ protected override void OnMessage(Message message)
{
// Make something
}
else // Group chats
{ }

// Group chats
// Check if the message contains a command
if (message.Entities.Any(e => e.Type == "bot_command"))
if (message.Entities?.Any(e => e.Type == "bot_command") is not true)
{
// 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;
return;
}

Console.WriteLine("New command: {0}", command);
this.OnCommand(message, command, @params);
}
// If the command includes a mention, you should verify that it is for your bot, otherwise you will need to ignore the command.
string? pattern = $@"^\/(?<COMMAND>\w*)(?:|@{Me.Username})(?:$|\s(?<PARAMETERS>.*))";
Match? match = Regex.Match(message.Text!, pattern, RegexOptions.IgnoreCase);
if (!match.Success)
{
return;
}

string? command = match.Groups.Values.Single(v => v.Name == "COMMAND").Value; // Get command name
string? @params =
match.Groups.Values.SingleOrDefault(v => v.Name == "PARAMETERS")?.Value
?? string.Empty;

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);
string[]? 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);
string? hello = $"Hello World, {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("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("New Exception: {0}", exp.Message);
Console.WriteLine();
}
}
Expand Down
47 changes: 20 additions & 27 deletions src/examples/BotTemplate/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,33 @@

using System;
using System.Linq;
using BotTemplateSample;
using Telegram.BotAPI.AvailableMethods;
using Telegram.BotAPI.AvailableTypes;
using Telegram.BotAPI.GettingUpdates;

namespace BotTemplateSample
Console.WriteLine("Start!");

MyBot.Bot.SetMyCommands([new BotCommand("hello", "Hello World!!")]);
MyBot.Bot.DeleteWebhook();

// Long Polling: Start
var updates = MyBot.Bot.GetUpdates();
while (true)
{
class Program
if (updates.Any())
{
static void Main()
foreach (var update in updates)
{
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
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
94 changes: 47 additions & 47 deletions src/examples/Callback query button 01/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,68 +2,68 @@
// Licensed under the MIT License, See LICENCE in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using Telegram.BotAPI;
using Telegram.BotAPI.AvailableMethods;
using Telegram.BotAPI.AvailableTypes;
using Telegram.BotAPI.GettingUpdates;
using Telegram.BotAPI.UpdatingMessages;

namespace CallbackQueryButton01
Console.WriteLine("Start!");

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

// Long Polling
IEnumerable<Update> updates = bot.GetUpdates();
while (true)
{
class Program
if (updates.Any())
{
static void Main()
foreach (Update update in updates)
{
Console.WriteLine("Start!");

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

// Long Polling
var updates = bot.GetUpdates();
while (true)
if (update.Message?.Chat is not null && !string.IsNullOrEmpty(update.Message.Text))
{
if (updates.Any())
if (!update.Message.Text.Contains("/callback"))
{
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)
continue;
}

InlineKeyboardMarkup replyMarkup =
new(
new InlineKeyboardButton[][]
{
var query = update.CallbackQuery;
bot.AnswerCallbackQuery(query.Id, "HELLO");
bot.EditMessageText(
query.Message.Chat.Id,
query.Message.MessageId,
$"Click!\n\n{query.Data}"
);

[
new InlineKeyboardButton("Callback")
{
CallbackData = "callback_data",
},
],
}
}
updates = updates = bot.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1);
}
else
{
updates = bot.GetUpdates();
}
);
bot.SendMessage(
update.Message.Chat.Id,
"Message with callback data",
replyMarkup: replyMarkup
);
}
else if (update.CallbackQuery?.Message is not null)
{
bot.AnswerCallbackQuery(update.CallbackQuery.Id, "HELLO");
bot.EditMessageText(
update.CallbackQuery.Message.Chat.Id,
update.CallbackQuery.Message.MessageId,
$"Click!\n\n{update.CallbackQuery.Data}"
);
}
}

updates = updates = bot.GetUpdates(updates.Max(u => u.UpdateId) + 1);
}
else
{
updates = bot.GetUpdates();
}
}
Loading

0 comments on commit ef99ee8

Please sign in to comment.