【发布时间】:2015-08-11 20:35:29
【问题描述】:
所以我正在制作一个连接到 twitch irc 聊天的机器人。这是代码:
Console.WriteLine("Joining Room");
IrcClient irc = new IrcClient("irc.twitch.tv", 6667, "ScottBots", "oauth:asdasd");
irc.joinRoom("ScottBots");
Console.WriteLine("Joined Room");
int i = 0;
while (true)
{
string message = irc.readMessage();
if(message.Contains("!helps"))
{
irc.sendChatMessage("Welcome to ScottBots! Currently in development.");
}
Console.WriteLine("loop: " + i);
i++;
}
看看 while true 循环......一切都好吗?
现在看看这个控制台应用程序给了我什么:
Joining Room
Joined Room
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9
9点就停了?
你们中的许多人都在询问我的 ircClient 代码:
private string username;
private string channel;
private TcpClient tcpClient;
private StreamReader inputStream;
private StreamWriter outputSteam;
public IrcClient(string ip, int port, string username, string password)
{
this.username = username;
tcpClient = new TcpClient(ip, port);
inputStream = new StreamReader(tcpClient.GetStream());
outputSteam = new StreamWriter(tcpClient.GetStream());
try
{
outputSteam.WriteLine("PASS " + password);
outputSteam.WriteLine("NICK " + username);
outputSteam.WriteLine("USER " + username + " 8 * :" + username);
outputSteam.Flush();
} catch (Exception e)
{
}
}
public void joinRoom(string channel)
{
try
{
this.channel = channel;
outputSteam.WriteLine("JOIN #" + channel);
outputSteam.Flush();
}
catch (Exception e)
{
Console.WriteLine("Failed to join room");
}
}
public void sendIrcMessage(string message)
{
try
{
outputSteam.WriteLine(message);
outputSteam.Flush();
}
catch (Exception e)
{
Console.WriteLine("failed to run sendIrcMessage() method");
}
}
public void sendChatMessage(string message)
{
sendIrcMessage(":" + username + "!" + username + "@" + username + ".tmi.twitch.tv PRIVNSG #" + channel + " : " + message);
}
public string readMessage()
{
string message = inputStream.ReadLine();
return message;
}
【问题讨论】:
-
很可能您的
irc.XXX方法之一失败并在循环中引发异常。 -
我应该尝试一下吗? @Eser
-
string message = irc.readMessage();这是否等待消息,例如Console.ReadLine()?也许它正在等待输入。当程序看似停止时暂停,然后调试它 -
irc 是否有一个 API,一旦有消息可用,您就会在其中进行回调?这对您的资源来说会容易得多...
-
@flp 我不这么认为。我是 C# 的新手,不知道该怎么做。对不起。我用我的 IrcClient 类更新了帖子。也许你可以看看。
标签: c# loops while-loop