qqbot #1

Merged
milimoe merged 8 commits from qqbot into master 2025-08-02 10:45:22 +00:00
11 changed files with 1242 additions and 188 deletions
Showing only changes of commit f098b808d2 - Show all commits

View File

@ -3,7 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RainBOT-CSharp", "src\RainBOT.csproj", "{46A60688-46D6-4414-A079-7DC0C95B5A37}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RainBOT", "src\RainBOT.csproj", "{46A60688-46D6-4414-A079-7DC0C95B5A37}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OneBot-HTTPClient", "..\OneBot-HTTPClient\src\OneBot-HTTPClient.csproj", "{D830E21D-78F7-4480-B86B-0AEA5A291A9D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunGame.Core", "..\FunGame.Core\FunGame.Core.csproj", "{3054F4C0-60AA-4353-B453-12C88E067AE5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +19,14 @@ Global
{46A60688-46D6-4414-A079-7DC0C95B5A37}.Debug|Any CPU.Build.0 = Debug|Any CPU
{46A60688-46D6-4414-A079-7DC0C95B5A37}.Release|Any CPU.ActiveCfg = Release|Any CPU
{46A60688-46D6-4414-A079-7DC0C95B5A37}.Release|Any CPU.Build.0 = Release|Any CPU
{D830E21D-78F7-4480-B86B-0AEA5A291A9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D830E21D-78F7-4480-B86B-0AEA5A291A9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D830E21D-78F7-4480-B86B-0AEA5A291A9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D830E21D-78F7-4480-B86B-0AEA5A291A9D}.Release|Any CPU.Build.0 = Release|Any CPU
{3054F4C0-60AA-4353-B453-12C88E067AE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3054F4C0-60AA-4353-B453-12C88E067AE5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3054F4C0-60AA-4353-B453-12C88E067AE5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3054F4C0-60AA-4353-B453-12C88E067AE5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -242,11 +242,52 @@ namespace Milimoe.RainBOT.Command
Daily.InitDaily();
SayNo.InitSayNo();
Ignore.InitIgnore();
FunGame.FunGameSimulation = false;
RainBOTFunGame.FunGameSimulation = false;
SendMessage(send_group, target_id, "参数设定以及权限组重新加载完成。");
}
else Access_Denied(send_group, target_id);
}
else if (command.Contains(".osm checkws"))
{
if (user_id == GeneralSettings.Master)
{
SendMessage(send_group, target_id, OshimaController.Instance.HTTPClient?.Connected ?? false ? $"已连接上服务器{OshimaController.Instance.HTTPClient.ServerAddress}" : "连接已断开。");
}
else Access_Denied(send_group, target_id);
}
else if (command.Contains(".osm retryserver"))
{
if (user_id == GeneralSettings.Master)
{
TaskUtility.NewTask(async () =>
{
OshimaController.Config.FunGame_isAutoRetry = true;
OshimaController.CurrentRetryTimes = -1;
try
{
await OshimaController.Instance.DisconnectFromAnonymousServer();
}
catch { }
try
{
await OshimaController.Instance.DisconnectAsync();
}
catch { }
try
{
await OshimaController.Instance.Retry(true);
}
catch { }
try
{
await OshimaController.Instance.ConnectToAnonymousServer();
}
catch { }
SendMessage(send_group, target_id, "已经重新启动 FunGame WebSocket 服务。");
});
}
else Access_Denied(send_group, target_id);
}
else if (command.Contains(".osm set"))
{
if (user_id == GeneralSettings.Master)

View File

@ -52,16 +52,16 @@ namespace Milimoe.RainBOT.ListeningTask
if (e.detail.Length >= 9 && e.detail[..9].Equals("FunGame模拟", StringComparison.CurrentCultureIgnoreCase))
{
if (!await Bot.CheckBlackList(true, e.user_id, e.user_id)) return quick_reply;
if (!FunGame.FunGameSimulation)
if (!RainBOTFunGame.FunGameSimulation)
{
FunGame.FunGameSimulation = true;
RainBOTFunGame.FunGameSimulation = true;
List<string> msgs = await Bot.HttpGet<List<string>>("https://api.milimoe.com/fungame/test?isweb=false") ?? [];
foreach (string msg in msgs)
{
await Bot.SendFriendMessage(e.user_id, "FunGame模拟", msg.Trim());
await Task.Delay(5500);
}
FunGame.FunGameSimulation = false;
RainBOTFunGame.FunGameSimulation = false;
}
else
{

View File

@ -137,7 +137,7 @@ namespace Milimoe.RainBOT.ListeningTask
return quick_reply;
}
if (await FunGame.Handler(e))
if (await RainBOTFunGame.Handler(e))
{
return quick_reply;
}

View File

@ -2,9 +2,12 @@
using Milimoe.OneBot.Model.Content;
using Milimoe.OneBot.Model.Message;
using Milimoe.OneBot.Model.Other;
using Milimoe.RainBOT.QQBot;
using Milimoe.RainBOT.Command;
using Milimoe.RainBOT.ListeningTask;
using Milimoe.RainBOT.Settings;
using Milimoe.FunGame.Core.Api.Utility;
using TaskScheduler = Milimoe.FunGame.Core.Api.Utility.TaskScheduler;
try
{
@ -17,6 +20,16 @@ try
Console.ForegroundColor = ConsoleColor.Gray;
}
if (args.Contains("--qqbot"))
{
GeneralSettings.IsQQBot = true;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("QQ官方BOT模式");
Console.ForegroundColor = ConsoleColor.Gray;
QQBotMain.RunQQBot();
return;
}
if (args.Any(a => a.StartsWith("-g")))
{
string debug_group = args.Where(a => a.StartsWith("-g")).FirstOrDefault() ?? "";
@ -120,17 +133,10 @@ try
listener.GroupBanNoticeListening += GroupBanTask.ListeningTask_handler;
listener.FriendMessageListening += FriendMessageTask.ListeningTask_handler;
_ = Task.Factory.StartNew(async () =>
{
while (true)
TaskScheduler.Shared.AddTask("发送每日新闻", new TimeSpan(8, 30, 0), async () =>
{
try
{
DateTime now = DateTime.Now;
if (now.Hour == 8 && now.Minute == 30 && !Daily.DailyNews)
{
Daily.DailyNews = true;
// 发送每日新闻
foreach (Group g in Bot.Groups)
{
GroupMessageContent content = new(g.group_id);
@ -141,27 +147,23 @@ try
Console.ForegroundColor = ConsoleColor.Gray;
}
}
if (now.Hour == 8 && now.Minute == 31)
catch (Exception e)
{
Daily.DailyNews = false;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e);
Console.ForegroundColor = ConsoleColor.Gray;
}
if (now.Hour == 0 && now.Minute == 0 && Daily.ClearDailys)
});
TaskScheduler.Shared.AddTask("清空每日运势", new TimeSpan(0, 0, 0), () =>
{
try
{
Daily.ClearDailys = false;
// 清空运势
Daily.UserDailys.Clear();
Daily.SaveDaily();
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("已重置所有人的今日运势。");
Console.ForegroundColor = ConsoleColor.Gray;
// 发放12点大挑战的奖励
//await Bot.Send12ClockPresents();
}
if (now.Hour == 0 && now.Minute == 1)
{
Daily.ClearDailys = true;
}
await Task.Delay(1000);
}
catch (Exception e)
{
@ -169,16 +171,11 @@ try
Console.WriteLine(e);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
});
_ = Task.Factory.StartNew(async () =>
{
while (true)
TaskScheduler.Shared.AddRecurringTask("清空下载图片", TimeSpan.FromMinutes(1), () =>
{
try
{
await Task.Delay(1000 * 60);
foreach (long uid in BlackList.Times.Where(d => d.Value < 5).Select(d => d.Key))
{
BlackList.Times.Remove(uid);
@ -196,6 +193,9 @@ try
catch { }
}
}
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("清空所有已下载的图片,释放空间。");
Console.ForegroundColor = ConsoleColor.Gray;
}
catch (Exception e)
{
@ -203,21 +203,28 @@ try
Console.WriteLine(e);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
});
// 连接 Oshima Core 服务器
OshimaController.Config.FunGame_isAutoRetry = true;
Task r = Task.Run(async () =>
{
await OshimaController.Instance.Start();
await OshimaController.Instance.ConnectToAnonymousServer();
});
bool isListening = true;
CancellationTokenSource cts = new();
CancellationToken ct = cts.Token;
Task t = Task.Factory.StartNew(() =>
Task t = Task.Factory.StartNew(async () =>
{
// 循环接收消息,此线程会在没有请求时阻塞
while (isListening)
{
try
{
listener.GetContext();
await listener.GetContext();
}
catch (Exception e)
{

433
src/Model/TEST.cs Normal file
View File

@ -0,0 +1,433 @@
//using Newtonsoft.Json.Linq;
//using QQBot4Sharp.Models;
//using Serilog;
//using System.Text;
//using System.Text.RegularExpressions;
//namespace QQBot4Sharp.Test
//{
// internal class Program
// {
// private static JObject _jConfig = [];
// static async Task Main(string[] args)
// {
// // 配置日志器
// Log.Logger = new LoggerConfiguration()
// .MinimumLevel.Debug()
// .WriteTo.Console()
// .CreateLogger();
// // 读取配置文件
// _jConfig = JObject.Parse(File.ReadAllText("config.json"));
// var info = new BotCreateInfo()
// {
// AppID = (string?)_jConfig["AppID"],
// ClientSecret = (string?)_jConfig["ClientSecret"],
// Intents = Intents.ALL,
// };
// // 创建机器人服务
// using var bot = new BotService(info);
// // 注册事件
// bot.OnReadyAsync += OnReadyAsync;
// bot.OnAtMessageCreateAsync += OnAtMessageCreateAsync;
// bot.OnDirectMessageCreateAsync += OnDirectMessageCreateAsync;
// bot.OnMessageCreateAsync += OnMessageCreateAsync;
// bot.OnC2CMessageCreateAsync += OnC2CMessageCreateAsync;
// bot.OnGroupAtMessageCreateAsync += OnGroupAtMessageCreateAsync;
// bot.OnMessageReactionAddAsync += OnMessageReactionAddAsync;
// bot.OnMessageReactionRemoveAsync += OnMessageReactionRemoveAsync;
// bot.OnInteractionCreateAsync += OnInteractionCreateAsync;
// bot.OnGuildUpdateAsync += OnGuildUpdateAsync;
// bot.OnChannelCreateAsync += OnChannelCreateAsync;
// // 启动和停止
// await bot.StartAsync();
// Console.ReadLine();
// await bot.StopAsync();
// }
// #region 通用事件
// /// <summary>
// /// READY 事件
// /// </summary>
// private static async Task OnReadyAsync(object sender, ContextEventArgs e)
// {
// Log.Information("Ready");
// var user = await e.Service.GetCurrentUserAsync();
// Log.Information($"当前用户:[{user.ID}]{user.Username}");
// await Task.CompletedTask;
// }
// #endregion
// #region 频道测试
// private static readonly Regex _atTestRegex = new("<@![0-9]+> 测试");
// private static readonly Regex _atPrivateTestRegex = new("<@![0-9]+> 私信测试");
// private static readonly Regex _atDeleteTestRegex = new("<@![0-9]+> 撤回测试");
// private static readonly Regex _atEmojiTestRegex = new("<@![0-9]+> 表情测试");
// private static readonly Regex _atMarkDownTestRegex = new("<@![0-9]+> MarkDown测试");
// private static readonly Regex _atGuildsRegex = new("<@![0-9]+> 频道列表测试");
// private static readonly Regex _atGuildRegex = new("<@![0-9]+> 频道测试");
// private static readonly Regex _atChannelRegex = new("<@![0-9]+> 子频道测试");
// private static readonly Regex _atChannelDetailRegex = new("<@![0-9]+> 子频道详情测试 [0-9]+");
// private static readonly Regex _atCreateChannelRegex = new("<@![0-9]+> 创建子频道测试 (?<Name>[0-9A-Za-z一-龥]+)");
// private static readonly Regex _atModifyChannelRegex = new("<@![0-9]+> 修改子频道测试 (?<ID>[0-9]+) (?<Name>[0-9A-Za-z一-龥]+)");
// private static readonly Regex _atDeleteChannelRegex = new("<@![0-9]+> 删除子频道测试 (?<ID>[0-9]+)");
// private static readonly Regex _atChannelOnlineMemberCountRegex = new("<@![0-9]+> 获取子频道在线成员数测试 (?<ID>[0-9]+)");
// /// <summary>
// /// 文字子频道At消息事件
// /// </summary>
// private static async Task OnAtMessageCreateAsync(object sender, AtMessageEventArgs e)
// {
// // 收到 “@Bot 测试” 消息后,回复 “At测试”
// if (_atTestRegex.IsMatch(e.Message.Content))
// {
// await e.ReplyAsync(new()
// {
// Content = "At测试",
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 私信测试” 消息后,私信回复 “文字频道的私信测试”
// if (_atPrivateTestRegex.IsMatch(e.Message.Content))
// {
// var dms = await e.CreateDirectMessageSessionAsync(new()
// {
// RecipientID = e.Message.Author.ID,
// SourceGuildID = e.Message.GuildID,
// });
// await e.SendDirectMessageAsync(new()
// {
// Content = "文字频道的私信测试",
// MessageID = e.Message.ID,
// }, dms.GuildID);
// }
// // 收到 “@Bot 撤回测试” 消息后,先发送一个消息,过几秒后撤回
// if (_atDeleteTestRegex.IsMatch(e.Message.Content))
// {
// var delay = 5 * 1000;
// var msg = await e.ReplyAsync(new()
// {
// Content = $"该消息将在{delay / 1000}秒后撤回",
// MessageID = e.Message.ID,
// });
// await Task.Delay(delay);
// await e.DeleteChannelMessageAsync(msg);
// }
// // 收到 “@Bot 表情测试” 消息后,先发送一个消息,进行表情测试
// if (_atEmojiTestRegex.IsMatch(e.Message.Content))
// {
// var delay = 3 * 1000;
// var msg = await e.ReplyAsync(new()
// {
// Content = "表情测试",
// MessageID = e.Message.ID,
// });
// await Task.Delay(delay);
// var emoji = new Emoji()
// {
// ID = "128076",
// Type = EmojiType.Emoji,
// };
// await e.SetEmojiReactionAsync(msg, emoji);
// await Task.Delay(delay);
// var users = await e.GetEmojiReactionAsync(msg, emoji);
// var sb = new StringBuilder();
// sb.Append("表情表态列表:");
// foreach (var user in users)
// {
// sb.Append(user.Username);
// sb.Append(' ');
// }
// await e.ReplyAsync(new()
// {
// Content = sb.ToString(),
// MessageID = e.Message.ID,
// });
// await Task.Delay(delay);
// await e.DeleteEmojiReactionAsync(msg, emoji);
// }
// // 收到 “@Bot MarkDown测试” 消息后进行MarkDown测试
// if (_atMarkDownTestRegex.IsMatch(e.Message.Content))
// {
// var builder = new MarkDownBuilder();
// builder.At(e.Message.Author.ID);
// builder.Text(" MarkDown测试\n");
// builder.Command("/MarkDown测试");
// await e.ReplyAsync(new()
// {
// Markdown = builder.Build(),
// });
// }
// // 收到 “@Bot 频道列表测试” 消息后,回复频道列表
// // 腾讯你逆大天
// // 我长这么大第一次见GET请求中带Content的
// // 不愧是你
// if (_atGuildsRegex.IsMatch(e.Message.Content))
// {
// // 还有一件事
// // 这API为什么会死循环的啊已经设置了after返回的还是一样的内容
// var guilds = await e.GetGuildsAsync();
// var sb = new StringBuilder();
// sb.Append("频道列表:");
// foreach (var guild in guilds)
// {
// sb.Append(guild.Name);
// sb.Append(' ');
// }
// await e.ReplyAsync(new()
// {
// Content = sb.ToString(),
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 频道测试” 消息后,回复频道信息
// if (_atGuildRegex.IsMatch(e.Message.Content))
// {
// var guild = await e.GetGuildAsync(e.Message.GuildID);
// await e.ReplyAsync(new()
// {
// Content = $"频道ID{guild.ID}\n频道名称{guild.Name}\n频道简介{guild.Description}",
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 子频道测试” 消息后,回复子频道信息
// if (_atChannelRegex.IsMatch(e.Message.Content))
// {
// var channels = await e.GetChannelsAsync(e.Message.GuildID);
// var sb = new StringBuilder();
// sb.Append("子频道列表:");
// foreach (var channel in channels)
// {
// sb.Append('[');
// sb.Append(channel.ID);
// sb.Append(']');
// sb.Append(channel.Name);
// sb.Append(' ');
// }
// await e.ReplyAsync(new()
// {
// Content = sb.ToString(),
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 子频道详情测试 ChannelID” 消息后,回复子频道详细信息
// if (_atChannelDetailRegex.IsMatch(e.Message.Content))
// {
// var segments = e.Message.Content.Split(' ');
// var channel = await e.GetChannelAsync(segments[2]);
// await e.ReplyAsync(new()
// {
// Content = $"子频道ID{channel.ID}\n子频道名称{channel.Name}\n子频道类型{channel.Type}",
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 创建子频道测试” 消息后,创建子频道
// var match = _atCreateChannelRegex.Match(e.Message.Content);
// if (match.Success)
// {
// var channel = await e.CreateChannelAsync(e.Message.GuildID, new()
// {
// Name = match.Groups["Name"].Value,
// Type = ChannelType.Text,
// SubType = ChannelSubType.Chat,
// PrivateType = PrivateType.Public,
// SpeakPermission = SpeakPermission.All,
// });
// await e.ReplyAsync(new()
// {
// Content = $"创建子频道ID{channel.ID}\n子频道名称{channel.Name}\n子频道类型{channel.Type}",
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 修改子频道测试 <ID> <Name>” 消息后,修改子频道
// match = _atModifyChannelRegex.Match(e.Message.Content);
// if (match.Success)
// {
// var id = match.Groups["ID"].Value;
// var channel = await e.GetChannelAsync(id);
// var name = match.Groups["Name"].Value;
// channel = await e.ModifyChannelAsync(id, new()
// {
// Name = name,
// ParentID = channel.ParentID,
// Position = channel.Position,
// PrivateType = channel.PrivateType,
// SpeakPermission = channel.SpeakPermission,
// });
// await e.ReplyAsync(new()
// {
// Content = $"修改子频道ID{channel.ID}\n子频道新名称{channel.Name}",
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 删除子频道测试 <ID>” 消息后,删除子频道
// match = _atDeleteChannelRegex.Match(e.Message.Content);
// if (match.Success)
// {
// var id = match.Groups["ID"].Value;
// var channel = await e.GetChannelAsync(id);
// await e.DeleteChannelAsync(id);
// await e.ReplyAsync(new()
// {
// Content = $"删除子频道ID{channel.ID}\n子频道名称{channel.Name}",
// MessageID = e.Message.ID,
// });
// }
// // 收到 “@Bot 获取子频道在线成员数测试 <ID>” 消息后,回复在线成员数
// match = _atChannelOnlineMemberCountRegex.Match(e.Message.Content);
// if (match.Success)
// {
// var id = match.Groups["ID"].Value;
// var count = await e.GetChannelOnlineMemberCountAsync(id);
// await e.ReplyAsync(new()
// {
// Content = $"子频道在线成员数:{count}",
// MessageID = e.Message.ID,
// });
// }
// }
// /// <summary>
// /// 频道私信事件
// /// </summary>
// private static async Task OnDirectMessageCreateAsync(object sender, DirectMessageEventArgs e)
// {
// // 收到 “测试” 消息后,回复 “私信测试”
// if (e.Message.Content == "测试")
// {
// await e.ReplyAsync(new()
// {
// Content = "私信测试",
// MessageID = e.Message.ID,
// });
// }
// // 收到 “撤回测试” 消息后,先发送一个消息,过几秒后撤回
// if (e.Message.Content == "撤回测试")
// {
// var delay = 5 * 1000;
// var msg = await e.ReplyAsync(new()
// {
// Content = $"该消息将在{delay / 1000}秒后撤回",
// MessageID = e.Message.ID,
// });
// await Task.Delay(delay);
// await e.DeleteDirectMessageAsync(msg);
// }
// }
// /// <summary>
// /// 文字子频道全量消息事件(仅私域)
// /// </summary>
// private static async Task OnMessageCreateAsync(object sender, GuildMessageEventArgs e)
// {
// // 收到 “测试” 消息后,回复 “文字频道测试”
// if (e.Message.Content == "测试")
// {
// await e.ReplyAsync(new()
// {
// Content = "文字频道测试",
// MessageID = e.Message.ID,
// });
// }
// }
// /// <summary>
// /// 消息表态添加事件
// /// </summary>
// private static async Task OnMessageReactionAddAsync(object sender, MessageReactionEventArgs e)
// {
// Log.Information("MessageReactionAdd");
// await Task.CompletedTask;
// }
// /// <summary>
// /// 消息表态移除事件
// /// </summary>
// private static async Task OnMessageReactionRemoveAsync(object sender, MessageReactionEventArgs e)
// {
// Log.Information("MessageReactionRemove");
// await Task.CompletedTask;
// }
// /// <summary>
// /// 按钮交互
// /// </summary>
// private static async Task OnInteractionCreateAsync(object sender, InteractionEventArgs e)
// {
// Log.Information("InteractionCreate");
// // 由于 websocket 推送事件是单向的,开发者收到事件之后,需要进行一次"回应"告知QQ后台事件已经收到否则客户端会一直处于loading状态直到超时。
// await e.RespondToInteractionAsync(e.Interaction.ID);
// }
// private static async Task OnGuildUpdateAsync(object sender, GuildUpdateEventArgs e)
// {
// Log.Information("GuildUpdate");
// await Task.CompletedTask;
// }
// private static async Task OnChannelCreateAsync(object sender, ChannelCreateEventArgs e)
// {
// Log.Information($"ChannelCreate:[{e.Channel.ID}]{e.Channel.Name}");
// await Task.CompletedTask;
// }
// #endregion
// #region QQ聊天测试
// /// <summary>
// /// 单聊事件
// /// </summary>
// private static async Task OnC2CMessageCreateAsync(object sender, Models.QQ.QQMessageEventArgs e)
// {
// await e.ReplyAsync(new()
// {
// Content = "私聊测试",
// Type = QQMessageType.Text,
// MessageID = e.Message.ID,
// });
// }
// /// <summary>
// /// 群聊事件
// /// </summary>
// private static async Task OnGroupAtMessageCreateAsync(object sender, Models.QQ.QQMessageEventArgs e)
// {
// await e.ReplyAsync(new()
// {
// Content = "群聊测试",
// Type = QQMessageType.Text,
// MessageID = e.Message.ID,
// });
// }
// #endregion
// }
//}

71
src/QQBot/QQBotMain.cs Normal file
View File

@ -0,0 +1,71 @@
using System.Text.Json;
using Milimoe.OneBot.Model.Event;
using Milimoe.OneBot.Model.Message;
using Milimoe.RainBOT.Settings;
namespace Milimoe.RainBOT.QQBot
{
public class AppConfig
{
public int AppID { get; set; } = 0;
public string BotToken { get; set; } = "";
public string ClientSecret { get; set; } = "";
public string FunGameServer { get; set; } = "";
}
public class QQBotMain
{
public static void RunQQBot()
{
try
{
string json = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json"));
AppConfig config = JsonSerializer.Deserialize<AppConfig>(json) ?? new();
if (config != null)
{
// 官方BOT服务
while (true)
{
string read = Console.ReadLine() ?? "";
if (read == "quit")
{
break;
}
if (read == "test")
{
GroupMessageEvent groupMessageEvent = new();
groupMessageEvent.message.Add(new TextMessage("生成20个攻击之爪 +50给123456"));
_ = RainBOTFunGame.Handler(groupMessageEvent);
continue;
}
// OSM指令
if (read.Length >= 4 && read[..4] == ".osm")
{
//MasterCommand.Execute(read, GeneralSettings.Master, false, GeneralSettings.Master, false);
continue;
}
switch (read.ToLower().Trim() ?? "")
{
case "debug on":
GeneralSettings.IsDebug = true;
Console.WriteLine("开启Debug模式");
break;
case "debug off":
GeneralSettings.IsDebug = false;
Console.WriteLine("关闭Debug模式");
break;
}
}
}
else throw new Exception("config.json 文件不存在");
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
}
}

View File

@ -21,9 +21,12 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="OneBot-HTTPClient">
<HintPath>..\..\OneBot-HTTPClient\bin\Debug\net9.0\OneBot-HTTPClient.dll</HintPath>
</Reference>
<EditorConfigFiles Remove="C:\milimoe\RainBOT-CSharp\src\.editorconfig" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\FunGame.Core\FunGame.Core.csproj" />
<ProjectReference Include="..\..\OneBot-HTTPClient\src\OneBot-HTTPClient.csproj" />
</ItemGroup>
</Project>

View File

@ -38,6 +38,8 @@ namespace Milimoe.RainBOT.Settings
public static bool IsDebug { get; set; } = false;
public static bool IsQQBot { get; set; } = false;
public static long DebugGroupID { get; set; } = 0;
public static long BlackTimes { get; set; } = 5;
@ -56,6 +58,10 @@ namespace Milimoe.RainBOT.Settings
public static List<long> FunGameGroup { get; set; } = [];
public static List<long> FunGameWebSocketGroup { get; set; } = [];
public static string FunGameServer { get; set; } = "";
public static string FunGameToken { get; set; } = "";
public static PluginConfig Configs { get; set; } = new("rainbot", "config");
@ -160,6 +166,14 @@ namespace Milimoe.RainBOT.Settings
{
FunGameGroup = (List<long>)value;
}
if (configs.TryGetValue("FunGameWebSocketGroup", out value) && value != null)
{
FunGameWebSocketGroup = (List<long>)value;
}
if (configs.TryGetValue("FunGameServer", out value) && value != null)
{
FunGameServer = (string)value;
}
if (configs.TryGetValue("FunGameToken", out value) && value != null)
{
FunGameToken = (string)value;
@ -191,6 +205,8 @@ namespace Milimoe.RainBOT.Settings
Configs.Add("SayNoAccessGroup", SayNoAccessGroup);
Configs.Add("OSMCoreGroup", OSMCoreGroup);
Configs.Add("FunGameGroup", FunGameGroup);
Configs.Add("FunGameWebSocketGroup", FunGameWebSocketGroup);
Configs.Add("FunGameServer", FunGameServer);
Configs.Add("FunGameToken", FunGameToken);
Configs.Save();
}
@ -218,6 +234,9 @@ namespace Milimoe.RainBOT.Settings
case "fungamegroup":
list = FunGameGroup;
break;
case "fungamewebsocketgroup":
list = FunGameWebSocketGroup;
break;
}
string msg = list.Count > 0 ? "权限组" + group + "拥有以下成员:" + "\r\n" + string.Join("\r\n", list) : "此权限组不存在或没有任何成员。";
_ = isgroup ? Bot.SendGroupMessage(target, "显示列表成员", msg) : Bot.SendFriendMessage(target, "显示列表成员", msg);

View File

@ -0,0 +1,186 @@
using System.Collections;
using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Core.Controller;
using Milimoe.FunGame.Core.Library.Common.Network;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Model;
using Milimoe.OneBot.Model.Other;
namespace Milimoe.RainBOT.Settings
{
public class OshimaController : RunTimeController
{
public static OshimaController Instance { get; set; } = new();
public static FunGameConfig Config { get; set; } = new();
public static int CurrentRetryTimes { get; set; } = -1;
public static int MaxRetryTimes => 10;
public override bool BeforeConnect(ref string addr, ref int port, ArrayList args)
{
if (Config.FunGame_isRetrying)
{
Console.WriteLine("正在连接服务器,请耐心等待。");
return false;
}
string[] strings = ["oshima.fungame.fastauto"];
args.Add(strings);
args.Add(false);
if (!Config.FunGame_isConnected)
{
CurrentRetryTimes++;
if (CurrentRetryTimes == 0) Console.WriteLine("开始连接服务器...");
else Console.WriteLine("第" + CurrentRetryTimes + "次重试连接服务器...");
// 超过重连次数上限
if (CurrentRetryTimes + 1 > MaxRetryTimes)
{
Config.FunGame_isAutoRetry = false;
Console.WriteLine("无法连接至服务器。");
_ = Bot.SendFriendMessage(GeneralSettings.Master, "websocket", "重连服务器失败,重试次数已过多。");
return false;
}
Config.FunGame_isRetrying = true;
return true;
}
else
{
Console.WriteLine("已连接至服务器,请勿重复连接。");
return false;
}
}
public override void AfterConnect(ArrayList ConnectArgs)
{
Config.FunGame_isRetrying = false;
string msg = ConnectArgs[1]?.ToString() ?? "";
string serverName = ConnectArgs[2]?.ToString() ?? "";
string notice = ConnectArgs[3]?.ToString() ?? "";
if (msg != "") Console.WriteLine(msg);
if (serverName != "") Console.WriteLine(serverName);
if (notice != "") Console.WriteLine(notice);
}
public async Task Start()
{
ConnectResult result = ConnectResult.CanNotConnect;
while (result != ConnectResult.Success && Config.FunGame_isAutoRetry)
{
try
{
result = await ConnectAsync(TransmittalType.WebSocket, GeneralSettings.FunGameServer, ssl: true, subUrl: "ws");
Config.FunGame_isRetrying = false;
await Task.Delay(2000);
}
catch (Exception e)
{
Error(e);
}
}
}
public async Task Retry(bool send = false)
{
if (HTTPClient is null)
{
try
{
if (await ConnectAsync(TransmittalType.WebSocket, GeneralSettings.FunGameServer, ssl: true, subUrl: "ws") == ConnectResult.Success)
{
Console.WriteLine("重连成功!");
if (send)
{
await Bot.SendFriendMessage(GeneralSettings.Master, "websocket", "重连服务器成功");
}
}
else
{
Console.WriteLine("重连失败!");
if (!Config.FunGame_isRetrying && Config.FunGame_isAutoRetry)
{
await Task.Delay(2000);
if (!Config.FunGame_isRetrying && Config.FunGame_isAutoRetry)
{
await Retry();
}
}
}
}
catch { }
}
}
public async Task ConnectToAnonymousServer()
{
if (HTTPClient != null)
{
await HTTPClient.Send(SocketMessageType.AnonymousGameServer, "oshima.fungame.anonymous");
}
}
public async Task DisconnectFromAnonymousServer()
{
if (HTTPClient != null)
{
await HTTPClient.Send(SocketMessageType.EndGame);
}
}
public async Task DisconnectAsync()
{
if (HTTPClient != null)
{
await HTTPClient.Send(SocketMessageType.Disconnect);
Close_WebSocket();
}
}
public override async void Error(Exception e)
{
Console.WriteLine(e.ToString());
await DisconnectAsync();
if (!Config.FunGame_isRetrying && Config.FunGame_isAutoRetry)
{
CurrentRetryTimes = -1;
Config.FunGame_isAutoRetry = true;
await Task.Delay(2000);
if (!Config.FunGame_isRetrying && Config.FunGame_isAutoRetry)
{
await Retry();
}
}
}
public override void WritelnSystemInfo(string msg, LogLevel level = LogLevel.Info, bool useLevel = true)
{
Console.WriteLine(msg);
}
protected override void SocketHandler_Disconnect(SocketObject ServerMessage)
{
Console.WriteLine("断开服务器连接成功");
}
protected override async void SocketHandler_AnonymousGameServer(SocketObject ServerMessage)
{
Dictionary<string, object> data = ServerMessage.GetParam<Dictionary<string, object>>(0) ?? [];
if (data.Count > 0)
{
long qq = NetworkUtility.JsonDeserializeFromDictionary<long>(data, "qq");
string msg = NetworkUtility.JsonDeserializeFromDictionary<string>(data, "msg") ?? "";
if (qq > 0 && msg != "")
{
foreach (Group g in Bot.Groups.Where(g => GeneralSettings.FunGameWebSocketGroup.Contains(g.group_id)))
{
Member m = Bot.GetMember(g.group_id, qq);
if (m.user_id == qq)
{
await Bot.SendGroupMessageAt(qq, g.group_id, "FunGame推送", msg);
break;
}
}
}
}
}
}
}

File diff suppressed because it is too large Load Diff