Skip to content

Instantly share code, notes, and snippets.

@kipters
Created November 21, 2019 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kipters/a81d14ef2976bcdc381aab8ccc9cd2fe to your computer and use it in GitHub Desktop.
Save kipters/a81d14ef2976bcdc381aab8ccc9cd2fe to your computer and use it in GitHub Desktop.
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Telegram.Bot.Types;
namespace DotNetGroup
{
public static class BotHandler
{
[FunctionName("BotHandler")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
ILogger log)
{
var content = await new StreamReader(req.Body).ReadToEndAsync();
var body = JsonConvert.DeserializeObject<Update>(content);
if (body?.Message is null)
{
log.LogInformation("Not a message");
return new OkResult();
}
var newMembers = body.Message.NewChatMembers;
if (newMembers is null || newMembers.Length == 0)
{
log.LogInformation("No user joined");
return new OkResult();
}
if (newMembers.Length > 1)
{
log.LogInformation($"Multiple users joined");
const string multiUserText = "Welcome to the group, please **read the rules** in the group description and remember job posts **are not allowed** and will cause an immediate kick+ban";
return TextMessageResult(body.Message, multiUserText);
}
var tagString = GetTagString(body.Message.NewChatMembers.First());
log.LogInformation("Single user joined");
var text =
$"Welcome to the group {tagString}, please **read the rules** in the group description and remember job posts **are not allowed** and will cause an immediate kick+ban";
return TextMessageResult(body.Message, text);
}
private static string GetTagString(User user)
{
if (!string.IsNullOrWhiteSpace(user.Username))
return $"@{user.Username}";
if (!string.IsNullOrWhiteSpace(user.LastName))
return $"[{user.FirstName} {user.LastName}](tg://user?id={user.Id})";
return $"[{user.FirstName}](tg://user?id={user.Id})";
}
private static IActionResult TextMessageResult(Message message, string text)
{
var response = new
{
chat_id = message.Chat.Id,
text,
parse_mode = "Markdown",
disable_notification = true,
reply_to_message_id = message.MessageId,
method = "sendMessage"
};
return new OkObjectResult(response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment