static async Task Main(string[] args)
        {
            var lines = File.ReadAllLines("students.csv", Encoding.UTF8);

            foreach (var line in lines.Where(l => l.NotNullNorWhiteSpace()))
            {
                var sp    = line.Split(',');
                var id    = sp[0];
                var stdid = sp[1];
                var name  = sp[2];
                PreRegisteredStudents.Add(new Student(null, id.ToInt(), stdid, name));
            }

            var options = new MiraiHttpSessionOptions("127.0.0.1", 8080, Config.Instance.AuthCode);
            var qq      = Config.Instance.QQ;

            mirai = new MiraiHttpSession();

            await mirai.ConnectAsync(options, qq);

            mirai.FriendMessageEvt  += OnFriendMessage;
            mirai.NewFriendApplyEvt += (sender, eventArgs) =>
            {
                mirai.HandleNewFriendApplyAsync(eventArgs, FriendApplyAction.Allow, "略略略");
                Thread.Sleep(5000);
                SendPrivate(eventArgs.FromQQ.ToString(), $"使用[注册 名字]来注册 如输入 '注册 小明' \n" +
                            $"使用[上传图片]来开始上传图片, 在输入上传图片后 发送的下一张图片将会被保存.\n" +
                            $"以上内容均不包含括号'[]'\n" +
                            $"Written by Cyl18 2020 https://github.com/Cyl18/");
                return(Task.FromResult(true));
            };
            mirai.DisconnectedEvt += async(sender, exception) =>
            {
                while (true)
                {
                    try
                    {
                        await mirai.ConnectAsync(options, qq); // 连到成功为止, QQ号自填, 你也可以另行处理重连的 behaviour

                        return(true);
                    }
                    catch (Exception)
                    {
                        await Task.Delay(1000);
                    }
                }
            };

            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
Exemple #2
0
        public override void Init()
        {
            var config  = MiraiConfig.Instance;
            var qq      = config.BotQQ;
            var host    = config.Host;
            var port    = config.Port;
            var authKey = config.AuthKey;

            if (Directory.Exists("WFBotImageCaches"))
            {
                Directory.Delete("WFBotImageCaches", true);
            }

            if (qq == default || host == default || port == default || authKey == default)
            {
                // todo 直接控制台写
                throw new InvalidOperationException("请在 MiraiConfig.json 内补全信息, 详情请查看文档.");
            }

            var options = new MiraiHttpSessionOptions(host, port, authKey); // 至少八位数

            session = new MiraiHttpSession();
            session.GroupMessageEvt += (sender, args) =>
            {
                var msg = args.Chain.GetPlain();
                ReportGroupMessage(args.Sender.Group.Id, args.Sender.Id, msg);
                return(Task.FromResult(true));
            };

            session.FriendMessageEvt += (sender, args) =>
            {
                var msg = args.Chain.GetPlain();
                ReportFriendMessage(args.Sender.Id, msg);
                return(Task.FromResult(true));
            };

            session.DisconnectedEvt += async(sender, exception) =>
            {
                while (true)
                {
                    try
                    {
                        Console.WriteLine("Mirai 连接断开, 正在重连...");
                        await session.ConnectAsync(options, qq);

                        return(true);
                    }
                    catch (Exception)
                    {
                        await Task.Delay(1000);
                    }
                }
            };
            session.ConnectAsync(options, qq).Wait();
        }
Exemple #3
0
        static async Task Main(string[] args)
        {
            // 把你要连接到的 mirai-api-http 所需的主机名/IP, 端口 和 AuthKey 全部填好
            // !! 最好不要用我例子里边的 key 和 端口, 请自己生成一个, 比如 System.Guid.NewGuid().ToString("n") !!
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(Setting.Host, Setting.Port, Setting.AuthKey);

            // session 使用 DisposeAsync 模式, 所以使用 await using 自动调用 DisposeAsync 方法。
            // 你也可以不在这里 await using, 不过使用完 session 后请务必调用 DisposeAsync 方法
            await using MiraiHttpSession session = new MiraiHttpSession();
            // 把你实现了 Mirai_CSharp.Plugin.Interfaces 下的接口的类给 new 出来, 然后作为插件塞给 session
            NormalPlugin plugin = new NormalPlugin();

            // 你也可以一个个绑定事件。比如 session.GroupMessageEvt += plugin.GroupMessage;
            // 手动绑定事件后不要再调用AddPlugin, 否则可能导致重复调用
            session.AddPlugin(plugin);
            // 实例化MQ
            MQUtil.InitMQ();
            // 使用上边提供的信息异步连接到 mirai-api-http
            await session.ConnectAsync(options, Setting.QQ); // 自己填机器人QQ号

            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
Exemple #4
0
        public static async Task Main()
        {
            // 把你要连接到的 mirai-api-http 所需的主机名/IP, 端口 和 AuthKey 全部填好
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("127.0.0.1", 33111, "8d726307dd7b468d8550a95f236444f7");

            // session 使用 DisposeAsync 模式, 所以使用 await using 自动调用 DisposeAsync 方法。
            // 你也可以不在这里 await using, 不过使用完 session 后请务必调用 DisposeAsync 方法
            await using MiraiHttpSession session = new MiraiHttpSession();
            // 把你实现了 Mirai_CSharp.Plugin.Interfaces 下的接口的类给 new 出来, 然后作为插件塞给 session
            ExamplePlugin plugin = new ExamplePlugin();

            // 你也可以一个个绑定事件。比如 session.GroupMessageEvt += plugin.GroupMessage;
            // 手动绑定事件后不要再调用AddPlugin, 否则可能导致重复调用
            session.AddPlugin(plugin);
            // 使用上边提供的信息异步连接到 mirai-api-http
            await session.ConnectAsync(options, 0); // 自己填机器人QQ号

            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
Exemple #5
0
        public static async Task Main()
        {
            // 把你要连接到的 mirai-api-http 所需的主机名/IP, 端口 和 AuthKey 全部填好
            // !! 最好不要用我例子里边的 key 和 端口, 请自己生成一个, 比如 System.Guid.NewGuid().ToString("n") !!
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("47.242.52.67", 5200, "zheng12321");

            // session 使用 DisposeAsync 模式, 所以使用 await using 自动调用 DisposeAsync 方法。
            // 你也可以不在这里 await using, 不过使用完 session 后请务必调用 DisposeAsync 方法
            await using MiraiHttpSession session = new MiraiHttpSession();
            // 把你实现了 Mirai_CSharp.Plugin.Interfaces 下的接口的类给 new 出来, 然后作为插件塞给 session
            ExamplePlugin plugin = new ExamplePlugin();

            // 你也可以一个个绑定事件。比如 session.GroupMessageEvt += plugin.GroupMessage;
            // 手动绑定事件后不要再调用AddPlugin, 否则可能导致重复调用
            session.AddPlugin(plugin);

            // 使用上边提供的信息异步连接到 mirai-api-http
            await session.ConnectAsync(options, 2593894146); // 自己填机器人QQ号  481503471   478893039   859255432

            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
Exemple #6
0
        public async Task Launch()
        {
            Logger.Log("Session host:", SessionHost);
            Logger.Log("Session port:", SessionPort);
            Logger.Log("Session key:", SessionKey);
            var sessionOptions = new MiraiHttpSessionOptions(SessionHost, SessionPort, SessionKey);

            Logger.Log("Mirai session created");
            _session = new MiraiHttpSession();

            foreach (var plugin in Plugins)
            {
                _session.AddPlugin(plugin);
                Logger.Log("Plugin:", plugin.GetType().Name, "added");
            }

            try
            {
                await _session.ConnectAsync(sessionOptions, BotQQ);

                Logger.Log("Successful connected", BotQQ, "to Mirai session");
                Logger.Log("Bot launched!");
            }
            catch (Exception e)
            {
                Logger.Log("Connect to", BotQQ, "failed");
                Logger.Log("Reason:", e.Message);
            }
        }
Exemple #7
0
        public static async Task Main()
        {
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("127.0.0.1", 8080, "1c783ceb3f5344d097781ab771021efc");

            await using MiraiHttpSession session = new MiraiHttpSession();
            var plugin = new Plugins();

            session.GroupMessageEvt += plugin.ImageMonitor;
            session.GroupMessageEvt += plugin.MemberBan;
            session.GroupMessageEvt += plugin.Accept;
            session.GroupMessageEvt += plugin.OnAt;
            session.DisconnectedEvt += plugin.Disconnected;
            session.GroupMessageEvt += plugin.MemberKick;
            session.GroupMessageEvt += plugin.ManagementUsingAt;
            await session.ConnectAsync(options, 3197173556);

            // await UnitTest.Run(session, 947904856);
            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
        public static async Task Configure()
        {
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(ConfigurationManager.AppSettings.Get("host"),
                                                                          Convert.ToInt32(ConfigurationManager.AppSettings.Get("port")),
                                                                          ConfigurationManager.AppSettings.Get("authKey"));

            groupID = Convert.ToInt64(ConfigurationManager.AppSettings.Get("groupID"));

            // session 使用 DisposeAsync 模式, 所以使用 await using 自动调用 DisposeAsync 方法。
            // 你也可以不在这里 await using, 不过使用完 session 后请务必调用 DisposeAsync 方法
            session = new MiraiHttpSession();
            // 把你实现了 Mirai_CSharp.Plugin.Interfaces 下的接口的类给 new 出来, 然后作为插件塞给 session
            Plugin plugin = new Plugin();

            // 你也可以一个个绑定事件。比如 session.GroupMessageEvt += plugin.GroupMessage;
            // 手动绑定事件后不要再调用AddPlugin, 否则可能导致重复调用
            session.AddPlugin(plugin);
            try
            {
                // 使用上边提供的信息异步连接到 mirai-api-http
                await session.ConnectAsync(options, Convert.ToInt64(ConfigurationManager.AppSettings.Get("qqNumber"))); // 自己填机器人QQ号
            }
            catch
            {
                MessageBox.Show("程序连接Mirai服务器失败,该程序目前只能测试弹幕使用,如需正常使用,请配置正确后重新启动程序。");
            }
        }
Exemple #9
0
        public static async Task Main()
        {
            // 把你要连接到的 mirai-api-http 所需的主机名/IP, 端口 和 AuthKey 全部填好
            // !! 最好不要用我例子里边的 key 和 端口, 请自己生成一个, 比如 System.Guid.NewGuid().ToString("n") !!
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("127.0.0.1", 8080, "INITKEYVCo5ktPW");

            // session 使用 DisposeAsync 模式, 所以使用 await using 自动调用 DisposeAsync 方法。
            // 你也可以不在这里 await using, 不过使用完 session 后请务必调用 DisposeAsync 方法
            await using MiraiHttpSession session = new MiraiHttpSession();
            // 把你实现了 Mirai_CSharp.Plugin.Interfaces 下的接口的类给 new 出来, 然后作为插件塞给 session
            GamePlugin plugin = new GamePlugin();

            // 你也可以一个个绑定事件。比如 session.GroupMessageEvt += plugin.GroupMessage;
            // 手动绑定事件后不要再调用AddPlugin, 否则可能导致重复调用
            session.AddPlugin(plugin);
            // 使用上边提供的信息异步连接到 mirai-api-http
            await session.ConnectAsync(options, 1018429593); // 自己填机器人QQ号

            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
        public static async Task <bool> Start(BotStartupConfig config)
        {
            if (connecting || session.Connected)
            {
                return(false);
            }
            else
            {
                connecting = true;
            }
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(config.host, config.port, config.authKey);

            try
            {
                await session.ConnectAsync(options, config.qqID);
            }
            catch
            {
                connecting = false;
                return(false);
            }
            if (session.Connected)
            {
                session.AddPlugin(new MainPlugin());
                await BotCore.Init(session, config);

                connecting = false;
                return(true);
            }
            else
            {
                connecting = false;
                return(false);
            }
        }
Exemple #11
0
        async void HandShakeClientStart(object sender, RoutedEventArgs e)
        {
            var port    = int.Parse(PortTextBox.Text);
            var options = new MiraiHttpSessionOptions("localhost", port, "PinkPill");
            var selfQQ  = long.Parse(SelfIDTextBox.Text);   // 自己
            var otherQQ = long.Parse(TargetIDTextBox.Text); // 对方

            TargetQQ = otherQQ;
            session  = new MiraiHttpSession();

            await session.ConnectAsync(options, selfQQ);

            var superStream  = new DelayedBufferStream((_, e) => { SendMessage(new ImageObfuscator().Obfuscate(e)); });
            var serverStream = new SslStream(superStream, false,
                                             (sender, certificate, chain, errors) =>
            {
                var subject = certificate.Subject;
                AddMessage($"握手完成: 证书名 {subject}");
                return(true);
            }, null);

            stream = serverStream;
            var cert = X509Certificate2.CreateFromPemFile(@"cert.pem");

            cert = new X509Certificate2(cert.Export(X509ContentType.Pkcs12));


            session.FriendMessageEvt += (_, args) =>
            {
                if (args.Sender.Id == otherQQ)
                {
                    var obfs = new ImageObfuscator();
                    var msg  = args.Chain;
                    if (msg.FirstOrDefault(c => c is ImageMessage) is not ImageMessage imageMessage)
                    {
                        return(Task.FromResult(true));
                    }
                    var imageBytes = new HttpClient().GetByteArrayAsync(imageMessage.Url).Result;

                    superStream.SendMessage(obfs.Deobfuscate(new MagickImage(imageBytes, MagickFormat.Png)));
                }

                return(Task.FromResult(true));
            };
            await serverStream.AuthenticateAsClientAsync("", new X509Certificate2Collection(new[] { cert }), SslProtocols.Tls12, false);

            _ = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    var buffer = new Span <byte>(new byte[1024]);
                    var i      = serverStream.Read(buffer);
                    if (i > 0)
                    {
                        AddMessage($"接收到了: {Encoding.UTF8.GetString(buffer.Slice(0, i))}");
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
Exemple #12
0
        public static async Task Main()
        {
            AppDomain.CurrentDomain.UnhandledException += (_, e) => ErrorHelper.WriteErrorLog(e.ExceptionObject);

            Console.WriteLine("葱葱机器人");

            if (!File.Exists(Cache.JsonConfigFileName))
            {
                Console.WriteLine("初次使用本机器人,请先设置config.json相关参数。");
            }

            Console.WriteLine("请输入机器人QQ号:");
            long qqId = Convert.ToInt64(Console.ReadLine());

            Console.WriteLine("请输入mirai-api-http host IP:");
            string ip = Console.ReadLine();

            Console.WriteLine("请输入mirai-api-http端口:");
            int port = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("请输入mirai-api-http autoKey:");
            string autoKey = Console.ReadLine();

            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(ip, port, autoKey);

            await using MiraiHttpSession session = new MiraiHttpSession();
            session.AddPlugin(new TempMessage());
            session.AddPlugin(new FriendMessage());
            session.AddPlugin(new GroupMessage());
            bool stop = false;
            await session.ConnectAsync(options, qqId).ContinueWith(callback =>
            {
                if (callback.IsFaulted)
                {
                    stop = true;
                    Console.WriteLine("连接失败,请检查Mirai是否已经正常启动并已配置mirai-api-http相关参数。");
                }
            });

            if (stop)
            {
                return;
            }

            Cache.SetTaskAtFixedTime();

            string nickname = (await session.GetFriendListAsync()).Where(m => m.Id == qqId).FirstOrDefault().Name;

            Console.WriteLine($"已连接到mirai-api-http, 登录昵称:{nickname}, 输入exit或按下Ctrl+C断开连接。");

            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("[QQ]配置初始化...");
            session = new MiraiHttpSession();
            if (!File.Exists("mirai.conf"))
            {
                JObject jb = new JObject();
                jb.Add("host", "127.0.0.1");
                jb.Add("port", 1234);
                jb.Add("auth", "passw0rd");
                File.WriteAllText("mirai.conf", jb.ToString());
            }
            string  config = File.ReadAllText("mirai.conf");
            JObject conf   = JObject.Parse(config);

            options = new MiraiHttpSessionOptions(conf.Value <string>("host"), conf.Value <int>("port"), conf.Value <string>("auth"));
            Console.WriteLine("[QQ]等待Mirai...");
            session.ConnectAsync(options, qq).Wait();
            session.DisconnectedEvt   += Session_DisconnectedEvt;
            session.FriendMessageEvt  += Session_FriendMessageEvt;
            session.NewFriendApplyEvt += Session_NewFriendApplyEvt;
            Console.WriteLine("[QQ]已连接");
            SignQueueHandler.session = session;
            if (File.Exists("./database.bin"))
            {
                Console.WriteLine("[Queue]加载保存的队列...");
                try
                {
                    SignQueueHandler.Load();
                    Console.WriteLine("[Queue]已加载" + SignQueueHandler.queue.Count + "个用户数据");
                }
                catch (Exception err)
                {
                    Console.WriteLine("[Queue]加载失败:" + err.Message + "\n" + err.StackTrace);
                }
            }
            while (true)
            {
                try
                {
                    DateTime start = DateTime.Now;
                    Console.WriteLine("[Timer] 计时器开始:" + start);
                    SignQueueHandler.__ProceedQueue();
                    SignQueueHandler.Save();
                    Console.WriteLine("[Timer] 计时器结束:" + DateTime.Now + ", 用时" + (DateTime.Now - start).Seconds + "秒");
                    Thread.Sleep(10 * 60 * 1000);
                }
                catch (Exception err)
                {
                    Console.WriteLine("[EXCEPTION] 消息循环内出现意外错误");
                    DumpError(err);
                }
            }
        }
Exemple #14
0
        public QClient(string addr, int port, string passwd, long account)
        {
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(addr, port, passwd);

            session       = new MiraiHttpSession();
            handler       = new EventHandler(this);
            conversations = new List <Conversation>();
            session.ConnectAsync(options, account).Wait();
            friends = session.GetFriendListAsync().Result.ToList();
            groups  = session.GetGroupListAsync().Result.ToList();
            session.AddPlugin(handler);
        }
Exemple #15
0
        public async Task Main(long qqId, string ip, int port, string autoKey)
        {
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(ip, port, autoKey);

            await using MiraiHttpSession session = new MiraiHttpSession();
            session.AddPlugin(new TempMessage());
            session.AddPlugin(new FriendMessage());
            session.AddPlugin(new GroupMessage());
            bool stop = false;
            await session.ConnectAsync(options, qqId).ContinueWith(callback =>
            {
                if (callback.IsFaulted)
                {
                    stop = true;
                    MessageBox.Show("连接失败,请检查Mirai是否已经正常启动并已配置mirai-api-http相关参数。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            });

            if (stop)
            {
                return;
            }

            Cache.SetTaskAtFixedTime();

            string nickname = (await session.GetFriendListAsync()).Where(m => m.Id == qqId).FirstOrDefault().Name;

            Invoke(new Action(() =>
            {
                lblState.Text      = $"连接状态: 已连接到mirai-api-http, 登录昵称:{nickname}";
                lblState.ForeColor = Color.Black;
                btnConnect.Text    = "断开连接";
                btnConnect.Click  -= btnConnect_Click;
                btnConnect.Click  += btnDeconnect_Click;
            }));

            while (true)
            {
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    Invoke(new Action(() =>
                    {
                        btnConnect.Text    = "连接到mirai-api-http";
                        lblState.Text      = "连接状态: 未连接到mirai-api-http";
                        lblState.ForeColor = Color.Red;
                    }));
                    return;
                }
            }
        }
 private async static System.Threading.Tasks.Task <bool> Session_DisconnectedEvt(MiraiHttpSession sender, Exception e)
 {
     while (true)
     {
         try
         {
             session.ConnectAsync(op, me_qq).Wait();
             break;
         }
         catch
         {
             Thread.Sleep(2000);
         }
     }
     return(false);
 }
Exemple #17
0
        public async Task <bool> Disconnected(MiraiHttpSession session, Exception e)
        {
            // e.Exception: 引发掉线的响应异常, 按需处理
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("127.0.0.1", 8080, "1c783ceb3f5344d097781ab771021efc");

            while (true)
            {
                try
                {
                    await session.ConnectAsync(options, 3197173556); // 连到成功为止, QQ号自填, 你也可以另行处理重连的 behaviour

                    return(true);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                }
            }
        }
        public async Task <bool> Disconnected(MiraiHttpSession session, IDisconnectedEventArgs e)
        {
            // e.Exception: 引发掉线的响应异常, 按需处理
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("mirai-api.duwanjuan.cn", 80, "chapanzhou");

            while (true)
            {
                try
                {
                    await session.ConnectAsync(options, 1493513606); // 连到成功为止, QQ号自填, 你也可以另行处理重连的 behaviour

                    return(true);
                }
                catch (Exception ex)
                {
                    await Task.Delay(1000);
                }
            }
        }
Exemple #19
0
        public async Task <bool> Disconnected(MiraiHttpSession session, IDisconnectedEventArgs e)
        {
            // e.Exception: 引发掉线的响应异常, 按需处理
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("127.0.0.1", 33111, "8d726307dd7b468d8550a95f236444f7");

            while (true)
            {
                try
                {
                    await session.ConnectAsync(options, 0); // 连到成功为止, QQ号自填, 你也可以另行处理重连的 behaviour

                    return(true);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                }
            }
        }
Exemple #20
0
        static async Task Main(string[] args)
        {
            var options = new MiraiHttpSessionOptions(Host, Port, AuthKey);

            await using var session = new MiraiHttpSession();
            await session.ConnectAsync(options, QQNum);

            session.GroupMessageEvt += MessageQueueListener.Listener;
            session.AddPlugin(new Commands.GroupCommandForwarder());
            session.AddPlugin(new Commands.TempCommandForwarder());
            Tests.TestRuner.Run();
            while (true)
            {
                if (await Console.In.ReadLineAsync() == "quit")
                {
                    return;
                }
            }
        }
        public async Task <bool> Disconnected(MiraiHttpSession session, IDisconnectedEventArgs e)
        {
            // e.Exception: 引发掉线的响应异常, 按需处理
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(Setting.Host, Setting.Port, Setting.AuthKey);

            while (true)
            {
                try
                {
                    await session.ConnectAsync(options, Setting.QQ); // 连到成功为止, QQ号自填, 你也可以另行处理重连的 behaviour

                    return(true);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                }
            }
        }
Exemple #22
0
        public async Task <bool> Disconnected(MiraiHttpSession session, IDisconnectedEventArgs e)
        {
            // e.Exception: 引发掉线的响应异常, 按需处理
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions("47.242.52.67", 5200, "zheng12321");

            while (true)
            {
                try
                {
                    await session.ConnectAsync(options, 2033593308); // 连到成功为止, QQ号自填, 你也可以另行处理重连的 behaviour

                    return(true);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                }
            }
        }
Exemple #23
0
        public async Task <bool> Disconnected(MiraiHttpSession session, IDisconnectedEventArgs e)
        {
            logger.LogError("已断开连接,正在尝试重连");
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(miraiSessionOptions.Value.MiraiHost, miraiSessionOptions.Value.MiraiHostPort, miraiSessionOptions.Value.MiraiSessionKey);

            while (true)
            {
                try
                {
                    await session.ConnectAsync(options, miraiSessionOptions.Value.MiraiSessionQQ);

                    logger.LogInformation("重连成功");
                    return(true);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                }
            }
        }
Exemple #24
0
        public static async Task Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var options = args.Length == 0 ?
                          new MiraiHttpSessionOptions("bothost", 8080, "1234567890"):
                          new MiraiHttpSessionOptions("localhost", 8080, "1234567890");

            await using var session = new MiraiHttpSession();

            session.AddPlugin(new MessageHandler());

            await session.ConnectAsync(options, long.Parse(args.Length == 0 ? "2025551588" : args[0]));

            PluginInitialize(session);

            Console.WriteLine("connected to server");

            Thread.Sleep(int.MaxValue);
        }
Exemple #25
0
        public static async Task Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var options = new MiraiHttpSessionOptions("127.0.0.1", 8080, "1234567890");

            //var options = new MiraiHttpSessionOptions("139.9.234.121", 8080, "1234567890");
            //args = new string[] { "2025551588" };
            await using var session = new MiraiHttpSession();

            session.AddPlugin(new MessageHandler());

            await session.ConnectAsync(options, long.Parse(args[0]));

            PluginInitialize(session);

            Console.WriteLine("connected to server");

            Thread.Sleep(int.MaxValue);
        }
Exemple #26
0
        private async Task InitializeMirai()
        {
            TssCurrentQInfo.Text = $"ID: {Config.Instance.QQNumber} | Connection: False";
            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(
                Config.Instance.Address,
                Config.Instance.Port,
                Config.Instance.Token);

            session = new MiraiHttpSession();
            await session.ConnectAsync(options, Config.Instance.QQNumber);

            session.FriendMessageEvt    += Session_FriendMessageEvt;
            session.GroupNameChangedEvt += Session_GroupNameChangedEvt;
            session.GroupMessageEvt     += Session_GroupMessageEvt;
            session.DisconnectedEvt     += Session_DisconnectedEvt;
            session.BotOnlineEvt        += Session_BotOnlineEvt;

            TssCurrentQInfo.Text = $"ID: {session.QQNumber} | Connection: {session.Connected}";

            await Task.Run(() => UpdateList(500)).ConfigureAwait(false);
        }
        private static async System.Threading.Tasks.Task <bool> Session_DisconnectedEvt(MiraiHttpSession sender, Exception e)
        {
            while (true)
            {
                try
                {
                    Console.WriteLine("[Connection]连接意外断开:" + e.Message + "\n" +
                                      "[Connection]断线重连...");
                    await sender.ConnectAsync(options, qq);

                    break;
                }
                catch (Exception err)
                {
                    Console.WriteLine("[Connection]失败:" + err.Message + "\n" +
                                      "[Connection]断线重连...");
                    await Task.Delay(500);
                }
            }
            return(false);
        }
Exemple #28
0
        /// <summary>
        /// 启动
        /// </summary>
        private async void Run()
        {
            _logger.LogInformation("Rimirin Bot启动中...");
#if DEBUG
            var updateFromNetwork = false;
#else
            var updateFromNetwork = true;
#endif
            UpdateFiles(updateFromNetwork);
            _timer.Elapsed += OnTimerElapsed;
            _timer.Start();
            var plugins = Assembly.GetExecutingAssembly().DefinedTypes.Where(ti => ti.GetInterface("IPlugin") != null).ToArray();
            foreach (var plugin in plugins)
            {
                _session.AddPlugin((IPlugin)_serviceProvider.GetService(plugin.AsType()));
            }
            await _session.ConnectAsync(new Mirai_CSharp.Models.MiraiHttpSessionOptions(_miraiSessionOptions.Value.MiraiHost, _miraiSessionOptions.Value.MiraiHostPort, _miraiSessionOptions.Value.MiraiSessionKey), _miraiSessionOptions.Value.MiraiSessionQQ);

#if DEBUG
            //OnTimerElapsed(null, null);
#endif
        }
Exemple #29
0
        public static async Task Main()
        {
            Configure();

            MiraiHttpSessionOptions options = new MiraiHttpSessionOptions(configuration["ip"], Convert.ToInt32(configuration["port"]), configuration["authKey"]);
            MessagePlugin           plugin  = new MessagePlugin(db, configuration, commandList);
            MiraiHttpSession        session = new MiraiHttpSession();

            session.AddPlugin(plugin);
            // 使用上边提供的信息异步连接到 mirai-api-http
            await session.ConnectAsync(options, Convert.ToInt64(configuration["botQQ"])); //机器人QQ号

            Console.WriteLine("服务启动~~");
            while (true)
            {
                Thread.Sleep(1000);
                if (await Console.In.ReadLineAsync() == "exit")
                {
                    return;
                }
            }
        }
        static void Main(string[] args)
        {
            var process = Process.Start(new ProcessStartInfo
            {
                FileName  = "python",
                Arguments = "-u -m deepdanbooru evaluate --project-path D:\\DeepDanbooru-master\\test --allow-folder",
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                CreateNoWindow         = true
            });
            var dic   = new Dictionary <string, int>();
            var count = new List <int>();

            process.OutputDataReceived += (sender, eventArgs) =>
            {
                var line = eventArgs.Data;
                if (line.IsNullOrWhiteSpace() || !line.StartsWith("MAGIC"))
                {
                    return;
                }
                line = line.Substring(5);
                var split      = line.Split('艹');
                var path       = split[0];
                var tagsSource = split.Skip(1);
                var tags       = new List <Tag>();

                foreach (var tagSource in tagsSource)
                {
                    var split1 = tagSource.Split('丂');
                    var score  = split1[0];
                    var tag    = split1[1];
                    tags.Add(new Tag {
                        Score = score, TagName = tag
                    });
                    if (!dic.ContainsKey(tag))
                    {
                        dic[tag] = 0;
                    }

                    dic[tag]++;
                }
                count.Add(tags.Count);
                var result = new FileResult {
                    FilePath = path, Tags = tags
                };
                result.ToJsonString().Print();
            };

            ChildProcessTracker.AddProcess(process);
            process.BeginOutputReadLine();



            var config  = new MiraiHttpSessionOptions("127.0.0.1", 8080, "********");
            var session = new MiraiHttpSession();

            session.GroupMessageEvt += (sender, eventArgs) =>
            {
                //eventArgs.Chain[0].Type.Print();

                eventArgs.Chain.GetPlains().Print();
                return(Task.FromResult(false));
            };
            session.ConnectAsync(config, 3320645904).Wait();
            Console.ReadKey();

            // var sb1 = new StringBuilder();
            // foreach (var pair in dic.OrderByDescending(item => item.Value))
            // {
            //     sb1.AppendLine($"{pair.Key},{pair.Value}");
            // }
            // File.WriteAllText("tag.csv",sb1.ToString());
            // File.WriteAllLines("count.csv", count.Select(item => item.ToString()));
        }