Skip to content
This repository has been archived by the owner on Sep 10, 2024. It is now read-only.

Commit

Permalink
修复
Browse files Browse the repository at this point in the history
  • Loading branch information
Yushu2606 committed Jan 3, 2024
1 parent 4087580 commit 9ff491f
Show file tree
Hide file tree
Showing 9 changed files with 225 additions and 102 deletions.
44 changes: 33 additions & 11 deletions src/Functions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public static async Task OnCallback(this CallbackQuery callbackQuery)
{
return;
}

Internationalization lang = Program.I18n.GetI18n(callbackQuery.From.LanguageCode);
if (!Program.GroupData.TryGetValue(callbackQuery.Message.Chat.Id, out Dictionary<long, int>? data) ||
!data.TryGetValue(callbackQuery.From.Id, out int historyMessageId) ||
Expand All @@ -25,6 +26,7 @@ public static async Task OnCallback(this CallbackQuery callbackQuery)
await Program.BotClient.AnswerCallbackQueryAsync(callbackQuery.Id, lang["Failed"]);
return;
}

try
{
await Program.BotClient.ApproveChatJoinRequest(callbackQuery.Message.Chat.Id, callbackQuery.From.Id);
Expand All @@ -34,41 +36,50 @@ public static async Task OnCallback(this CallbackQuery callbackQuery)
await Program.BotClient.AnswerCallbackQueryAsync(callbackQuery.Id, lang["Failed"]);
return;
}

await Program.BotClient.AnswerCallbackQueryAsync(callbackQuery.Id, lang["Pass"]);
}

public static async Task OnRequest(this ChatJoinRequest chatJoinRequest)
{
if (!Program.GroupData.ContainsKey(chatJoinRequest.Chat.Id))
if (!Program.GroupData.TryGetValue(chatJoinRequest.Chat.Id, out Dictionary<long, int>? value))
{
Program.GroupData[chatJoinRequest.Chat.Id] = new();
}
else if (Program.GroupData[chatJoinRequest.Chat.Id].ContainsKey(chatJoinRequest.From.Id))
else if (value.ContainsKey(chatJoinRequest.From.Id))
{
return;
}

Internationalization lang = Program.I18n.GetI18n(chatJoinRequest.From.LanguageCode);
int min = 3; // TODO:群组管理员自定义时长
const int min = 3; // TODO:群组管理员自定义时长
Message msg = await Program.BotClient.SendTextMessageAsync(
chatJoinRequest.Chat.Id,
lang.Translate("Message", $"[{(string.IsNullOrWhiteSpace(chatJoinRequest.From.Username) ? $"{chatJoinRequest.From.FirstName} {chatJoinRequest.From.LastName}".Escape() : chatJoinRequest.From.Username)}](tg://user?id={chatJoinRequest.From.Id})", min),
(chatJoinRequest.Chat.IsForum ?? false) ? Program.Database.GetCollection<ChatData>("chats").FindById(chatJoinRequest.Chat.Id).MessageThreadId : default,
lang.Translate("Message",
$"[{(string.IsNullOrWhiteSpace(chatJoinRequest.From.Username) ? $"{chatJoinRequest.From.FirstName} {chatJoinRequest.From.LastName}".Escape() : chatJoinRequest.From.Username)}](tg://user?id={chatJoinRequest.From.Id})",
min),
chatJoinRequest.Chat.IsForum ?? false
? Program.Database.GetCollection<ChatData>("chats").FindById(chatJoinRequest.Chat.Id).MessageThreadId
: default,
ParseMode.MarkdownV2,
replyMarkup: new InlineKeyboardMarkup(new[]
{
InlineKeyboardButton.WithCallbackData(lang["VerifyButton"]),
InlineKeyboardButton.WithCallbackData(lang["VerifyButton"])
})
);
Program.GroupData[chatJoinRequest.Chat.Id][chatJoinRequest.From.Id] = msg.MessageId;
Timer timer = new(min * 60000)
{
AutoReset = false,
AutoReset = false
};
timer.Elapsed += async (_, _) =>
{
if (!Program.GroupData.TryGetValue(chatJoinRequest.Chat.Id, out Dictionary<long, int>? members) || !members.ContainsKey(chatJoinRequest.From.Id))
if (!Program.GroupData.TryGetValue(chatJoinRequest.Chat.Id, out Dictionary<long, int>? members) ||
!members.ContainsKey(chatJoinRequest.From.Id))
{
return;
}
members.Remove(chatJoinRequest.From.Id);
try
{
Expand All @@ -80,35 +91,46 @@ public static async Task OnRequest(this ChatJoinRequest chatJoinRequest)
};
timer.Start();
}

public static async Task OnSet(this Message message)
{
if (message.From is null)
{
return;
}

Internationalization lang = Program.I18n.GetI18n(message.From.LanguageCode);
if ((!message.Chat.IsForum ?? true) || !(await Program.BotClient.GetChatAdministratorsAsync(message.Chat.Id)).Any((chatMember) => chatMember.User.Id == message.From.Id))
if ((!message.Chat.IsForum ?? true) ||
(await Program.BotClient.GetChatAdministratorsAsync(message.Chat.Id)).All(chatMember =>
chatMember.User.Id != message.From.Id))
{
await Program.BotClient.SendTextMessageAsync(message.Chat.Id, lang["UpdateFailed"], (message.Chat.IsForum ?? false) ? message.MessageThreadId : default, ParseMode.MarkdownV2, replyToMessageId: message.MessageId);
await Program.BotClient.SendTextMessageAsync(message.Chat.Id, lang["UpdateFailed"],
message.Chat.IsForum ?? false ? message.MessageThreadId : default, ParseMode.MarkdownV2,
replyToMessageId: message.MessageId);
return;
}

ILiteCollection<ChatData> col = Program.Database.GetCollection<ChatData>("chats");
col.Upsert(new ChatData(message.Chat.Id, message.MessageThreadId ?? default));
await Program.BotClient.SendTextMessageAsync(message.Chat.Id, lang["UpdateSuccess"], message.MessageThreadId, ParseMode.MarkdownV2, replyToMessageId: message.MessageId);
await Program.BotClient.SendTextMessageAsync(message.Chat.Id, lang["UpdateSuccess"], message.MessageThreadId,
ParseMode.MarkdownV2, replyToMessageId: message.MessageId);
}

public static async Task OnJoin(this User member, long chatId, Dictionary<long, int> data)
{
if (!data.TryGetValue(member.Id, out int value))
{
return;
}

try
{
await Program.BotClient.DeleteMessageAsync(chatId, value);
}
catch (ApiRequestException)
{
}

data.Remove(member.Id);
}
}
168 changes: 121 additions & 47 deletions src/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
using LiteDB;
using System.Net;
using LiteDB;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Yan;
using Yan.Utils;
using File = System.IO.File;

