Update Happiness Task

This commit is contained in:
Chris Chen
2022-10-02 09:50:42 -07:00
parent b33c0d8286
commit f9a5dc5e34
43 changed files with 4904 additions and 623 deletions
@@ -15,24 +15,23 @@ namespace WebAPI.Services.AutoReplyCommands
{
public class ArArkCellGroupDinner : IAutoReplyCommand
{
private PastoralDomain pastoralDomain;
public ArArkCellGroupDinner(
CellGroupLogic logic)
PastoralDomainLogic logic)
{
this.logic = logic;
}
private static readonly string[] COMMANDS = { "晚餐", "dinner" };
private static readonly LineGroup[] GROUPS = {
LineGroup.Ark,
LineGroup.Chris,
private static readonly DomainType[] GROUPS = {
DomainType.CellGroup,
};
private readonly CellGroupLogic logic;
private readonly PastoralDomainLogic logic;
public string Description => "顯示方舟小組聚會晚餐";
public string Description => "顯示小組聚會晚餐";
public IEnumerable<string> Commands => COMMANDS;
public IEnumerable<LineGroup> SupportGroups => GROUPS;
public IEnumerable<string> ReplyMessage => null;
public IEnumerable<DomainType> SupportGroups => GROUPS;
public string ReplyTextMessage => null;
public IEnumerable<ILineMessage> LineMessage
{
@@ -41,7 +40,7 @@ namespace WebAPI.Services.AutoReplyCommands
var random = new Random();
List<ILineMessage> list = new List<ILineMessage>();
var _event = logic.GetComingEvent();
var _event = logic.GetComingEvent(pastoralDomain.Id);
string title = "小組晚宴,吃飯皇帝大";
string imageUrl = "https://happiness.tours/assets/images/dinner.jpg";
@@ -191,5 +190,15 @@ namespace WebAPI.Services.AutoReplyCommands
return list;
}
}
public void Initialize(PastoralDomain pastoralDomain = null)
{
this.pastoralDomain = pastoralDomain;
}
public bool Enabled(PastoralDomain pastoralDomain = null, string command = null)
{
return COMMANDS.Any(c=>c.IndexOf(command)==0);
}
}
}
@@ -1,4 +1,5 @@
using LineMessaging;
using Church.Net.Entity;
using LineMessaging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -9,25 +10,31 @@ namespace WebAPI.Services.AutoReplyCommands
{
public class ArArkCellGroupInfo : IAutoReplyCommand
{
private PastoralDomain pastoralDomain;
private static readonly string[] COMMANDS = { "小組" };
private static readonly DomainType[] GROUPS = {
DomainType.CellGroup,
};
private static readonly string[] COMMANDS = { "方舟", "方舟小組", "ark" };
private static readonly string[] MESSAGES = {
public string Description => "顯示小組聚會資訊";
public IEnumerable<string> Commands => COMMANDS;
public string ReplyTextMessage =>
"新生命靈糧堂 Arcadia 牧區 - 方舟小組\n" +
"聚會時間 & 流程 周五晚上\n" +
"07:30 PM ~ 08:30 PM - PotLuck 時光\n" +
"08:30 PM ~ 10:00 PM - 小組分享",
"1881 Forest Dr, Azusa, CA 91702"
};
private static readonly LineGroup[] GROUPS = {
LineGroup.Ark,
LineGroup.ArkCowoker,
LineGroup.Chris
};
public string Description => "顯示方舟小組聚會資訊";
public IEnumerable<string> Commands => COMMANDS;
public IEnumerable<string> ReplyMessage => MESSAGES;
public IEnumerable<LineGroup> SupportGroups => GROUPS;
"08:30 PM ~ 10:00 PM - 小組分享\n" +
"1881 Forest Dr, Azusa, CA 91702";
public IEnumerable<DomainType> SupportGroups => GROUPS;
public IEnumerable<ILineMessage> LineMessage => null;
public void Initialize(PastoralDomain pastoralDomain = null)
{
this.pastoralDomain = pastoralDomain;
}
public bool Enabled(PastoralDomain pastoralDomain = null, string command = null)
{
return COMMANDS.Any(c => c.IndexOf(command) == 0);
}
}
}
@@ -1,6 +1,7 @@
using Church.Net.DAL.EF;
using Church.Net.Entity;
using Church.Net.Utility;
using Esprima;
using LineMessaging;
using Microsoft.EntityFrameworkCore;
using System;
@@ -15,9 +16,9 @@ namespace WebAPI.Services.AutoReplyCommands
{
public class ArArkCellGroupPrayer : IAutoReplyCommand
{
PastoralDomain pastoralDomain;
public ArArkCellGroupPrayer(
CellGroupLogic logic
PastoralDomainLogic logic
)
{
this.logic = logic;
@@ -67,67 +68,15 @@ namespace WebAPI.Services.AutoReplyCommands
}
private static readonly string[] COMMANDS = { "禱告", "代禱", "letspray", "pray" };
private static readonly LineGroup[] GROUPS = {
LineGroup.Ark,
LineGroup.Chris,
LineGroup.ArkCowoker,
private static readonly DomainType[] GROUPS = {
DomainType.CellGroup,
};
private readonly CellGroupLogic logic;
private readonly PastoralDomainLogic logic;
public string Description => "顯示代禱事項";
public IEnumerable<string> Commands => COMMANDS;
public IEnumerable<LineGroup> SupportGroups => GROUPS;
public IEnumerable<string> ReplyMessage
{
get
{
StringBuilder sb = new StringBuilder();
StringBuilder comments = new StringBuilder();
sb.AppendLine("方舟小組-禱告中心");
var _event = logic.GetLastEvent();
if (_event == null || _event.Prayers.Count == 0)
{
sb.AppendLine($"目前暫無禱告事項唷!");
sb.AppendLine($"請使用方舟禱告系統,新增代禱項目唷!");
sb.AppendLine("https://happiness.tours/CellGroup/prayer?openExternalBrowser=1");
}
var random = new Random();
int index = random.Next(bibleReferrences.Count);
var bibleSentence = bibleReferrences[index];
sb.AppendLine("======= 代禱事項 =======");
foreach (var a in _event.Prayers)
{
var name = logic.GetMemberFirstNameById(a.MemberId);
sb.AppendLine($"{name} - {string.Join(", ", a.Prayer.Split('|'))}");
//sb.AppendLine($"{logic.GetMemberFirstNameById (a.MemberId)} - ");
//int count = 0;
//foreach (var prayer in a.Prayer.Split('|'))
//{
// count++;
// sb.AppendLine(prayer);
//}
if (!string.IsNullOrWhiteSpace(a.Comment))
{
comments.AppendLine($"{name}:{a.Comment}");
}
}
if (comments.Length > 0)
{
sb.AppendLine("========= 備註 =========");
sb.Append(comments.ToString());
}
sb.AppendLine("");
sb.AppendLine($"請使用方舟禱告系統,新增代禱項目唷!");
sb.AppendLine("https://happiness.tours/CellGroup/prayer?openExternalBrowser=1");
return new string[] { sb.ToString() };
}
}
public IEnumerable<DomainType> SupportGroups => GROUPS;
public string ReplyTextMessage => null;
public IEnumerable<ILineMessage> LineMessage
{
get
@@ -137,7 +86,7 @@ namespace WebAPI.Services.AutoReplyCommands
var bibleSentence = bibleReferrences[index];
List<ILineMessage> list = new List<ILineMessage>();
var _event = logic.GetLastEvent();
var _event = logic.GetLastEvent(this.pastoralDomain.Id);
string title = "禱告中心 普壘森特";
string imageUrl = "https://dailyverses.net/images/tc/cuv/matthew-21-22-3.jpg";
@@ -280,6 +229,15 @@ namespace WebAPI.Services.AutoReplyCommands
}
private List<BibleReferrence> bibleReferrences;
public void Initialize(PastoralDomain pastoralDomain = null)
{
this.pastoralDomain = pastoralDomain;
}
public bool Enabled(PastoralDomain pastoralDomain = null, string command = null)
{
return COMMANDS.Any(c => c.IndexOf(command) == 0);
}
}
@@ -1,4 +1,5 @@
using LineMessaging;
using Church.Net.Entity;
using LineMessaging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -11,21 +12,29 @@ namespace WebAPI.Services.AutoReplyCommands
{
private static readonly string[] COMMANDS = { "教會", "church" };
private static readonly string[] MESSAGES = {
"新生命靈糧堂 Arcadia 牧區\n聚會時間 周日 11:00 AM - 12:30PM\n聚會後有提供精緻午餐唷!",
"1881 S 1st Ave, Arcadia, CA 91006"
};
private static readonly LineGroup[] GROUPS = {
LineGroup.Ark,
LineGroup.ArkCowoker,
LineGroup.Chris
private static readonly string MESSAGES =
"新生命靈糧堂 Arcadia 牧區\n聚會時間 周日 11:00 AM - 12:30PM\n聚會後有提供精緻午餐唷!\n"+
"1881 S 1st Ave, Arcadia, CA 91006";
private static readonly DomainType[] GROUPS = {
DomainType.HappinessGroup,
DomainType.CellGroup
};
public string Description => "顯示教會主日聚會資訊";
public IEnumerable<string> Commands => COMMANDS;
public IEnumerable<string> ReplyMessage => MESSAGES;
public string ReplyTextMessage => MESSAGES;
public IEnumerable<LineGroup> SupportGroups => GROUPS;
public IEnumerable<ILineMessage> LineMessage => null;
IEnumerable<DomainType> IAutoReplyCommand.SupportGroups => GROUPS;
public bool Enabled(PastoralDomain pastoralDomain = null, string command = null)
{
return COMMANDS.Any(c => c.IndexOf(command) == 0);
}
public void Initialize(PastoralDomain pastoralDomain = null)
{
}
}
}
@@ -0,0 +1,199 @@
using Church.Net.DAL.EF;
using Church.Net.Entity;
using Church.Net.Utility;
using LineMessaging;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebAPI.Logics;
using WebAPI.Services.Interfaces;
namespace WebAPI.Services.AutoReplyCommands
{
public class ArHappinessGroupTask : IAutoReplyCommand
{
private PastoralDomain pastoralDomain;
public ArHappinessGroupTask(
PastoralDomainLogic logic)
{
this.logic = logic;
}
private static readonly string[] COMMANDS = { "分工", "分工#" };
private static readonly DomainType[] GROUPS = {
DomainType.HappinessGroup,
};
private readonly PastoralDomainLogic logic;
public string Description => "顯示幸福小組分工表 #代表周數";
public IEnumerable<string> Commands => COMMANDS;
public IEnumerable<DomainType> SupportGroups => GROUPS;
public string ReplyTextMessage => null;
public IEnumerable<ILineMessage> LineMessage
{
get
{
var random = new Random();
List<ILineMessage> list = new List<ILineMessage>();
string title = $"W{weekSeq} {week.Topic} 分工表";
string imageUrl = $"https://happiness.tours/assets/images/HappinessGroup/week0{weekSeq}.jpg";
var flexMessage = new LineFlexMessage();
flexMessage.AltText = title;
#region Header
var headerContent = flexMessage.Contents.InitHeader();
headerContent.Add(
new LineFlexText(title)
{
Size = FlexObjectSize.lg,
Weight = FlexObjectTextWeidht.Bold,
Align = "center"
});
#endregion
#region Hero
flexMessage.Contents.InitHero()
.Add(
new LineFlexImage(imageUrl)
{
Size = FlexObjectSize.full,
AspectRatio = "1.5:1"
}
);
#endregion
#region Body
var bodyContent = flexMessage.Contents.InitBody();
TimeSpan ts = week.Date - DateTime.Now;
Console.WriteLine("No. of Minutes (Difference) = {0}", ts.TotalMinutes);
bodyContent.Add(
new LineFlexText($"再過 {ts.TotalMinutes.ToString("N0")} 分鐘,就是萬眾期待的幸福小組啦!!!")
{
Size = FlexObjectSize.md,
Weight = FlexObjectTextWeidht.Regular,
OffsetBottom = FlexObjectSize.xxl,
Wrap = true
});
//bodyContent.Add(
// new LineFlexText($"{_event.Time.ToString("MM/dd HH:mm tt")} 準時開飯唷!!")
// {
// Size = FlexObjectSize.md,
// Weight = FlexObjectTextWeidht.Regular,
// OffsetBottom = FlexObjectSize.xl,
// Wrap = true
// });
bodyContent.Add(
new LineFlexText("分工明細")
{
Size = FlexObjectSize.md,
Weight = FlexObjectTextWeidht.Bold,
OffsetBottom = FlexObjectSize.md
});
//$"目前暫無禱告事項唷, 趕快來新增代禱事項吧!!"
List<LineFlexBox> comments = new List<LineFlexBox>();
foreach (var a in week.Tasks)
{
var name = string.IsNullOrEmpty(a.Tasker)?"N/A": a.Tasker;// logic.GetMemberFirstNameById(a.MemberId);
var baseLineBox = new LineFlexBox()
{
Layout = FlexObjectBoxLayout.Baseline,
};
baseLineBox.Contents.Add(
new LineFlexText(a.Type.EnumToDescriptionString())
{
Size = FlexObjectSize.sm,
Color = "#aaaaaa",
Flex = 3
});
baseLineBox.Contents.Add(
new LineFlexText(
$"{name}"
)
{
Size = FlexObjectSize.sm,
Color = "#666666",
Flex = 3,
Wrap = true
});
baseLineBox.Contents.Add(
new LineFlexText(
$"內容:{a.Content}"
)
{
Size = FlexObjectSize.sm,
Color = "#666666",
Flex = 7,
Wrap = true
});
bodyContent.Add(baseLineBox);
}
bodyContent.Add(new LineFlexSeparator());
#endregion
#region Footer
//flexMessage.Contents.InitFooter()
// .Add(
// new LineFlexButton()
// {
// Action = new UriAction()
// {
// Uri = "https://happiness.tours/CellGroup/dinner?openExternalBrowser=1",
// Label = "我的菜單"
// }
// }
// );
#endregion
list.Insert(0, flexMessage);
return list;
}
}
public void Initialize(PastoralDomain pastoralDomain = null)
{
this.pastoralDomain = pastoralDomain;
}
private int weekSeq = 0;
private HappinessWeek week = null;
public bool Enabled(PastoralDomain pastoralDomain = null, string command = null)
{
if (pastoralDomain != null && COMMANDS.Any(c => c.IndexOf(command) == 0))
{
this.pastoralDomain = pastoralDomain;
command = command.Replace("分工", "");
if (command.Length > 0)
{
weekSeq = int.Parse(command);
}
logic.GetHappinessGroupInfo(pastoralDomain);
if (weekSeq > 0)
{
week = pastoralDomain.HappinessWeeks.Where(w => w.SEQ == weekSeq).FirstOrDefault();
}
else
{
week = pastoralDomain.HappinessWeeks.Where(w => w.Date >= DateTime.UtcNow).FirstOrDefault();
weekSeq = week.SEQ;
}
return true;
};
return false;
}
}
}
+31 -13
View File
@@ -1,26 +1,44 @@
using Church.Net.Entity;
using Church.Net.DAL.EFCoreDBF;
using Church.Net.Entity;
using Church.Net.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using WebAPI.Logics;
namespace WebAPI.Services
{
public class IdentityService
{
public string UserAccessToken { get; set; }
public string UserId { get; set; }
private readonly IHttpContextAccessor httpContextAccessor;
public PastoralDomain CellGroup
public IdentityService(
IHttpContextAccessor httpContextAccessor
)
{
this.httpContextAccessor = httpContextAccessor;
}
public string UserAccessToken
{
get
{
return httpContextAccessor.HttpContext.Request.Headers["accessToken"];
}
}
private string _UserId;
public string UserId
{
get {
TokenHelper.GetUserIdFromToken
return null; }
if (string.IsNullOrWhiteSpace(_UserId))
{
_UserId = TokenHelper.GetUserIdFromToken(UserAccessToken);
}
return _UserId;
}
set {
_UserId = value;
}
}
}
}
@@ -1,4 +1,6 @@
using LineMessaging;
using Church.Net.Entity;
using LineMessaging;
using NuGet.Protocol.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,8 +12,10 @@ namespace WebAPI.Services.Interfaces
{
string Description { get; }
IEnumerable<string> Commands { get; }
IEnumerable<string> ReplyMessage { get; }
IEnumerable<LineGroup> SupportGroups { get; }
string ReplyTextMessage { get; }
IEnumerable<DomainType> SupportGroups { get; }
IEnumerable<ILineMessage> LineMessage { get; }
bool Enabled(PastoralDomain pastoralDomain = null, string command = null);
void Initialize(PastoralDomain pastoralDomain = null);
}
}
+99 -70
View File
@@ -1,4 +1,5 @@
using Church.Net.Entity.Messenger;
using Church.Net.Entity;
using Church.Net.Entity.Messenger;
using Church.Net.Utility;
using LineMessaging;
using Microsoft.Extensions.Logging.Abstractions;
@@ -9,6 +10,7 @@ using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebAPI.Logics;
using WebAPI.Logics.Interface;
using WebAPI.Services.Interfaces;
using static System.Net.Mime.MediaTypeNames;
@@ -22,6 +24,8 @@ namespace WebAPI.Services
Ark = 1 << 0,
[Description("Ca20e3b65aa58e676815eb13c3222591a")]
ArkCowoker = 1 << 1,
PastoralDomain = 1 << 2,
HappinessGroup = 1 << 3,
[Description("U97e9e579a41a5222e33bf68a3bf479a0")]
Chris = ~(~0 << 20),
}
@@ -30,20 +34,26 @@ namespace WebAPI.Services
private readonly IEnumerable<IAutoReplyCommand> autoReplyCommands;
private readonly ILoggingService loggingService;
private readonly ICrudLogic<LineMessageClient> clientLogic;
private readonly LineMessagingAccountLogic lineMessagingAccountLogic;
private string chatToken;
private PastoralDomain cellGroup;
public LineAutoBotService(
IEnumerable<IAutoReplyCommand> autoReplyCommands,
ILoggingService loggingService,
ICrudLogic<LineMessageClient> clientLogic
ICrudLogic<LineMessageClient> clientLogic,
LineMessagingAccountLogic lineMessagingAccountLogic
)
{
this.autoReplyCommands = autoReplyCommands;
this.loggingService = loggingService;
this.clientLogic = clientLogic;
this.lineMessagingAccountLogic = lineMessagingAccountLogic;
}
public void SendTextMessage(string text, LineGroup target)
{
var test = new LineMessagingClient();
var test = new LineMessagingClient(this.chatToken);
try
{
@@ -57,27 +67,27 @@ namespace WebAPI.Services
}
}
public async Task<bool> ReplyTextMessage(string replyToken, IEnumerable<string> textMessages)
public async Task<bool> ReplyTextMessage(string lineId, string textMessages)
{
var test = new LineMessagingClient();
var test = new LineMessagingClient(this.chatToken);
var replyMessage = new LineReplyMessage() { ReplyToken = replyToken };
var messages = new List<ILineMessage>();
foreach (var message in textMessages)
{
messages.Add(new LineTextMessage() { Text = message });
}
replyMessage.Messages = messages;
//var replyMessage = new LineReplyMessage() { ReplyToken = replyToken };
//var messages = new List<ILineMessage>();
//foreach (var message in textMessages)
//{
// messages.Add(new LineTextMessage() { Text = message });
//}
//replyMessage.Messages = messages;
//test.ReplyMessage(replyMessage);
try
{
await test.ReplyMessage(replyMessage);
await test.PushMessage(lineId, new LineTextMessage() { Text = textMessages });
return true;
}
catch (Exception ex)
{
this.loggingService.Error(ex, "ReplyTextMessage:75", JsonConvert.SerializeObject(replyMessage, Formatting.Indented));
this.loggingService.Error(ex, "ReplyTextMessage:75", textMessages);
if (ex.Message == "You have reached your monthly limit.")
{
@@ -86,11 +96,11 @@ namespace WebAPI.Services
return false;
}
}
public async Task<bool> ReplyLineMessage(string replyToken, IEnumerable<ILineMessage> lineMessages)
public async Task<bool> ReplyLineMessage(string lineId, IEnumerable<ILineMessage> lineMessages)
{
var test = new LineMessagingClient();
var test = new LineMessagingClient(this.chatToken);
var replyMessage = new LinePushMessage() { To = replyToken };
var replyMessage = new LinePushMessage() { To = lineId };
replyMessage.Messages = lineMessages;
try
@@ -112,8 +122,9 @@ namespace WebAPI.Services
}
public async Task<bool> AutoReply(LineWebhookContent content)
public async Task<bool> AutoReply(LineMessagingAccount lineAccount, LineWebhookContent content)
{
chatToken = lineAccount.ChatToken;
loggingService.Log("AutoReply", content);
try
{
@@ -127,7 +138,7 @@ namespace WebAPI.Services
string text = e.Message.Text;
string target = "";
bool isGroup = true;
var client = new LineMessagingClient();
var client = new LineMessagingClient(this.chatToken);
switch (e.Source.Type)
{
case WebhookRequestSourceType.User:
@@ -136,58 +147,74 @@ namespace WebAPI.Services
break;
case WebhookRequestSourceType.Group:
target = e.Source.GroupId;
cellGroup = lineMessagingAccountLogic.GetCellGroup(target);
break;
case WebhookRequestSourceType.Room:
target = e.Source.RoomId;
break;
default:
target = e.Source.RoomId;
return false;
break;
}
if (isGroup)
{
if (clientLogic.First(c => c.ClientId == e.Source.GroupId) == null)
{
clientLogic.CreateOrUpdate(new LineMessageClient()
{
ClientId = target,
Name = client.GetGroupProfile(e.Source.GroupId).Result.GroupName,
IsGroup = true
}, out string id);
}
//TODO:Get user by user id under group
}
else
{
if (clientLogic.First(c => c.ClientId == e.Source.UserId) == null)
{
clientLogic.CreateOrUpdate(new LineMessageClient()
try
{
if (isGroup)
{
if (clientLogic.First(c => c.ClientId == e.Source.GroupId) == null)
{
ClientId = target,
Name = client.GetProfile(e.Source.UserId).Result.DisplayName,
IsGroup = false
}, out string id);
clientLogic.CreateOrUpdate(new LineMessageClient()
{
ClientId = target,
Name = client.GetGroupProfile(e.Source.GroupId).Result.GroupName,
IsGroup = true
}, out string id);
}
//TODO:Get user by user id under group
}
else
{
if (clientLogic.First(c => c.ClientId == e.Source.UserId) == null)
{
clientLogic.CreateOrUpdate(new LineMessageClient()
{
ClientId = target,
Name = client.GetProfile(e.Source.UserId).Result.DisplayName,
IsGroup = false
}, out string id);
}
}
}
catch (Exception)
{
}
if (!String.IsNullOrWhiteSpace(replyToken) && text.IndexOf("#") == 0)
{
text = text.ToLower().Substring(1);
var group = EnumHelper.GetEnumValueFromDescription<LineGroup>(target);
LineGroup group = LineGroup.Chris;
var autoReply = autoReplyCommands.Where(ar => ar.SupportGroups.Contains(group) && ar.Commands.Contains(text)).FirstOrDefault();
if (cellGroup == null)
{
return false;
}
var autoReply = autoReplyCommands.Where(ar =>
ar.SupportGroups.Contains(cellGroup.Type) &&
ar.Enabled(cellGroup, text)
).FirstOrDefault();
if (autoReply != null)
{
if (autoReply.LineMessage != null)
{
await ReplyLineMessage(target, autoReply.LineMessage);
}
else
{
await ReplyTextMessage(replyToken, autoReply.ReplyMessage);
await ReplyTextMessage(replyToken, autoReply.ReplyTextMessage);
}
return true;
@@ -195,13 +222,13 @@ namespace WebAPI.Services
else if (text == "help" || text == "?")
{
StringBuilder commandText = new StringBuilder();
commandText.AppendLine("方舟資訊部 - 指令清單");
foreach (var ar in autoReplyCommands.Where(ar => ar.SupportGroups.Contains(group)))
commandText.AppendLine("NLCC資訊部 - 指令清單");
foreach (var ar in autoReplyCommands.Where(ar => ar.SupportGroups.Contains(cellGroup.Type)))
{
commandText.AppendLine($"{string.Join(", ", ar.Commands.Select(s => $"#{s}"))} - {ar.Description}");
}
commandText.Append($"#help, #? - 顯示指令清單");
await ReplyTextMessage(replyToken, new string[] { commandText.ToString() });
await ReplyTextMessage(replyToken, commandText.ToString());
}
@@ -210,11 +237,11 @@ namespace WebAPI.Services
}
else if (e.Message.Type == MessageType.Sticker && e.Source.GroupId == LineGroup.Ark.EnumToDescriptionString() && e.Message.PackageId == "1011092" && e.Message.StickerId == "510712")
{
//else if (e.Message.Type == MessageType.Sticker && e.Source.GroupId == LineGroup.Ark.EnumToDescriptionString() && e.Message.PackageId == "1011092" && e.Message.StickerId == "510712")
//{
await ReplyLineMessage(e.Source.GroupId, autoReplyCommands.Where(ar => ar.Commands.Contains("pray")).FirstOrDefault().LineMessage);
}
// await ReplyLineMessage(e.Source.GroupId, autoReplyCommands.Where(ar => ar.Commands.Contains("pray")).FirstOrDefault().LineMessage);
//}
}
}
@@ -229,7 +256,7 @@ namespace WebAPI.Services
}
public async Task<bool> PushCommandMessage(LineGroup group, string command)
public async Task<bool> PushCommandMessage(PastoralDomain group, string command)
{
try
{
@@ -238,32 +265,34 @@ namespace WebAPI.Services
{
command = command.ToLower().Substring(1);
var autoReply = autoReplyCommands.Where(ar => ar.SupportGroups.Contains(group) && ar.Commands.Contains(command)).FirstOrDefault();
var autoReply = autoReplyCommands.Where(ar =>
ar.SupportGroups.Contains(cellGroup.Type) &&
ar.Enabled(cellGroup, command)).FirstOrDefault();
if (autoReply != null)
{
if (autoReply.LineMessage != null)
{
await ReplyLineMessage(group.EnumToDescriptionString(), autoReply.LineMessage);
await ReplyLineMessage(cellGroup.LineGroupId, autoReply.LineMessage);
}
else
{
await ReplyTextMessage(group.EnumToDescriptionString(), autoReply.ReplyMessage);
await ReplyTextMessage(cellGroup.LineGroupId, autoReply.ReplyTextMessage);
}
return true;
}
else if (command == "help" || command == "?")
{
StringBuilder commandText = new StringBuilder();
commandText.AppendLine("方舟資訊部 - 指令清單");
foreach (var ar in autoReplyCommands.Where(ar => ar.SupportGroups.Contains(group)))
{
commandText.AppendLine($"{string.Join(", ", ar.Commands.Select(s => $"#{s}"))} - {ar.Description}");
}
commandText.Append($"#help, #? - 顯示指令清單");
await ReplyTextMessage(group.EnumToDescriptionString(), new string[] { commandText.ToString() });
}
//else if (command == "help" || command == "?")
//{
// StringBuilder commandText = new StringBuilder();
// commandText.AppendLine("方舟資訊部 - 指令清單");
// foreach (var ar in autoReplyCommands.Where(ar => ar.SupportGroups.Contains(group)))
// {
// commandText.AppendLine($"{string.Join(", ", ar.Commands.Select(s => $"#{s}"))} - {ar.Description}");
// }
// commandText.Append($"#help, #? - 顯示指令清單");
// await ReplyTextMessage(group.EnumToDescriptionString(), new string[] { commandText.ToString() });
//}
+16 -2
View File
@@ -1,6 +1,7 @@
using Church.Net.Utility;
using System;
using System.Threading.Tasks;
using WebAPI.Logics;
using WebAPI.Services.Interfaces;
namespace WebAPI.Services.ScheduledTask
@@ -9,14 +10,17 @@ namespace WebAPI.Services.ScheduledTask
{
private readonly LineAutoBotService lineAutoBotService;
private readonly ILoggingService loggingService;
private readonly PastoralDomainLogic pastoralDomainLogic;
private DateTime? nextRunningTime = null;
public MorningPrayer(
LineAutoBotService lineAutoBotService,
ILoggingService loggingService
ILoggingService loggingService,
PastoralDomainLogic pastoralDomainLogic
)
{
this.lineAutoBotService = lineAutoBotService;
this.loggingService = loggingService;
this.pastoralDomainLogic = pastoralDomainLogic;
this.SetNextRunningTime();
}
public string Description => "Sent out Ark Morning Prayer";
@@ -35,7 +39,17 @@ namespace WebAPI.Services.ScheduledTask
public Task<bool> RunTask()
{
SetNextRunningTime();
return lineAutoBotService.PushCommandMessage(LineGroup.Ark, "#pray");
return Task.Run(async () =>
{
var list = pastoralDomainLogic.GetAll(p => p.Type == Church.Net.Entity.DomainType.CellGroup);
foreach (var group in list)
{
await lineAutoBotService.PushCommandMessage(group, "#pray");
}
return true;
});
}
private void SetNextRunningTime()
{
+20 -15
View File
@@ -7,23 +7,21 @@ using System.Collections.Generic;
using System.Linq;
using Church.Net.Utility;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace WebAPI.Services
{
public class WorkerService : BackgroundService
{
private IEnumerable<IScheduledTask> scheduledTasks;
private ILoggingService loggingService;
private readonly IServiceProvider serviceProvider;
private readonly IWebHostEnvironment env;
private static bool initialized = false;
public WorkerService(
IEnumerable<IScheduledTask> scheduledTasks,
ILoggingService loggingService
IServiceProvider serviceProvider
)
{
this.scheduledTasks = scheduledTasks;
this.loggingService = loggingService;
this.serviceProvider = serviceProvider;
}
private const int generalDelay = 5 * 60 * 1000; // 10 seconds
@@ -48,21 +46,28 @@ namespace WebAPI.Services
//}
var now = DateTimeHelper.Now();
foreach (var worker in scheduledTasks)
using (var scope = serviceProvider.CreateScope())
{
try
var scheduledTasks = scope.ServiceProvider.GetRequiredService<IEnumerable<IScheduledTask>>();
var loggingService = scope.ServiceProvider.GetRequiredService<ILoggingService>();
foreach (var worker in scheduledTasks)
{
if (worker.CheckTime(now))
try
{
loggingService.Log($"Running {worker.Description}");
await worker.RunTask();
if (worker.CheckTime(now))
{
loggingService.Log($"Running {worker.Description}");
await worker.RunTask();
}
}
catch (Exception ex)
{
loggingService.Error(ex, worker.Description);
}
}
catch (Exception ex)
{
loggingService.Error(ex, worker.Description);
}
}
return "Done";
}