Skip to content

Commit

Permalink
bugfix
Browse files Browse the repository at this point in the history
  • Loading branch information
chr233 committed Feb 21, 2023
1 parent fc588e3 commit fc5fdb9
Show file tree
Hide file tree
Showing 13 changed files with 93 additions and 88 deletions.
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>2.0.18.2</Version>
<Version>2.0.19.0</Version>
</PropertyGroup>

<PropertyGroup>
Expand Down
8 changes: 4 additions & 4 deletions XinjingdailyBot.Command/AdminCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ async Task<string> exec()
}
catch (Exception ex)
{
_logger.LogError("发送私聊消息失败 {Message}", ex.Message);
_logger.LogError(ex, "发送私聊消息失败");
}

StringBuilder sb = new();
Expand Down Expand Up @@ -319,7 +319,7 @@ async Task<string> exec()
}
catch (Exception ex)
{
_logger.LogError("发送私聊消息失败 {Message}", ex.Message);
_logger.LogError(ex, "发送私聊消息失败");
}

StringBuilder sb = new();
Expand Down Expand Up @@ -462,7 +462,7 @@ async Task<string> exec()
}
catch (Exception ex)
{
_logger.LogError("发送私聊消息失败 {Message}", ex.Message);
_logger.LogError(ex, "发送私聊消息失败");
}

return sb.ToString();
Expand Down Expand Up @@ -1066,7 +1066,7 @@ async Task<string> exec()
}
catch (Exception ex)
{
_logger.LogError("向用户 {targetUser} 发送消息失败, {ex}", targetUser, ex);
_logger.LogError(ex, "向用户 {targetUser} 发送消息失败", targetUser);
}
}

Expand Down
27 changes: 20 additions & 7 deletions XinjingdailyBot.Command/NormalCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ public async Task QGetRandomPost(Users dbUser, CallbackQuery callbackQuery, stri
bool hasSpoiler = randomPost.HasSpoiler;
Chat? chat = callbackQuery.Message!.Chat;

if (randomPost.IsMediaGroup && false)
if (randomPost.IsMediaGroup)
{
var attachments = await _attachmentService.Queryable().Where(x => x.PostID == randomPost.Id).ToListAsync();
var group = new IAlbumInputMedia[attachments.Count];
Expand All @@ -366,15 +366,14 @@ public async Task QGetRandomPost(Users dbUser, CallbackQuery callbackQuery, stri
}

var messages = await _botClient.SendMediaGroupAsync(chat, group);

await _botClient.SendTextMessageAsync(chat, "随机稿件操作", replyMarkup: keyboard);
}
else
{
Attachments attachment = await _attachmentService.Queryable().FirstAsync(x => x.PostID == randomPost.Id);
var handler = randomPost.PostType switch
{
MessageType.Text => _botClient.SendTextMessageAsync(chat, randomPost.Text, replyMarkup: keyboard),
MessageType.Text => _botClient.SendTextMessageAsync(chat, randomPost.Text),
MessageType.Photo => _botClient.SendPhotoAsync(chat, new InputFileId(attachment.FileID), caption: randomPost.Text, parseMode: ParseMode.Html, replyMarkup: keyboard, hasSpoiler: hasSpoiler),
MessageType.Audio => _botClient.SendAudioAsync(chat, new InputFileId(attachment.FileID), caption: randomPost.Text, parseMode: ParseMode.Html, replyMarkup: keyboard, title: attachment.FileName),
MessageType.Video => _botClient.SendVideoAsync(chat, new InputFileId(attachment.FileID), caption: randomPost.Text, parseMode: ParseMode.Html, replyMarkup: keyboard, hasSpoiler: hasSpoiler),
Expand All @@ -386,17 +385,31 @@ public async Task QGetRandomPost(Users dbUser, CallbackQuery callbackQuery, stri

if (handler == null)
{
await _botClient.AutoReplyAsync($"不支持的稿件类型: {randomPost.PostType}", callbackQuery);
await _botClient.AutoReplyAsync($"不支持的稿件类型: {randomPost.PostType}", callbackQuery, true);
await _botClient.EditMessageTextAsync(callbackQuery.Message!, $"不支持的稿件类型: {randomPost.PostType}", null);
return;
}

var message = await handler;
try
{
var message = await handler;
}
catch (Exception ex)
{
int i = 0;
}
}

//去除第一条消息的按钮
var kbd = args.Length > 3 ? _markupHelperService.LinkToOriginPostKeyboard(args[3]) : null;
await _botClient.EditMessageReplyMarkupAsync(callbackQuery.Message!, kbd);
if (args.Length > 3 && long.TryParse(args[3], out long msgId))
{
var kbd = _markupHelperService.LinkToOriginPostKeyboard(msgId);
await _botClient.EditMessageReplyMarkupAsync(callbackQuery.Message!, kbd);
}
else
{
await _botClient.EditMessageReplyMarkupAsync(callbackQuery.Message!, null);
}
}
else
{
Expand Down
2 changes: 1 addition & 1 deletion XinjingdailyBot.Command/SuperCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task ResponseRestart(Message message)
catch (Exception ex)
{
await _botClient.SendCommandReply("启动进程遇到错误", message);
_logger.LogError("启动进程遇到错误", ex);
_logger.LogError(ex, "启动进程遇到错误");
}
}

Expand Down
10 changes: 9 additions & 1 deletion XinjingdailyBot.Infrastructure/Extensions/ChatExtension.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Telegram.Bot.Types;
using System.Threading.Channels;
using Telegram.Bot.Types;

namespace XinjingdailyBot.Infrastructure.Extensions
{
Expand Down Expand Up @@ -33,5 +34,12 @@ public static string EscapedChatName(this Chat chat)
{
return chat.Title?.EscapeHtml() ?? "";
}

public static string GetMessageLink (this Chat chat,long messageId)
{
string link = !string.IsNullOrEmpty(chat.Username) ? $"https://t.me/{chat.Username}/{messageId}" : $"https://t.me/c/{chat.Id}/{messageId}";
return link;

}
}
}
2 changes: 1 addition & 1 deletion XinjingdailyBot.Interface/Helper/IMarkupHelperService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public interface IMarkupHelperService
{
InlineKeyboardMarkup DirectPostKeyboard(bool anymouse, int tagNum, bool? hasSpoiler);
InlineKeyboardMarkup? LinkToOriginPostKeyboard(Posts post);
InlineKeyboardMarkup? LinkToOriginPostKeyboard(string link);
InlineKeyboardMarkup? LinkToOriginPostKeyboard(long messageId);
InlineKeyboardMarkup PostKeyboard(bool anymouse);
InlineKeyboardMarkup RandomPostMenuKeyboard(Users dbUser);
InlineKeyboardMarkup RandomPostMenuKeyboard(Users dbUser, int tagNum);
Expand Down
2 changes: 1 addition & 1 deletion XinjingdailyBot.Service/Bot/Common/DispatcherService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private async Task UnPinMessage(Message message)
}
catch (Exception ex)
{
_logger.LogError("取消置顶出错", ex);
_logger.LogError(ex, "取消置顶出错");
}
}