namespace Yan;

internal static class Program
{
public static ConfigHelper Config;
public static I18nHelper I18n;
public static LiteDatabase Database;
public static Dictionary<long, Dictionary<long, int>> GroupData;
public static TelegramBotClient BotClient;
public static readonly ConfigHelper Config;
public static readonly I18nHelper I18n;
public static readonly LiteDatabase Database;
public static readonly Dictionary<long, Dictionary<long, int>> GroupData;
public static readonly TelegramBotClient BotClient;

static Program()
{
Expand All @@ -22,12 +23,14 @@ static Program()
Database = new("Groups.db");
GroupData = new();
BotClient = new(Config.Token,
string.IsNullOrWhiteSpace(Config.ProxyUrl) ? default : new(
new HttpClientHandler
{
Proxy = new WebProxy(Config.ProxyUrl, true)
}
)
string.IsNullOrWhiteSpace(Config.ProxyUrl)
? default
: new(
new HttpClientHandler
{
Proxy = new WebProxy(Config.ProxyUrl, true)
}
)
);
}

Expand All @@ -40,55 +43,126 @@ private static void Main()
switch (update.Type)
{
case UpdateType.CallbackQuery:
{
if (update.CallbackQuery is null)
{
if (update.CallbackQuery is null)
{
break;
}
await update.CallbackQuery.OnCallback();
break;
}
await update.CallbackQuery.OnCallback();
break;
}
case UpdateType.Message:
{
if (update.Message is null)
{
if (update.Message is null)
break;
}
switch (update.Message.Type)
{
case MessageType.Text:
{
break;
if (update.Message.Text != $"/set@{(await BotClient.GetMeAsync()).Username}")
{
break;
}
await update.Message.OnSet();
}
switch (update.Message.Type)
break;
case MessageType.ChatMembersAdded:
{
case MessageType.Text:
{
if (update.Message.Text != $"/set@{(await BotClient.GetMeAsync()).Username}")
{
break;
}
await update.Message.OnSet();
}
if (update.Message.NewChatMembers is null ||
!GroupData.TryGetValue(update.Message.Chat.Id, out Dictionary<long, int>? data))
{
break;
case MessageType.ChatMembersAdded:
{
if (update.Message.NewChatMembers is null || !GroupData.TryGetValue(update.Message.Chat.Id, out Dictionary<long, int>? data))
{
break;
}
foreach (User member in update.Message.NewChatMembers)
{
await member.OnJoin(update.Message.Chat.Id, data);
}
break;
}
}
foreach (User member in update.Message.NewChatMembers)
{
await member.OnJoin(update.Message.Chat.Id, data);
}
break;
}
break;
case MessageType.Unknown:
case MessageType.Photo:
case MessageType.Audio:
case MessageType.Video:
case MessageType.Voice:
case MessageType.Document:
case MessageType.Sticker:
case MessageType.Location:
case MessageType.Contact:
case MessageType.Venue:
case MessageType.Game:
case MessageType.VideoNote:
case MessageType.Invoice:
case MessageType.SuccessfulPayment:
case MessageType.WebsiteConnected:
case MessageType.ChatMemberLeft:
case MessageType.ChatTitleChanged:
case MessageType.ChatPhotoChanged:
case MessageType.MessagePinned:
case MessageType.ChatPhotoDeleted:
case MessageType.GroupCreated:
case MessageType.SupergroupCreated:
case MessageType.ChannelCreated:
case MessageType.MigratedToSupergroup:
case MessageType.MigratedFromGroup:
case MessageType.Poll:
case MessageType.Dice:
case MessageType.MessageAutoDeleteTimerChanged:
case MessageType.ProximityAlertTriggered:
case MessageType.WebAppData:
case MessageType.VideoChatScheduled:
case MessageType.VideoChatStarted:
case MessageType.VideoChatEnded:
case MessageType.VideoChatParticipantsInvited:
case MessageType.Animation:
case MessageType.ForumTopicCreated:
case MessageType.ForumTopicClosed:
case MessageType.ForumTopicReopened:
case MessageType.ForumTopicEdited:
case MessageType.GeneralForumTopicHidden:
case MessageType.GeneralForumTopicUnhidden:
case MessageType.WriteAccessAllowed:
case MessageType.UserShared:
case MessageType.ChatShared:
case MessageType.Story:
break;
default:
throw new ArgumentOutOfRangeException();
}
break;
}
case UpdateType.ChatJoinRequest:
{
if (update.ChatJoinRequest is null || update.ChatJoinRequest.From.IsBot)
{
if (update.ChatJoinRequest is null || update.ChatJoinRequest.From.IsBot)
{
break;
}
await update.ChatJoinRequest.OnRequest();
break;
}
await update.ChatJoinRequest.OnRequest();
break;
}
case UpdateType.Unknown:
case UpdateType.InlineQuery:
case UpdateType.ChosenInlineResult:
case UpdateType.EditedMessage:
case UpdateType.ChannelPost:
case UpdateType.EditedChannelPost:
case UpdateType.ShippingQuery:
case UpdateType.PreCheckoutQuery:
case UpdateType.Poll:
case UpdateType.PollAnswer:
case UpdateType.MyChatMember:
case UpdateType.ChatMember:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
catch (Exception ex)
Expand Down
4 changes: 3 additions & 1 deletion src/Utils/ConfigHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Text.Json;

namespace Yan.Utils;

public record ConfigHelper(string Token, string ProxyUrl, bool EnableAutoI18n)
{
internal ConfigHelper(string path) : this("", "", default)
Expand All @@ -11,8 +12,9 @@ internal ConfigHelper(string path) : this("", "", default)
{
return;
}

Token = config.Token;
ProxyUrl = config.ProxyUrl;
EnableAutoI18n = config.EnableAutoI18n;
}
}
}
9 changes: 6 additions & 3 deletions src/Utils/FileHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace Yan.Utils;
internal static class FileHelper
{
/// <summary>
/// 获取DirectoryInfo,不存在时自动创建
/// 获取DirectoryInfo,不存在时自动创建
/// </summary>
/// <param name="path">文件夹目录</param>
/// <returns>文件夹DirectoryInfo对象</returns>
Expand All @@ -14,10 +14,12 @@ public static DirectoryInfo CheckDir(string path)
{
info.Create();
}

return info;
}

/// <summary>
/// 读取文件全部文字,不存在时自动创建
/// 读取文件全部文字,不存在时自动创建
/// </summary>
/// <param name="path">文件目录</param>
/// <param name="defaultValue">创建时的默认内容</param>
Expand All @@ -28,7 +30,8 @@ public static string CheckFile(string path, string defaultValue = "")
{
return File.ReadAllText(path);
}

File.WriteAllText(path, defaultValue);
return defaultValue;
}
}
}
Loading

0 comments on commit 9ff491f

Please sign in to comment.