1+ #include < iostream>
2+ // 使用静态库必须要在引入 mirai.h 前定义这个宏
3+ #define MIRAICPP_STATICLIB
4+ // 按需引用头文件
5+ // 你也可以使用 #include <mirai.h> 引用所有头文件(可能导致编译缓慢)
6+ #include < mirai/MiraiBot.hpp>
7+ #include < mirai/events/OtherClientMessage.hpp>
8+ #include < mirai/events/FriendSyncMessage.hpp>
9+ using namespace std ;
10+ using namespace Cyan ;
11+
12+ int main (int argc, char * argv[])
13+ {
14+ // 源文件使用 UTF-8 编码保存,在 Windows 上需要切换代码页才不会显示乱码
15+ #if defined(WIN32) || defined(_WIN32)
16+ system (" chcp 65001" );
17+ #endif
18+
19+ MiraiBot bot;
20+ SessionOptions opts = SessionOptions::FromCommandLine (argc, argv);
21+
22+ // 自动重试地与 mirai-api-http 建立连接
23+ while (true )
24+ {
25+ try
26+ {
27+ bot.Connect (opts);
28+ break ;
29+ }
30+ catch (const std::exception& ex)
31+ {
32+ cout << ex.what () << endl;
33+ }
34+ MiraiBot::SleepSeconds (1 );
35+ }
36+
37+ // 检查一下版本
38+ try
39+ {
40+ string mah_version = bot.GetMiraiApiHttpVersion ();
41+ string mc_version = bot.GetMiraiCppVersion ();
42+ cout << " mirai-api-http 的版本: " << mah_version
43+ << " ; mirai-cpp 的版本: " << mc_version << " ; " << endl;
44+ if (mah_version != mc_version)
45+ {
46+ cout << " Warning: 你的 mirai-api-http 插件的版本与 mirai-cpp 的版本不同,可能存在兼容性问题。" << endl;
47+ }
48+ }
49+ catch (const std::exception& ex)
50+ {
51+ cout << ex.what () << endl;
52+ }
53+
54+ cout << " Bot Working..." << endl;
55+
56+ // 修改 groupId 以测试发送群公告!
57+ auto groupId = 12345678_gid;
58+ if (groupId != 12345678_gid)
59+ {
60+ try
61+ {
62+ MiraiImage img;
63+ // 设置 img 的 Path、Base64 或 Url 以设置群公告图片(设置 Id 无效)
64+ // img.Base64 = "...";
65+ auto options = GroupAnnouncement::PublishFlags::Pinned | GroupAnnouncement::PublishFlags::RequireConfirmation;
66+ auto result = bot.PublishGroupAnnouncement (groupId, " 测试测试222" , options, img);
67+ cout << " 已经发送群公告:" << result.Content << endl;
68+ }
69+ catch (const std::exception& ex)
70+ {
71+ cout << ex.what () << endl;
72+ }
73+ }
74+ else
75+ {
76+ cout << " 修改 groupId 以测试发送群公告!" << endl;
77+ }
78+
79+ bot.On <LostConnection>([&](LostConnection e)
80+ {
81+ cout << e.ErrorMessage << " (" << e.Code << " )" << endl;
82+ while (true )
83+ {
84+ try
85+ {
86+ cout << " 尝试与 mirai-api-http 重新建立连接..." << endl;
87+ bot.Reconnect ();
88+ break ;
89+ }
90+ catch (const std::exception& ex)
91+ {
92+ cout << ex.what () << endl;
93+ }
94+ MiraiBot::SleepSeconds (1 );
95+ }
96+ cout << " 成功与 mirai-api-http 重新建立连接!" << endl;
97+ });
98+
99+ bot.On <EventParsingError>([&](EventParsingError e)
100+ {
101+ try
102+ {
103+ e.Rethrow ();
104+ }
105+ catch (const std::exception& ex)
106+ {
107+ cout << " 解析事件时出现错误: " << ex.what () << endl;
108+ }
109+ });
110+
111+ string command;
112+ while (cin >> command)
113+ {
114+ if (command == " exit" ) break ;
115+ }
116+
117+ // 程序结束前必须释放 Session, 否则会导致 mirai-api-http 内存泄漏
118+ bot.Disconnect ();
119+
120+ return 0 ;
121+ }
0 commit comments