Initial commit

This commit is contained in:
Chris Chen
2022-09-08 08:04:32 -07:00
commit 184db15773
4604 changed files with 503905 additions and 0 deletions
@@ -0,0 +1,241 @@
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 ArArkCellGroupDinner : IAutoReplyCommand
{
public ArArkCellGroupDinner(ChurchNetContext context,
CellGroupLogic logic)
{
this._context = context;
this.logic = logic;
}
private static readonly string[] COMMANDS = { "晚餐", "dinner" };
private static readonly LineGroup[] GROUPS = {
LineGroup.Ark,
LineGroup.Chris,
};
private readonly ChurchNetContext _context;
private readonly CellGroupLogic 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 = _context.CellGroupRoutineEvents.Where(e => e.Time >= DateTime.Today)
.Include(e => e.Attendees).FirstOrDefault();
if (_event == null)
{
_event = new CellGroupRoutineEvent()
{
Id = Format.Get33BaseGuid(),
Time = DateTimeHelper.GetNextWeekday(DateTime.Today, DayOfWeek.Friday).AddHours(19).AddMinutes(30),
Address = "1881 Forest Dr., Azusa, CA 91702",
Attendees = new List<CellGroupRoutineEventAttendee>()
};
_context.Add(_event);
_context.SaveChanges();
}
sb.AppendLine($"{_event.Time.ToString("MM/dd HH:mm tt")} 開飯~");
sb.AppendLine("======= 晚宴清單 =======");
foreach (var a in _event.Attendees)
{
sb.AppendLine($"{a.Name} - {string.Join(", ", a.PotluckItem.Split('|'))}");
if (!string.IsNullOrWhiteSpace(a.Comment))
{
comments.AppendLine($"{a.Name}:{a.Comment}");
}
}
if (comments.Length > 0)
{
sb.AppendLine("========= 備註 =========");
sb.Append(comments.ToString());
}
return new string[] { sb.ToString() };
}
}
public IEnumerable<ILineMessage> LineMessage
{
get
{
var random = new Random();
List<ILineMessage> list = new List<ILineMessage>();
var _event = logic.GetComingEvent();
string title = "小組晚宴,吃飯皇帝大";
string imageUrl = "https://happiness.tours/assets/images/dinner.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.38:1"
}
);
#endregion
#region Body
var bodyContent = flexMessage.Contents.InitBody();
TimeSpan ts = _event.Time - 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 _event.Attendees)
{
var name = a.Name;// logic.GetMemberFirstNameById(a.MemberId);
var baseLineBox = new LineFlexBox()
{
Layout = FlexObjectBoxLayout.Baseline,
};
baseLineBox.Contents.Add(
new LineFlexText(name)
{
Size = FlexObjectSize.sm,
Color = "#aaaaaa",
Flex = 1
});
baseLineBox.Contents.Add(
new LineFlexText(
string.Join(", ", a.PotluckItem.Split('|')
.Where(s => !String.IsNullOrWhiteSpace(s))
)
)
{
Size = FlexObjectSize.sm,
Color = "#666666",
Flex = 5,
Wrap = true
});
if (!string.IsNullOrWhiteSpace(a.Comment))
{
var commentLineBox = new LineFlexBox()
{
Layout = FlexObjectBoxLayout.Baseline,
};
commentLineBox.Contents.Add(
new LineFlexText(name)
{
Size = FlexObjectSize.sm,
Color = "#aaaaaa",
Flex = 1
});
commentLineBox.Contents.Add(
new LineFlexText(a.Comment)
{
Size = FlexObjectSize.sm,
Color = "#666666",
Flex = 5
});
comments.Add(commentLineBox);
}
bodyContent.Add(baseLineBox);
}
if (comments.Count > 0)
{
bodyContent.Add(
new LineFlexText("備註")
{
Size = FlexObjectSize.md,
Weight = FlexObjectTextWeidht.Bold,
//Style = "Italic"
});
foreach (var item in comments)
{
bodyContent.Add(item);
}
}
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;
}
}
}
}
@@ -0,0 +1,33 @@
using LineMessaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.Services.Interfaces;
namespace WebAPI.Services.AutoReplyCommands
{
public class ArArkCellGroupInfo : IAutoReplyCommand
{
private static readonly string[] COMMANDS = { "方舟", "方舟小組", "ark" };
private static readonly string[] MESSAGES = {
"新生命靈糧堂 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;
public IEnumerable<ILineMessage> LineMessage => null;
}
}
@@ -0,0 +1,297 @@
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 ArArkCellGroupPrayer : IAutoReplyCommand
{
public ArArkCellGroupPrayer(
CellGroupLogic logic
)
{
this.logic = logic;
this.bibleReferrences = new List<BibleReferrence>();
bibleReferrences.Add(new BibleReferrence(
"腓立比書 4:6-7",
"應當一無掛慮,只要凡事藉著禱告、祈求和感謝,將你們所要的告訴神。神所賜出人意外的平安必在基督耶穌裡保守你們的心懷意念。"
));
bibleReferrences.Add(new BibleReferrence(
"馬太福音 7:7-8",
"你們祈求,就給你們;尋找,就尋見;叩門,就給你們開門。因為凡祈求的,就得著;尋找的,就尋見;叩門的,就給他開門。"
));
bibleReferrences.Add(new BibleReferrence(
"耶利米書 29:12",
"你們要呼求我,禱告我,我就應允你們。"
));
bibleReferrences.Add(new BibleReferrence(
"馬太福音 18:19-20",
"我又告訴你們,若是你們中間有兩個人在地上同心合意地求什麼事,我在天上的父必為他們成全。因為無論在哪裡,有兩三個人奉我的名聚會,那裡就有我在他們中間。"
));
bibleReferrences.Add(new BibleReferrence(
"路加福音 11:2-4",
"耶穌說:「你們禱告的時候,要說:『我們在天上的父(有古卷只作:父啊):願人都尊你的名為聖。願你的國降臨;願你的旨意行在地上,如同行在天上(有古卷無願你的旨意云云)。我們日用的飲食,天天賜給我們。赦免我們的罪,因為我們也赦免凡虧欠我們的人。不叫我們遇見試探;救我們脫離凶惡(有古卷無末句)。』」"
));
bibleReferrences.Add(new BibleReferrence(
"馬太福音 21:22",
"主耶穌說:「你們禱告,無論求什麼,只要信,就必得著。」"
));
bibleReferrences.Add(new BibleReferrence(
"馬太福音 6:5",
"你們禱告的時候,不可像那假冒為善的人,愛站在會堂裡和十字路口上禱告,故意叫人看見。我實在告訴你們,他們已經得了他們的賞賜。"
));
bibleReferrences.Add(new BibleReferrence(
"馬太福音 6:6-7",
"你禱告的時候,要進你的內屋,關上門,禱告你在暗中的父;你父在暗中察看,必然報答你。你們禱告,不可像外邦人,用許多重複話,他們以為話多了必蒙垂聽。"
));
bibleReferrences.Add(new BibleReferrence(
"馬太福音 26:41",
"總要儆醒禱告,免得入了迷惑。你們心靈固然願意,肉體卻軟弱了。"
));
bibleReferrences.Add(new BibleReferrence(
"雅各書 5:16",
"所以你們要彼此認罪,互相代求,使你們可以得醫治。義人祈禱所發的力量是大有功效的。"
));
}
private static readonly string[] COMMANDS = { "禱告", "代禱", "letspray", "pray" };
private static readonly LineGroup[] GROUPS = {
LineGroup.Ark,
LineGroup.Chris,
LineGroup.ArkCowoker,
};
private readonly CellGroupLogic 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<ILineMessage> LineMessage
{
get
{
var random = new Random();
int index = random.Next(bibleReferrences.Count);
var bibleSentence = bibleReferrences[index];
List<ILineMessage> list = new List<ILineMessage>();
var _event = logic.GetLastEvent();
string title = "禱告中心 普壘森特";
string imageUrl = "https://dailyverses.net/images/tc/cuv/matthew-21-22-3.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,
}
);
#endregion
#region Body
var bodyContent = flexMessage.Contents.InitBody();
bodyContent.Add(
new LineFlexText("代禱項目")
{
Size = FlexObjectSize.md,
Weight = FlexObjectTextWeidht.Bold,
OffsetBottom = FlexObjectSize.md
});
//$"目前暫無禱告事項唷, 趕快來新增代禱事項吧!!"
List<LineFlexBox> comments = new List<LineFlexBox>();
if (_event == null || _event.Prayers.Count == 0)
{
bodyContent.Add(
new LineFlexText("目前暫無禱告事項唷, 趕快來新增代禱事項吧!!")
{
Size = FlexObjectSize.md,
Color = "#666666",
});
}
else
{
foreach (var a in _event.Prayers)
{
var name = logic.GetMemberFirstNameById(a.MemberId);
var baseLineBox = new LineFlexBox()
{
Layout = FlexObjectBoxLayout.Baseline,
};
baseLineBox.Contents.Add(
new LineFlexText(name)
{
Size = FlexObjectSize.sm,
Color = "#aaaaaa",
Flex = 1
});
baseLineBox.Contents.Add(
new LineFlexText(
string.Join(", ", a.Prayer.Split('|')
.Where(s => !String.IsNullOrWhiteSpace(s))
)
)
{
Size = FlexObjectSize.sm,
Color = "#666666",
Flex = 5,
Wrap = true
});
if (!string.IsNullOrWhiteSpace(a.Comment))
{
var commentLineBox = new LineFlexBox()
{
Layout = FlexObjectBoxLayout.Baseline,
};
commentLineBox.Contents.Add(
new LineFlexText(name)
{
Size = FlexObjectSize.sm,
Color = "#aaaaaa",
Flex = 1
});
commentLineBox.Contents.Add(
new LineFlexText(a.Comment)
{
Size = FlexObjectSize.sm,
Color = "#666666",
Flex = 5
});
comments.Add(commentLineBox);
}
bodyContent.Add(baseLineBox);
}
if (comments.Count > 0)
{
bodyContent.Add(
new LineFlexText("備註")
{
Size = FlexObjectSize.md,
Weight = FlexObjectTextWeidht.Bold,
//Style = "Italic"
});
foreach (var item in comments)
{
bodyContent.Add(item);
}
}
}
bodyContent.Add(new LineFlexSeparator());
#endregion
#region Footer
flexMessage.Contents.InitFooter()
.Add(
new LineFlexButton()
{
Action = new UriAction()
{
Uri = "https://happiness.tours/CellGroup/prayer?openExternalBrowser=1",
Label = "我的代禱事項"
}
}
);
#endregion
list.Insert(0, flexMessage);
return list;
}
}
private List<BibleReferrence> bibleReferrences;
}
class BibleReferrence
{
public BibleReferrence(string from, string content)
{
From = from;
Content = content;
}
public string From { get; set; }
public string Content { get; set; }
}
}
@@ -0,0 +1,31 @@
using LineMessaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.Services.Interfaces;
namespace WebAPI.Services.AutoReplyCommands
{
public class ArChurchInfo : IAutoReplyCommand
{
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
};
public string Description => "顯示教會主日聚會資訊";
public IEnumerable<string> Commands => COMMANDS;
public IEnumerable<string> ReplyMessage => MESSAGES;
public IEnumerable<LineGroup> SupportGroups => GROUPS;
public IEnumerable<ILineMessage> LineMessage => null;
}
}
+165
View File
@@ -0,0 +1,165 @@
using System.Collections.Generic;
using System.Linq;
using System;
using WebAPI.Services.Interfaces;
using System.Diagnostics;
using Church.Net.Entity;
using Church.Net.Entity.Interface;
using Church.Net.DAL.EFCoreDBF;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace WebAPI.Services
{
public class DbLoggingService : ILoggingService
{
private readonly ICrudDAL<LogInfo> crudDAL;
public DbLoggingService(ICrudDAL<LogInfo> crudDAL)
{
this.crudDAL = crudDAL;
}
public int Error(Exception exception)
{
string msg = exception.Message.ToString();
string detailMsg = exception.InnerException != null ? exception.InnerException.Message : "";
LogInfo log = new LogInfo(LogLevel.Error)
{
Message = msg,
DetailMessage = detailMsg,
Source = exception.Source,
StackTrace = exception.StackTrace,
UserId = ""
};
return AppendLog(log);
}
public int Error(Exception exception, string from)
{
string msg = exception.Message.ToString();
string detailMsg = exception.InnerException != null ? exception.InnerException.Message : "";
LogInfo log = new LogInfo(LogLevel.Error)
{
Url = from,
Message = msg,
DetailMessage = detailMsg,
Source = exception.Source,
StackTrace = exception.StackTrace
};
return AppendLog(log);
}
public int Error(Exception exception, string from, string detailMsg)
{
string msg = exception.Message.ToString();
string exceptionDetailMsg = exception.InnerException != null ? exception.InnerException.Message : "";
if (false == string.IsNullOrEmpty(exceptionDetailMsg))
{
detailMsg += Environment.NewLine + "=========== Exception Detail ==========";
detailMsg += Environment.NewLine + exceptionDetailMsg;
}
LogInfo log = new LogInfo(LogLevel.Error)
{
Url = from,
Message = msg,
DetailMessage = detailMsg,
Source = exception.Source,
StackTrace = exception.StackTrace
};
return AppendLog(log);
}
public IEnumerable<LogInfo> GetAllErrors(DateTime? rangeStart = null, DateTime? rangeEnd = null)
{
IQueryable<LogInfo> query = crudDAL.GetDbSet().AsQueryable();
if (rangeStart != null)
{
query = query.Where(l => l.Time >= rangeStart);
}
if (rangeEnd != null)
{
query = query.Where(l => l.Time <= rangeEnd);
}
return query.OrderByDescending(l => l.Time).ToList();
}
private int AppendLog(LogInfo log)
{
try
{
crudDAL.Create(log);
return log.TrackNo;
}
catch (Exception ex)
{
WriteWindowsEventLog(ex);
WriteWindowsEventLog(log);
return -1;
}
}
private void WriteWindowsEventLog(LogInfo log)
{
//var fileLogService = new FileLoggingService();
//fileLogService.Error(new Exception(
// log.Source + Environment.NewLine + Environment.NewLine +
// log.Message + Environment.NewLine + Environment.NewLine +
// log.DetailMessage
// ));
EventLog.WriteEntry("BeyondAPI",
log.Source + Environment.NewLine + Environment.NewLine +
log.Message + Environment.NewLine + Environment.NewLine +
log.DetailMessage
, EventLogEntryType.Error);
}
private void WriteWindowsEventLog(Exception ex)
{
//var fileLogService = new FileLoggingService();
//fileLogService.Error(ex, "Can Not Append Error Log");
EventLog.WriteEntry("BeyondAPI", $"Can Not Append Error Log:{ex.Message}", EventLogEntryType.Error);
}
public void Log(string message, object detail)
{
LogInfo log = new LogInfo(LogLevel.Info)
{
Message = message,
DetailMessage = JsonConvert.SerializeObject(detail,Formatting.Indented) ,
//Source = exception.Source,
//StackTrace = exception.StackTrace
};
AppendLog(log);
}
public void Warning(string message, object detail)
{
LogInfo log = new LogInfo(LogLevel.Warning)
{
Message = message,
DetailMessage = JsonConvert.SerializeObject(detail, Formatting.Indented),
//Source = exception.Source,
//StackTrace = exception.StackTrace
};
AppendLog(log);
}
IEnumerable<LogInfo> ILoggingService.GetAllErrors(DateTime? rangeStart, DateTime? rangeEnd)
{
throw new NotImplementedException();
}
public IEnumerable<LogInfo> GetAllLogs(LogLevel logLevel, DateTime? rangeStart = null, DateTime? rangeEnd = null)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,17 @@
using LineMessaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI.Services.Interfaces
{
public interface IAutoReplyCommand
{
string Description { get; }
IEnumerable<string> Commands { get; }
IEnumerable<string> ReplyMessage { get; }
IEnumerable<LineGroup> SupportGroups { get; }
IEnumerable<ILineMessage> LineMessage { get; }
}
}
@@ -0,0 +1,19 @@
using System.Collections.Generic;
using System;
using Church.Net.Entity;
using Church.Net.Entity.Interface;
namespace WebAPI.Services.Interfaces
{
public interface ILoggingService
{
void Log(string message, object detail);
void Warning(string message, object detail);
int Error(Exception exception);
int Error(Exception exception, string from);
int Error(Exception exception, string from, string detailMsg);
IEnumerable<LogInfo> GetAllErrors(DateTime? rangeStart = null, DateTime? rangeEnd = null);
IEnumerable<LogInfo> GetAllLogs(LogLevel logLevel, DateTime? rangeStart = null, DateTime? rangeEnd = null);
}
}
+295
View File
@@ -0,0 +1,295 @@
using Church.Net.Utility;
using LineMessaging;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebAPI.Services.Interfaces;
using static System.Net.Mime.MediaTypeNames;
namespace WebAPI.Services
{
[Flags]
public enum LineGroup
{
[Description("Cac4ac5a8d7fc52daa444d71dc7c360a9")]
Ark = 1 << 0,
[Description("Ca20e3b65aa58e676815eb13c3222591a")]
ArkCowoker = 1 << 1,
[Description("U97e9e579a41a5222e33bf68a3bf479a0")]
Chris = ~(~0 << 20),
}
public class LineAutoBotService
{
private readonly IEnumerable<IAutoReplyCommand> autoReplyCommands;
private readonly ILoggingService loggingService;
public LineAutoBotService(
IEnumerable<IAutoReplyCommand> autoReplyCommands,
ILoggingService loggingService
)
{
this.autoReplyCommands = autoReplyCommands;
this.loggingService = loggingService;
}
public void SendTextMessage(string text, LineGroup target)
{
var test = new LineMessagingClient();
try
{
var wait = test.PushMessage(EnumHelper.EnumToDescriptionString(target), new LineTextMessage() { Text = text })
.GetAwaiter();
wait.GetResult();
}
catch (Exception ex)
{
this.loggingService.Error(ex);
}
}
public async Task<bool> ReplyTextMessage(string replyToken, IEnumerable<string> textMessages)
{
var test = new LineMessagingClient();
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);
return true;
}
catch (Exception ex)
{
this.loggingService.Error(ex, "ReplyTextMessage:68", JsonConvert.SerializeObject(replyMessage, Formatting.Indented));
return false;
}
}
public async Task<bool> ReplyLineMessage(string replyToken, IEnumerable<ILineMessage> lineMessages)
{
var test = new LineMessagingClient();
var replyMessage = new LinePushMessage() { To = replyToken };
replyMessage.Messages = lineMessages;
try
{
//var wait= test.PushMessage(replyMessage).GetAwaiter();
//wait.GetResult();
await test.PushMessage(replyMessage);
return true;
}
catch (Exception ex)
{
this.loggingService.Error(ex, "ReplyLineMessage:84", JsonConvert.SerializeObject(replyMessage, Formatting.Indented));
return false;
}
}
public async Task<bool> AutoReply(LineWebhookContent content)
{
loggingService.Log("AutoReply", content);
try
{
foreach (var e in content.Events)
{
if (e.Message.Type == MessageType.Text)
{
List<string> textMessages = new List<string>();
string replyToken = e.ReplyToken;
string text = e.Message.Text;
string target = "";
switch (e.Source.Type)
{
case WebhookRequestSourceType.User:
target = e.Source.UserId;
break;
case WebhookRequestSourceType.Group:
target = e.Source.GroupId;
break;
case WebhookRequestSourceType.Room:
target = e.Source.RoomId;
break;
default:
break;
}
if (!String.IsNullOrWhiteSpace(replyToken) && text.IndexOf("#") == 0)
{
text = text.ToLower().Substring(1);
var group = EnumHelper.GetEnumValueFromDescription<LineGroup>(target);
var autoReply = autoReplyCommands.Where(ar => ar.SupportGroups.Contains(group) && ar.Commands.Contains(text)).FirstOrDefault();
if (autoReply != null)
{
if (autoReply.LineMessage != null)
{
await ReplyLineMessage(target, autoReply.LineMessage);
}
else
{
await ReplyTextMessage(replyToken, autoReply.ReplyMessage);
}
return true;
}
else if (text == "help" || text == "?")
{
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(replyToken, new string[] { commandText.ToString() });
}
}
}
this.LogLineMessage(e);
}
}
catch (Exception ex)
{
loggingService.Error(ex, "AutoReply:188", JsonConvert.SerializeObject(content, Formatting.Indented));
return false;
}
return true;
}
public async Task<bool> PushCommandMessage(LineGroup group, string command)
{
try
{
if (command.IndexOf("#") == 0)
{
command = command.ToLower().Substring(1);
var autoReply = autoReplyCommands.Where(ar => ar.SupportGroups.Contains(group) && ar.Commands.Contains(command)).FirstOrDefault();
if (autoReply != null)
{
if (autoReply.LineMessage != null)
{
await ReplyLineMessage(group.EnumToDescriptionString(), autoReply.LineMessage);
}
else
{
await ReplyTextMessage(group.EnumToDescriptionString(), autoReply.ReplyMessage);
}
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() });
}
}
}
catch (Exception ex)
{
loggingService.Error(ex, "AutoReply:188",command);
return false;
}
return true;
}
private void LogLineMessage(LineWebhookContent.Event e)
{
return;
try
{
//var lineHookRequest = new LineMessaging.LineWebhookRequest("d23edf453427256a759d218ec8b6779f", request);
//var content = await lineHookRequest.GetContent();
string txtPath = ServerUtils.MapPath("App_Data/LinePostLog.txt");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"==================={DateTime.Now.ToString("MM/dd/yyyy HH:mm")}=========================");
stringBuilder.AppendLine($"Message Type:{e.Type.ToString()}");
switch (e.Source.Type)
{
case WebhookRequestSourceType.User:
stringBuilder.AppendLine($"UserId:{e.Source.UserId}");
break;
case WebhookRequestSourceType.Group:
stringBuilder.AppendLine($"GroupId:{e.Source.GroupId}");
break;
case WebhookRequestSourceType.Room:
stringBuilder.AppendLine($"RoomId:{e.Source.RoomId}");
break;
default:
break;
}
stringBuilder.AppendLine($"Reply Token:{e.ReplyToken}");
stringBuilder.AppendLine($"Message Type:{e.Message.Type.ToString()}");
switch (e.Message.Type)
{
case MessageType.Text:
stringBuilder.AppendLine($"Message:{e.Message.Text}");
break;
case MessageType.Image:
case MessageType.Video:
case MessageType.Audio:
case MessageType.File:
case MessageType.Location:
case MessageType.Sticker:
case MessageType.Imagemap:
case MessageType.Template:
default:
stringBuilder.AppendLine($"Message:{JsonConvert.SerializeObject(e.Message, Formatting.Indented)}");
break;
}
System.IO.File.AppendAllText(txtPath, stringBuilder.ToString());
}
catch (Exception ex)
{
}
}
}
}