Reputation: 28
Hey I want to create a chat bot for Twitch and I'm kind of a beginner in those things and this is my work so far:
Form1.cs as below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyTwitchChat
{
public partial class Form1 : Form
{
private string username;
private string password;
bool joined;
IRCClient ircClient;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
username = userNameTB.Text;
password = TokenBox.Text;
ircClient = new IRCClient("irc.chat.twitch.tv", 6667, username, password);
ircClient.joinChannel("deadlycursed");
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (ircClient.tcpClient.Available > 0 )
{
string message = ircClient.inputStream.ReadLine();
ChatBox.Items.Add(message);
if (message.Contains("!Hallo"))
ircClient.sendChatMessage("Hi!");
}
}
}
}
IRCClient.cs as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace MyTwitchChat
{
class IRCClient
{
private string username;
private string channel;
private string nickname = "deadlycursed";
public TcpClient tcpClient;
public StreamReader inputStream;
public StreamWriter outputStream;
public IRCClient(string ip, int port, string username, string password)
{
this.username = username;
tcpClient = new TcpClient(ip, port);
inputStream = new StreamReader(tcpClient.GetStream());
outputStream = new StreamWriter(tcpClient.GetStream());
outputStream.WriteLine("PASS " + password);
outputStream.WriteLine("NICK " + nickname);
outputStream.WriteLine("USER " + username + " 0 * :" + nickname );
outputStream.Flush();
}
public void joinChannel(string channel)
{
this.channel = channel;
outputStream.WriteLine("JOIN #" + channel);
outputStream.Flush();
}
public void sendIRCMessage(string message)
{
outputStream.WriteLine(message);
outputStream.Flush();
}
public void sendChatMessage(string message)
{
outputStream.WriteLine(":" + nickname + "!" + username + "@" + nickname + ".tmi.twitch.tv PRIVMSG #"
+ channel + ":" + message);
outputStream.Flush();
}
public string getMessage()
{
string message = inputStream.ReadLine();
return message;
}
}
}
And I would like to know why I actually can't send messages or receive them? Sometimes the reading thing works and sometimes not and I can't write to the chat with my bot
Upvotes: 2
Views: 4388
Reputation: 391
There are libraries for helping you do this, so you could either see how they work or use them directly.
For example most popular on NuGet seems to be:
TwitchLib - Twitch Chat and API C# Library - https://github.com/swiftyspiffy/TwitchLib
Upvotes: 1