forked from Headline/Steam-Discord-Bot
/
MarkovHandler.cs
200 lines (169 loc) · 5.71 KB
/
MarkovHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using SteamDiscordBot;
using Discord;
using Markov;
using SteamDiscordBot.Commands;
class MarkovHandler
{
private ConcurrentDictionary<ulong, MarkovChain<string>> dict;
private ConcurrentDictionary<ulong, string> nextResponse;
private Random rand;
public MarkovHandler()
{
dict = new ConcurrentDictionary<ulong, MarkovChain<string>>();
nextResponse = new ConcurrentDictionary<ulong, string>();
rand = new Random();
}
public async Task AddGuild(ulong guild)
{
if (dict.ContainsKey(guild)) // we must've disconnected briefly, but still have our data
return;
var path = Program.BuildPath(guild + ".txt");
var markov = new MarkovChain<string>(1);
dict.TryAdd(guild, markov);
nextResponse.TryAdd(guild, "");
if (!File.Exists(path))
{
File.CreateText(path); // guild non-existant. Make empty file and move on
return;
}
await LoadGraph(markov, path, guild);
BuildNext(guild);
}
private async Task LoadGraph(MarkovChain<string> markov, string path, ulong guild)
{
try
{
/*
* Unforunately with huge files, using StreamReader alone is too slow,
* so we use BufferedStream to speed things up a bit.
*/
using (FileStream fileStream = File.Open(path, FileMode.Open))
{
using (BufferedStream bufferedStream = new BufferedStream(fileStream))
using (StreamReader reader = new StreamReader(bufferedStream))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
string[] pieces = line.ToLower().Split(' ');
markov.Add(pieces, 1);
}
}
}
}
catch { }
}
public void WriteToGuild(ulong guild, string line)
{
if (WriteLineToFile(guild + ".txt", line))
{
string[] pieces = line.Split(' ');
this.dict[guild].Add(pieces, 1);
}
}
public async Task<int> RemoveFromGuild(ulong guild, string term)
{
int retval = await MarkovHandler.RemoveTermFromFile(guild + ".txt", term);
var markov = new MarkovChain<string>(1);
dict.TryUpdate(guild, markov, this.dict[guild]);
await LoadGraph(markov, Program.BuildPath(guild + ".txt"), guild);
BuildNext(guild);
return retval;
}
public string ReadFromGuild(ulong guild)
{
var str = nextResponse[guild];
BuildNext(guild);
return str;
}
public string ReadFromGuild(ulong guild, string[] phrase)
{
var markovstr = this.dict[guild];
return string.Join(" ", markovstr.Chain(phrase, rand));
}
public void BuildNext(ulong guild)
{
var markovstr = this.dict[guild];
this.nextResponse[guild] = string.Join(" ", markovstr.Chain(rand));
if (this.nextResponse[guild] == "" && this.dict[guild].GetStates().Count() > 0)
{
BuildNext(guild);
}
}
public string GetHastebinLink(ulong guild)
{
string[] inputArray = File.ReadAllLines(guild + ".txt");
string input = "";
foreach (string line in inputArray)
input += line + "\n";
return FactsListCommand.UploadHastebin(input);
}
private static bool WriteLineToFile(string file, string line)
{
if (line.ToLower().Contains("http")
|| line.ToLower().Contains(".com")
|| line.Split(' ').Length < 3
|| line.Contains("<")
|| line[line.Length - 1] == ';'
|| line.Contains("()")
|| line.Contains("{")
|| line.Contains("}")
|| line.Contains("```"))
{
return false;
}
try
{
using (FileStream stream = new FileStream(Program.BuildPath(file), FileMode.Append))
{
Byte[] info = new UTF8Encoding(true).GetBytes((line + "\n"));
stream.Write(info, 0, info.Length);
}
return true;
}
catch (Exception e)
{
Program.Instance.Log(new LogMessage(LogSeverity.Info, "MarkovHandler.WriteLineToFile", e.Message));
return false;
}
}
public static async Task<int> RemoveTermFromFile(string file, string needle)
{
int count = 0;
List<string> array = new List<string>();
using (FileStream fileStream = File.Open(Program.BuildPath(file), FileMode.Open))
using (BufferedStream bufferedStream = new BufferedStream(fileStream))
using (StreamReader reader = new StreamReader(bufferedStream))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
if (!line.Contains(needle))
array.Add(line);
else
count++;
}
}
using (FileStream fileStream = File.Open(Program.BuildPath(file), FileMode.Create))
using (BufferedStream bufferedStream = new BufferedStream(fileStream))
using (StreamWriter reader = new StreamWriter(bufferedStream))
{
foreach(string line in array)
{
await reader.WriteLineAsync(line);
}
}
return count;
}
public string GetPhraseFromFile(ulong file, string term = null)
{
return this.nextResponse[file];
}
}