Skip to content

Commit e2ea596

Browse files
committed
add hasTty
1 parent 571ffa7 commit e2ea596

1 file changed

Lines changed: 45 additions & 20 deletions

File tree

src/HuaJiBot.NET.CLI/App.cs

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -92,28 +92,53 @@ BotServiceBase CreateService(Config config)
9292
}
9393
#endregion
9494
await Internal.SetupAsync(api, pluginDir); //启动
95-
while (true)
95+
bool hasTty;
96+
try
9697
{
97-
if (Console.ReadLine() is { } line)
98+
// Try to get cursor position to determine whether we are attached to a real TTY.
99+
// Console.GetCursorPosition throws when output is redirected, so this is a good probe.
100+
_ = Console.GetCursorPosition();
101+
102+
// Also ensure input/output are not redirected
103+
hasTty = !Console.IsInputRedirected && !Console.IsOutputRedirected;
104+
}
105+
catch
106+
{
107+
hasTty = false;
108+
}
109+
110+
if (hasTty)
111+
while (true)
98112
{
99-
var cmds = line.Split(' ');
100-
switch (cmds)
113+
if (Console.ReadLine() is { } line)
101114
{
102-
case ["quit" or "q"]:
103-
break;
104-
case ["r" or "rc"]:
105-
api.Reconnect();
106-
break;
107-
case ["save"]:
108-
var result = api.Config.Save();
109-
api.Log("配置文件保存成功:" + result);
110-
break;
111-
case ["send", var targetGroup, var message]:
112-
await api.SendGroupMessageAsync(accountId, targetGroup, message);
113-
break;
114-
default:
115-
Console.WriteLine($"未知的命令 {line} .");
116-
break;
115+
var cmds = line.Split(' ');
116+
switch (cmds)
117+
{
118+
case ["quit" or "q"]:
119+
break;
120+
case ["r" or "rc"]:
121+
api.Reconnect();
122+
break;
123+
case ["save"]:
124+
var result = api.Config.Save();
125+
api.Log("配置文件保存成功:" + result);
126+
break;
127+
case ["send", var targetGroup, var message]:
128+
await api.SendGroupMessageAsync(accountId, targetGroup, message);
129+
break;
130+
default:
131+
Console.WriteLine($"未知的命令 {line} .");
132+
break;
133+
}
117134
}
118135
}
119-
}
136+
var cts = new CancellationTokenSource();
137+
Console.CancelKeyPress += (sender, e) =>
138+
{
139+
e.Cancel = true;
140+
cts.Cancel();
141+
};
142+
Console.WriteLine("Running... Press Ctrl+C to exit.");
143+
await Task.Delay(Timeout.Infinite, cts.Token);
144+
Console.WriteLine("Exiting gracefully...");

0 commit comments

Comments
 (0)