Expand Down
2 changes: 1 addition & 1 deletion XinjingdailyBot.Service/Bot/Common/PollingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private async Task DoWork(CancellationToken stoppingToken)

catch (Exception ex)
{
_logger.LogError("接收服务运行出错: {Exception}", ex);
_logger.LogError(ex,"接收服务运行出错");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
Expand Down
4 changes: 2 additions & 2 deletions XinjingdailyBot.Service/Bot/Handler/CommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public async Task OnCommandReceived(Users dbUser, Message message)
catch (Exception ex)
{
errorMsg = $"{ex.GetType} {ex.Message}";

_logger.LogError(ex, "命令 {cmd} 执行出错", cmd);
await _botClient.SendCommandReply(_optionsSetting.Debug ? errorMsg : "遇到内部错误", message);
}
handled = true;
Expand Down Expand Up @@ -356,7 +356,7 @@ public async Task OnQueryCommandReceived(Users dbUser, CallbackQuery query)
catch (Exception ex) //无法捕获 TODO
{
errorMsg = $"{ex.GetType} {ex.Message}";

_logger.LogError(ex, "回调命令 {cmd} 执行出错", cmd);
await _botClient.AutoReplyAsync(_optionsSetting.Debug ? errorMsg : "遇到内部错误", query, true);
}
handled = true;
Expand Down
18 changes: 8 additions & 10 deletions XinjingdailyBot.Service/Helper/MarkupHelperService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Telegram.Bot.Types.ReplyMarkups;
using XinjingdailyBot.Infrastructure.Attribute;
using XinjingdailyBot.Infrastructure.Extensions;
using XinjingdailyBot.Infrastructure.Localization;
using XinjingdailyBot.Interface.Bot.Common;
using XinjingdailyBot.Interface.Helper;
Expand Down Expand Up @@ -316,18 +317,13 @@ public InlineKeyboardMarkup ReviewKeyboardB()
public InlineKeyboardMarkup? LinkToOriginPostKeyboard(Posts post)
{
var channel = _channelService.AcceptChannel;
string? username = channel.Username;

if (string.IsNullOrEmpty(username))
{
return null;
}
string link = channel.GetMessageLink(post.PublicMsgID);

InlineKeyboardMarkup keyboard = new(new[]
{
new []
{
InlineKeyboardButton.WithUrl($"{channel.Title}中查看", $"https://t.me/{username}/{post.PublicMsgID}"),
InlineKeyboardButton.WithUrl($"{channel.Title}中查看", link),
},
});
return keyboard;
Expand All @@ -338,9 +334,11 @@ public InlineKeyboardMarkup ReviewKeyboardB()
/// </summary>
/// <param name="link"></param>
/// <returns></returns>
public InlineKeyboardMarkup? LinkToOriginPostKeyboard(string link)
public InlineKeyboardMarkup? LinkToOriginPostKeyboard(long messageId)
{
var channel = _channelService.AcceptChannel;
string link = channel.GetMessageLink(messageId);

InlineKeyboardMarkup keyboard = new(new[]
{
new []
Expand Down Expand Up @@ -434,14 +432,14 @@ public InlineKeyboardMarkup RandomPostMenuKeyboard(Users dbUser, int tagNum)
public InlineKeyboardMarkup RandomPostMenuKeyboard(Users dbUser, Posts post, int tagId, string postType)
{
var channel = _channelService.AcceptChannel;
string link = !string.IsNullOrEmpty(channel.Username) ? $"https://t.me/{channel.Username}/{post.PublicMsgID}" : $"https://t.me/c/{channel.Id}/{post.PublicMsgID}";
string link = channel.GetMessageLink(post.PublicMsgID);

InlineKeyboardMarkup keyboard = new(new[]
{
new []
{
InlineKeyboardButton.WithUrl($"{channel.Title}中查看", link),
InlineKeyboardButton.WithCallbackData("再来一张",$"cmd {dbUser.UserID} randompost {tagId} {postType} {link}"),
InlineKeyboardButton.WithCallbackData("再来一张",$"cmd {dbUser.UserID} randompost {tagId} {postType} {post.PublicMsgID}"),
},
});

Expand Down
2 changes: 1 addition & 1 deletion XinjingdailyBot.Tasks/ExpiredPostsTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public async Task Execute(IJobExecutionContext context)
}
catch (Exception ex)
{
_logger.LogError("通知消息发送失败, 自动禁用更新 {error}", ex);
_logger.LogError(ex, "通知消息发送失败, 自动禁用更新");
user.PrivateChatID = -1;
await Task.Delay(5000);
}
Expand Down
2 changes: 1 addition & 1 deletion XinjingdailyBot.Tasks/PostAdvertiseTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task Execute(IJobExecutionContext context)
}
catch (Exception ex)
{
_logger.LogError("投放广告出错: {error}", ex.Message);
_logger.LogError(ex, "投放广告出错");
}
finally
{
Expand Down
100 changes: 43 additions & 57 deletions XinjingdailyBot.WebAPI/nlog.config
Original file line number Diff line number Diff line change
Expand Up @@ -5,93 +5,79 @@
internalLogLevel="Warn"
internalLogFile="${basedir}/logs/nlog-internal.txt">

<!-- Load the ASP.NET Core plugin,enable asp.net core layout renderers-->
<extensions>
<add assembly="NLog.Web.AspNetCore" />
</extensions>
<!-- Load the ASP.NET Core plugin,enable asp.net core layout renderers-->
<extensions>
<add assembly="NLog.Web.AspNetCore" />
</extensions>

<targets>
<targets>
<default-wrapper xsi:type="AsyncWrapper"></default-wrapper>

<!-- 控制台日志 -->
<!-- 网络请求日志 -->
<target name="consoleNet" xsi:type="ColoredConsole"
enableAnsiOutput="True"
layout="${level:format=FirstCharacter} ${date} [${logger:shortName=true}] | ${aspnet-request-iP} | ${aspnet-request-url}${newline} ${message}" />
<!-- SQL日志 -->
<target name="consoleSql" xsi:type="ColoredConsole"
enableAnsiOutput="True"
layout="${level:format=FirstCharacter} ${date} SQL${newline}${message}" />
<!-- 普通日志 -->
<target name="console" xsi:type="ColoredConsole"

<!-- 控制台日志 -->
<!-- 普通日志 -->
<target name="console" xsi:type="ColoredConsole"
errorStream="True"
enableAnsiOutput="True"
layout="${level:format=FirstCharacter} ${date} [${logger:shortName=true}] ${message}" />
<!-- 错误日志 -->
<target name="consoleError" xsi:type="ColoredConsole"
errorStream="True"
enableAnsiOutput="True"
layout="${level:format=FirstCharacter} ${date} [${logger:shortName=true}] ${message} ${exception:format=toString,Data}" />

<!-- 文件日志 -->
<!-- 网络请求日志 -->
<target name="filelogNet" xsi:type="File"
fileName="${basedir}/logs/net.txt"
archiveFileName="${basedir}/logs/net.{###}.txt"
<!-- 文件日志 -->
<!-- 普通日志 -->
<target name="filelog" xsi:type="File"
fileName="${basedir}/logs/log.txt"
archiveFileName="${basedir}/logs/log.${date:format=yyyy-MM-dd}.txt"
archiveEvery="Day"
archiveNumbering="DateAndSequence"
archiveAboveSize="20000000"
maxArchiveFiles="30"
archiveOldFileOnStartup="true"
keepFileOpen="true"
layout="${longdate} | ${level} | ${logger} | ${message} | ${aspnet-request-iP:CheckForwardedForHeader=true} | ${aspnet-request-url} | ${event-properties:item=requestParam} | ${event-properties:item=jsonResult} | ${onexception:${exception:format=tostring}" />
<!--SQL-->
<target name="filelogSql" xsi:type="File"
fileName="${basedir}/logs/all-sql.txt"
archiveFileName="${basedir}/logs/all.sql{###}.txt"
archiveEvery="Day"
archiveNumbering="DateAndSequence"
archiveAboveSize="20000000"
maxArchiveFiles="30"
keepFileOpen="true"
layout="${longdate} | ${level} |${newline}${message}" />
<!-- 普通日志 -->
<target name="filelog" xsi:type="File"
fileName="${basedir}/logs/log.txt"
archiveFileName="${basedir}/logs/log.{###}.txt"
layout="${longdate} | ${level} | ${logger} | ${message}" />
<!-- 错误日志 -->
<target name="fileErrorlog" xsi:type="File"
fileName="${basedir}/logs/error.txt"
archiveFileName="${basedir}/logs/error.${date:format=yyyy-MM-dd}.txt"
archiveEvery="Day"
archiveAboveSize="20000000"
maxArchiveFiles="30"
archiveOldFileOnStartup="true"
keepFileOpen="true"
layout="${longdate} | ${level} | ${logger} | ${message}" />
<!-- 全部日志 -->
<target name="filelogAll" xsi:type="File"
layout="${longdate} | ${level} | ${logger} | ${message} | ${exception:format=toString,Data}" />
<!-- 全部日志 -->
<target name="filelogAll" xsi:type="File"
fileName="${basedir}/logs/all.txt"
archiveFileName="${basedir}/logs/all.{###}.txt"
archiveFileName="${basedir}/logs/all.${date:format=yyyy-MM-dd}.txt"
archiveEvery="Day"
archiveAboveSize="20000000"
maxArchiveFiles="30"
archiveOldFileOnStartup="true"
keepFileOpen="true"
layout="${longdate} | ${level} | ${logger} | ${message}" />

<!--黑洞-->
<target name="blackhole" xsi:type="Null" />
</targets>
<!--黑洞-->
<target name="blackhole" xsi:type="Null" />
</targets>

<rules>
<!-- 除非调试需要,把 .NET Core 程序集的 Debug 输出都屏蔽 Trace -> Debug-> Info ->Warn-> Error-> Critical-->
<!-- 屏蔽日志 -->
<rules>
<!-- 除非调试需要,把 .NET Core 程序集的 Debug 输出都屏蔽 Trace -> Debug-> Info ->Warn-> Error-> Critical-->
<!-- 屏蔽日志 -->
<logger name="Microsoft.*" writeTo="blackhole" maxlevel="Warn" final="true" />
<logger name="Quartz.*" writeTo="blackhole" maxlevel="Warn" final="true" />
<logger name="System.*" writeTo="blackhole" maxlevel="Warn" final="true" />

<!-- SQL日志 -->
<!-- SQL日志 -->
<logger name="XinjingdailyBot.WebAPI.Extensions.DatabaseExtension" writeTo="console" final="true" />
<logger name="XinjingdailyBot.WebAPI.Extensions.DatabaseExtension" writeTo="consoleSql" final="true" />
<logger name="XinjingdailyBot.WebAPI.Extensions.DatabaseExtension" writeTo="filelogSql" final="true" />

<!-- 控制台日志 -->
<logger name="*" minLevel="Debug" writeTo="console" />
<!-- 控制台日志 -->
<logger name="*" minLevel="Error" writeTo="consoleError" />
<logger name="*" minLevel="Debug" writeTo="console" />

<!-- 文件日志 -->
<logger name="*" minLevel="Info" writeTo="filelog" />
<logger name="*" minLevel="Trace" writeTo="allfile" />
</rules>
<!-- 文件日志 -->
<logger name="*" minLevel="Error" writeTo="fileErrorlog"/>
<logger name="*" minLevel="Info" writeTo="filelog" />
<logger name="*" minLevel="Trace" writeTo="allfile" />
</rules>
</nlog>

0 comments on commit fc5fdb9

Please sign in to comment.