我正在尝试为 irc 频道编写机器人,它将从频道读取消息,识别它们是否是对他的命令,并根据发送的命令执行一些操作。我选择 ircDotNet 是因为它是唯一一个包含一些如何使用它的示例的库,但它们实际上非常过时,只有一半有效。我在 C# 和编程方面缺乏经验,根本无法让我在没有好的例子的情况下理解东西:(
所以我的程序现在做了什么:
- 使用密码登录服务器
- 加入频道
- 注销(非常错误)
我无法从频道捕获和发送任何消息,也无法立即注销。
用于登录的全局类和在事件中随处使用的 IrcClient 类示例
public IrcRegistrationInfo irc_iri
{
get
{
return new IrcUserRegistrationInfo()
{
NickName = "jsBot",
UserName = "jsBot",
RealName = "jsBot",
Password = "oauth:p4$$w0rdH3Re48324729214812489"
};
}
}
public IrcClient gIrcClient = new IrcClient();
还有所有时事:
private void Form1_Load(object sender, EventArgs e)
{
try
{
gIrcClient.Connected += ircClient_Connected;
gIrcClient.Disconnected += gIrcClient_Disconnected;
gIrcClient.FloodPreventer = new IrcStandardFloodPreventer(1, 10000);
}
catch (Exception ex) { MessageBox.Show(ex.ToString());}
}
登录按钮代码:
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
if (!gIrcClient.IsConnected)
{
button1.Text = "Connecting...";
gIrcClient.Connect("irc.twitch.tv", 6667, false, irc_iri);
}
else
{
button1.Text = "Disconnecting...";
gIrcClient.Quit(5000, "bye");
}
}
逻辑是:程序检查ircClient是否连接,并做一些动作。然后在该操作之后将引发适当的事件,再次启用该按钮。但是那个 Quit 函数工作得很慢或者根本不工作,bot 会一直呆在频道上,直到我不关闭我的程序(也许我需要处理 ircclient?)
连接和断开事件。在连接事件中,机器人将加入频道。Bot 在我按下连接按钮后约 30 秒后出现在频道中,但连接事件在 2-3 秒后引发。断开连接也是如此 - 断开连接事件迅速引发,但机器人在通道上停留的时间要长得多(大约 120 秒)。
void ircClient_Connected(object sender, EventArgs e)
{
try
{
if (button1.InvokeRequired)
{
MethodInvoker del = delegate {
button1.Text = "Disconnect";
button1.Enabled = true; };
button1.Invoke(del);
}
else
{
button1.Text = "Disconnect";
button1.Enabled = true;
}
gIrcClient.Channels.Join("#my_channel");
gIrcClient.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
void gIrcClient_Disconnected(object sender, EventArgs e)
{
if (!gIrcClient.IsConnected)
{
try
{
if (button1.InvokeRequired)
{
MethodInvoker del = delegate
{
button1.Text = "Connect";
button1.Enabled = true;
};
button1.Invoke(del);
}
else
{
button1.Text = "Connect";
button1.Enabled = true;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
else gIrcClient.Disconnect();
}
加入频道和消息接收事件。他们从不提高,不知道为什么。
void LocalUser_JoinedChannel(object sender, IrcChannelEventArgs e)
{
try
{
gIrcClient.Channels[0].MessageReceived += Form1_MessageReceived;
gIrcClient.LocalUser.SendMessage(e.Channel, "test");
MessageBox.Show(gIrcClient.Channels[0].Users[0].User.NickName);
MessageBox.Show("bot_join_channel_event_raised");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
void Form1_MessageReceived(object sender, IrcMessageEventArgs e)
{
try
{
if (e.Text.Equals("asd"))
gIrcClient.LocalUser.SendMessage(e.Targets, "received");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
所以主要问题是:我如何从频道捕获消息以及如何将消息发送到频道?我会很感激任何例子。您可以在这里找到所有代码:http: //pastebin.com/TBkfL3Vq 谢谢