move legacy code to separate branch

This commit is contained in:
Marco Realacci 2025-01-17 21:06:51 +01:00
parent 68a30c8ee6
commit 11b4c48c3a
3528 changed files with 14477 additions and 53258 deletions

View file

@ -0,0 +1,90 @@
using Newtonsoft.Json;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.ReplyMarkups;
namespace SoUnBot.AccessControl
{
public class AccessManager
{
private string _acl_path;
private Dictionary<long, HashSet<string>> _acl;
public long AdminId { get; private set; }
public AccessManager(string aclPath, long adminId)
{
_acl_path = aclPath;
AdminId = adminId;
if (!System.IO.File.Exists(aclPath + "/acl.json"))
{
_acl = new Dictionary<long, HashSet<string>>();
return;
}
var json = System.IO.File.ReadAllText(aclPath + "/acl.json");
_acl = JsonConvert.DeserializeObject<Dictionary<long, HashSet<string>>>(json) ?? new Dictionary<long, HashSet<string>>();;
}
public long[] Users()
{
return _acl.Keys.ToArray();
}
private void SaveToJson()
{
var json = JsonConvert.SerializeObject(_acl);
System.IO.File.WriteAllText(_acl_path + "/acl.json", json);
}
public void GrantPermission(long uid, string perm)
{
if (_acl.ContainsKey(uid)) _acl[uid].Add(perm);
else _acl.Add(uid, new HashSet<string> { perm });
SaveToJson();
}
public bool RevokePermission(long uid, string perm)
{
if (_acl.ContainsKey(uid)) _acl[uid].Remove(perm);
else return false;
SaveToJson();
return true;
}
public bool CheckPermission(long uid, string perm)
{
return _acl.ContainsKey(uid) ? _acl[uid].Contains(perm) : false;
}
public bool CheckPermission(User user, string perm, ITelegramBotClient client)
{
var uid = user.Id;
var hasPerm = _acl.ContainsKey(uid) ? _acl[uid].Contains(perm) : false;
if (hasPerm) return true;
client.SendTextMessageAsync(
chatId: uid,
text: $"ACM\nNon hai l'accesso a `{ perm }`. Puoi richiederlo ad un amministratore usando il pulsante qui sotto",
replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData("🔆 Richiedi accesso"))
);
return false;
}
public void AskPermission(User user, string perm, ITelegramBotClient client)
{
/*InlineKeyboardButton[][] ik = new InlineKeyboardButton[][]
{
new InlineKeyboardButton[]
{
new InlineKeyboardButton("✅ Grant")
},
new InlineKeyboardButton[]
{
new InlineKeyboardButton("❌ Deny")
}
};*/
client.SendTextMessageAsync(
chatId: AdminId,
text: $"ACM: { user.Id }\nL'utente { user.FirstName } { user.LastName } @{ user.Username }\nHa richiesto l'accesso a: { perm }",
replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData("✅ Grant"))
);
}
}
}

View file

@ -0,0 +1,12 @@
using Telegram.Bot;
using Telegram.Bot.Types;
namespace SoUnBot.ModuleLoader
{
public interface IModule
{
public string Cmd();
public string GetName();
public void ProcessUpdate(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken);
}
}

View file

@ -0,0 +1,18 @@
namespace SoUnBot.ModuleLoader
{
public class ModuleLoader
{
public Dictionary<string, IModule> Modules { get; private set; }
public ModuleLoader()
{
Modules = new Dictionary<string, IModule>();
}
public void LoadModule(IModule module)
{
if (Modules == null) Modules = new Dictionary<string, IModule>();
Modules.Add(module.Cmd(), module);
}
}
}

View file

@ -0,0 +1,565 @@
using System.Collections;
using Newtonsoft.Json;
using SoUnBot.AccessControl;
using SoUnBot.ModuleLoader;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types.ReplyMarkups;
using File = System.IO.File;
namespace SoUnBot.Modules.OttoLinux
{
public class BotGame : IModule
{
private AccessManager _accessManager;
private List<Question> _questions;
private string _questionsPath;
private string _name;
private bool _lock;
private string _imgBaseDir;
private Dictionary<long, OttoScore> _scores;
private Dictionary<long, Question> _playingQuestions;
private Dictionary<long, List<int>> _playedQuestions;
private Dictionary<Question, OttoScore> _questionStats;
private static Random _rng = new Random();
public BotGame(AccessManager accessManager, string name, string path, bool locke, string imgBaseDir, int version = 1)
{
_accessManager = accessManager;
_questionsPath = path;
_name = name;
_lock = locke;
_imgBaseDir = imgBaseDir;
_questions = new List<Question>();
_scores = new Dictionary<long, OttoScore>();
_playingQuestions = new Dictionary<long, Question>();
_questionStats = new Dictionary<Question, OttoScore>();
_playedQuestions = new Dictionary<long, List<int>>();
if (version == 2) LoadQuestionsV2();
else if (version == 3) LoadQuestionsJSON();
else LoadQuestions();
}
public BotGame(AccessManager accessManager)
{
_accessManager = accessManager;
_questions = new List<Question>();
_scores = new Dictionary<long, OttoScore>();
_playingQuestions = new Dictionary<long, Question>();
_questionStats = new Dictionary<Question, OttoScore>();
_playedQuestions = new Dictionary<long, List<int>>();
LoadQuestions();
}
private void LoadQuestions()
{
var lines = System.IO.File.ReadAllLines(_questionsPath);
Question cur = null;
var preEmpty = true;
foreach (var line in lines)
{
if (line.Equals("")) preEmpty = true;
else preEmpty = false;
if (line.StartsWith(">")) cur.AddAnswer(line.Substring(2), false);
else if (line.StartsWith("v")) cur.AddAnswer(line.Substring(2), true);
else
{
if (!preEmpty && cur != null)
{
cur.Append("\n" + line);
continue;
}
if (cur != null) _questions.Add(cur);
cur = new Question(line);
}
}
_questions.Add(cur);
SanitizeQuestions();
}
private void LoadQuestionsV2()
{
var questions = System.IO.Directory.GetFileSystemEntries(_questionsPath);
foreach (var questPath in questions)
{
var quest = System.IO.File.ReadAllText(questPath + "/quest.txt");
if (quest.StartsWith("img=")) quest = quest.Insert(quest.IndexOf("\n") + 1, questPath.Split(new char[] { '/', '\\' }).Last() + ". ");
else quest = questPath.Split(new char[] { '/', '\\' }).Last() + ". " + quest;
Question cur = new Question(quest);
var shuffledAnsPaths = Directory.GetFiles(questPath).OrderBy(a => _rng.Next()).ToArray();
foreach (var ansPath in shuffledAnsPaths)
{
if (ansPath.EndsWith("quest.txt")) continue;
if (ansPath.EndsWith(".png")) continue;
var ans = System.IO.File.ReadAllText(ansPath);
if (ansPath.EndsWith("correct.txt")) cur.AddAnswer(ans, true);
else cur.AddAnswer(ans, false);
}
_questions.Add(cur);
}
SanitizeQuestions();
}
private void LoadQuestionsJSON()
{
var json = System.IO.File.ReadAllText(_questionsPath);
var quests = JsonConvert.DeserializeObject<Question[]>(json);
if (quests != null) _questions = quests.ToList();
}
private void SanitizeQuestions()
{
var invalidQuestions = new List<Question>();
foreach (var qst in _questions)
{
while (qst.Quest.StartsWith("\n")) qst.Quest = qst.Quest.Substring(1);
for (int i = 0; i < qst.Answers.Count; i++)
{
while (qst.Answers[i].StartsWith("\n")) qst.Answers[i] = qst.Answers[i].Substring(1);
}
if (qst.Quest == "")
{
invalidQuestions.Add(qst);
Console.WriteLine("an empty question was found, skipping it");
}
else if(qst.Answers.Count == 0)
{
invalidQuestions.Add(qst);
Console.WriteLine($"The following question: {qst.Quest} \nhas no answers, skipping it");
}
}
_questions = _questions.Except(invalidQuestions).ToList();
}
public Question PickRandomQuestion(long player, ITelegramBotClient botClient)
{
//WebRequest w = WebRequest.Create($"https://www.random.org/integers/?num=1&min=1&max={_questions.Count - 1 }&col=1&base=10&format=plain&rnd=new");
//w.Method = "GET";
//var number = int.Parse(new StreamReader(w.GetResponse().GetResponseStream()).ReadToEnd());
var number = _rng.Next(0, _questions.Count - 1);
while (_questions[number].Quest == "")
{
number = _rng.Next(0, _questions.Count - 1);
}
if (!_playedQuestions.ContainsKey(player)) _playedQuestions.Add(player, new List<int>());
if (_playedQuestions[player].Count >= _questions.Count)
{
_playedQuestions[player].Clear();
botClient.SendTextMessageAsync(
chatId: player,
text: $"🥳🥳🥳 Congratulazioni! Hai risposto a tutte le {_questions.Count} domande!"
);
}
while (_playedQuestions[player].Contains(number))
{
if (number < _questions.Count - 1) number++;
else number = 0;
}
_playedQuestions[player].Add(number);
return _questions[number];
}
public string Cmd()
{
return GetName();
}
async void IModule.ProcessUpdate(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
var uid = update.Message.From.Id;
if (_lock)
{
if (!_accessManager.CheckPermission(update.Message.From, Cmd(), botClient)) return;
}
else
{
if (!_accessManager.CheckPermission(uid, Cmd()))
{
_accessManager.GrantPermission(uid, Cmd());
await botClient.SendTextMessageAsync(
chatId: _accessManager.AdminId,
text: $"ACM: { update.Message.From.Id }\nL'utente { update.Message.From.FirstName } { update.Message.From.LastName } @{ update.Message.From.Username }\nHa iniziato a usare il bot."
);
}
}
//if (!scores.Keys.Contains(uid))
//{
// await botClient.SendTextMessageAsync(
// chatId: _acm.AdminId,
// text: $"ACM: { update.Message.From.Id }\nL'utente { update.Message.From.FirstName } { update.Message.From.LastName } @{ update.Message.From.Username }\nHa iniziato a usare il bot."
// );
//}
if (update.Type != UpdateType.Message)
return;
if (update.Message!.Type != MessageType.Text)
return;
if (update.Message.Text.StartsWith("/qsc"))
{
int number = 1;
if (update.Message.Text.Length > 4) int.TryParse(update.Message.Text.Substring(5), out number);
var mostCorrect = _questionStats.GroupBy(e => e.Value.Correct).ToDictionary(e => e.Key, t => t.Select(r => r.Key).ToArray());
var c = 0;
foreach (var item in mostCorrect.Keys.OrderByDescending(i => i))
{
if (c == number) break;
var msg = mostCorrect[item].Select(q => q.Quest.Substring(0, 30)).Aggregate((a, b) => a + "\n\n" + b);
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"✅ Risposte indovinate {item} volte:\n{msg}");
c++;
}
return;
}
if (update.Message.Text.StartsWith("/qsw"))
{
int number = 1;
if (update.Message.Text.Length > 4) int.TryParse(update.Message.Text.Substring(5), out number);
var mostWrong = _questionStats.GroupBy(e => e.Value.Wrong).ToDictionary(e => e.Key, t => t.Select(r => r.Key).ToArray());
var c = 0;
foreach (var item in mostWrong.Keys.OrderByDescending(i => i))
{
if (c == number) break;
var msg = mostWrong[item].Select(q => q.Quest.Substring(0, 30)).Aggregate((a, b) => a + "\n\n" + b);
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"❌ Risposte sbagliate {item} volte:\n{msg}");
c++;
}
return;
}
if (update.Message.Text.StartsWith("/qsb"))
{
int number = 1;
if (update.Message.Text.Length > 4) int.TryParse(update.Message.Text.Substring(5), out number);
var mostBlank = _questionStats.GroupBy(e => e.Value.Blank).ToDictionary(e => e.Key, t => t.Select(r => r.Key).ToArray());
var c = 0;
foreach (var item in mostBlank.Keys.OrderByDescending(i => i))
{
if (c == number) break;
var msg = mostBlank[item].Select(q => q.Quest.Substring(0, 30)).Aggregate((a, b) => a + "\n\n" + b);
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"🟡 Risposte non date {item} volte:\n{msg}");
c++;
}
return;
}
if (update.Message.Text.Equals("/rsp"))
{
if (!_playedQuestions.ContainsKey(uid))
{
await botClient.SendTextMessageAsync(
chatId: uid,
text: "❌ Non c'è niente da eliminare!");
return;
}
_playedQuestions[uid].Clear();
await botClient.SendTextMessageAsync(
chatId: uid,
text: "✅ Memoria eliminata!");
return;
}
if ((!_playingQuestions.ContainsKey(uid)) || update.Message.Text == GetName().ToLower() || update.Message.Text == "/" + GetName().ToLower() || update.Message.Text == "/reset" || update.Message.Text == "/restart")
{
if (_scores.ContainsKey(update.Message.From.Id)) _scores[update.Message.From.Id] = new OttoScore();
else _scores.Add(update.Message.From.Id, new OttoScore());
SendRandomQuestion(update.Message.From.Id, botClient, cancellationToken);
return;
}
var cur = _playingQuestions[uid];
var wrongMsg = "🟡 La risposta corretta era la " + (cur.Correct + 1) + " ☹️";
if (update.Message.Text == "n" || update.Message.Text == "Passa")
{
_scores[uid].Blank += 1;
_questionStats[cur].Blank += 1;
await botClient.SendTextMessageAsync(
chatId: uid,
text: wrongMsg
);
SendRandomQuestion(uid, botClient, cancellationToken);
return;
}
//todo try parse
var pick = -1;
if (!int.TryParse(update.Message.Text, out pick))
{
await botClient.SendTextMessageAsync(
chatId: uid,
text: "❓ scusa, non ho capito 😭");
await botClient.SendTextMessageAsync(
chatId: uid,
text: "⭕️ per uscire da 8linux, scrivi /leave");
return;
}
pick -= 1;
if (pick == _playingQuestions[uid].Correct)
{
await botClient.SendTextMessageAsync(
chatId: uid,
text: "✅ Risposta esatta!");
_scores[uid].Correct += 1;
_questionStats[cur].Correct += 1;
}
else
{
await botClient.SendTextMessageAsync(
chatId: uid,
text: "❌ Risposta errata!");
await botClient.SendTextMessageAsync(
chatId: uid,
text: wrongMsg);
_scores[uid].Wrong += 1;
_questionStats[cur].Wrong += 1;
}
SendStats(uid, botClient, cancellationToken);
await Task.Delay(400);
SendRandomQuestion(uid, botClient, cancellationToken);
}
private async void SendRandomQuestion(long uid, ITelegramBotClient botClient, CancellationToken cancellationToken)
{
var qst = PickRandomQuestion(uid, botClient);
try
{
if (qst.Quest.Length <= 40)
{
Console.WriteLine("Sto inviando la domanda " + qst.Quest + " a " + uid);
}
else
{
Console.WriteLine("Sto inviando la domanda " + qst.Quest.Substring(0, 40) + " a " + uid);
}
}
catch(Exception e)
{
botClient.SendTextMessageAsync(
chatId: _accessManager.AdminId,
text: $"Question is malformed -> {qst.Quest} \n {e.Message}"
);
return;
}
if (!_questionStats.ContainsKey(qst)) _questionStats.Add(qst, new OttoScore());
if (_playingQuestions.ContainsKey(uid)) _playingQuestions[uid] = qst;
else _playingQuestions.Add(uid, qst);
string answers = "";
List<KeyboardButton> kbs = new List<KeyboardButton>();
bool splitAns = false;
foreach (var ans in qst.Answers)
if ((ans.Contains("\n") && ans.Substring(ans.IndexOf("\n")).Length > 1 ) || ans.Contains("img=")) splitAns = true;
var corry = qst.Answers[qst.Correct];
for (int i = 0; i < qst.Answers.Count; i++)
{
if (!splitAns) answers += (i + 1) + ". " + qst.Answers[i] + "\n\n";
kbs.Add((i + 1).ToString());
}
KeyboardButton[] fr = kbs.ToArray();
ReplyKeyboardMarkup replyKeyboardMarkup = new(new[]
{
fr,
new KeyboardButton[] { "Passa" },
})
{
ResizeKeyboard = true
};
string quest = qst.Quest;
if (!string.IsNullOrEmpty(qst.Image))
{
try
{
if (qst.Image.Contains("http"))
{
await botClient.SendPhotoAsync(
chatId: uid,
photo: qst.Image);
}
else
{
await botClient.SendPhotoAsync(
chatId: uid,
photo: File.OpenRead(_imgBaseDir + "/" + qst.Image));
}
}
catch(Exception e)
{
CatchParsingError(botClient, quest, uid, e);
}
}
if (qst.Quest.StartsWith("img="))
{
try
{
if (qst.Image.Contains("http"))
{
await botClient.SendPhotoAsync(
chatId: uid,
photo: quest.Substring(4).Split('\n')[0]);
}
else
{
await botClient.SendPhotoAsync(
chatId: uid,
photo: File.OpenRead(_imgBaseDir + "/" + quest.Substring(4).Split('\n')[0]));
}
}
catch(Exception e)
{
CatchParsingError(botClient, quest, uid, e);
}
quest = quest.Substring(quest.IndexOf('\n') + 1);
}
try
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: uid,
text: "📎 " + PrepareHtml(quest) + "\n\n" + PrepareHtml(answers),
replyMarkup: replyKeyboardMarkup,
parseMode: ParseMode.Html
);
}
catch (Exception e) { CatchParsingError(botClient, quest, uid, e); }
if (splitAns)
{
for (int i = 0; i < qst.Answers.Count; i++)
{
await Task.Delay(350);
if (qst.Answers[i].StartsWith("img="))
{
try
{
if (qst.Image.Contains("http"))
{
await botClient.SendPhotoAsync(
chatId: uid,
photo: qst.Answers[i].Split('\n')[0].Substring(4));
}
else
{
await botClient.SendPhotoAsync(
chatId: uid,
photo: File.OpenRead(_imgBaseDir + "/" + qst.Answers[i].Split('\n')[0].Substring(4)));
}
}
catch(Exception e)
{
CatchParsingError(botClient, "[R] " + qst.Answers[i].Substring(0, 20) + " -> " + quest, uid, e);
}
}
else
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: uid,
text: "✏️ Risposta " + PrepareHtml((i + 1) + ":\n" + qst.Answers[i]),
replyMarkup: replyKeyboardMarkup,
parseMode: ParseMode.Html
);
}
}
}
}
private async void CatchParsingError(ITelegramBotClient botClient, string quest, long uid, Exception e)
{
await botClient.SendTextMessageAsync(
chatId: uid,
text: "❌ Cercavo di inviarti una domanda ma si è verificato un errore anomalo nel parsing. Per favore, invia /restart per resettarmi.\nL'errore verrà automaticamente segnalato (visto che tecnologia avanzatissima?)"
);
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"❌ La domanda {quest.Substring(0, 60)} è rotta.\nSi è verificato {e.Message}"
);
}
private static string PrepareHtml(string s)
{
return s.Replace("<", "&lt;")
.Replace(">", "&gt;")
.Replace("&lt;code&gt;", "<code>")
.Replace("&lt;/code&gt;", "</code>")
.Replace("&lt;pre&gt;", "<pre>")
.Replace("&lt;/pre&gt;", "</pre>")
.Replace("&lt;b&gt;", "<b>")
.Replace("&lt;/b&gt;", "</b>");
}
private async void SendStats(long uid, ITelegramBotClient botClient, CancellationToken cancellationToken)
{
var stats = _scores[uid];
var total = stats.Correct + stats.Wrong + stats.Blank;
await botClient.SendTextMessageAsync(
chatId: uid,
text: stats.Correct + " corrette (" + ((float)stats.Correct / (float)total) * 100f + "%)\n" + stats.Wrong + " errate (" + ((float)stats.Wrong / (float)total) * 100f + "%)\n" + stats.Blank + " non date (" + ((float)stats.Blank / (float)total) * 100f + "%)\n");
}
public string GetName()
{
return _name;
}
public List<Question> GetQuestions()
{
return _questions;
}
}
}

View file

@ -0,0 +1,197 @@
// This feature is not maintained anymore
// it has been commented as it depends on the old project structure
/** using HomeBot.ACL;
using HomeBot.ModuleLoader;
using System.Net;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
namespace HomeBot.Modules.OttoLinux
{
public class OttoReverse : IModule
{
private List<Question> _questions;
private string NAME = "8reverse";
private bool LOCK = false;
public OttoReverse(string name, List<Question> questions, bool lck)
{
_questions = questions;
LOCK = lck;
NAME = name;
Thread thread = new Thread(() => new WebReverse(GetMatch));
thread.Start();
}
public string Cmd()
{
return GetName();
}
public List<Question> GetMatch(string qst)
{
var m = qst
.Replace("\n", "")
.Replace("\r", "")
.Replace("<pre>", "")
.Replace("<code>", "")
.Replace("</pre>", "")
.Replace("</code>", "")
.Replace("'", "")
.Replace("à", "a")
.Replace("è", "e")
.Replace("é", "e")
.Replace("ì", "i")
.Replace("ò", "o")
.Replace("ù", "u")
.Replace(" ", "")
.Replace(" ", "")
.ToLower();
var filtered = _questions.FindAll((Question q) =>
{
return q.Quest
.Replace("\n", "")
.Replace("\r", "")
.Replace("<pre>", "")
.Replace("<code>", "")
.Replace("</pre>", "")
.Replace("</code>", "")
.Replace("'", "")
.Replace("à", "a")
.Replace("è", "e")
.Replace("é", "e")
.Replace("ì", "i")
.Replace("ò", "o")
.Replace("ù", "u")
.Replace(" ", "")
.Replace(" ", "")
.ToLower()
.Contains(m);
});
return filtered;
}
async void IModule.ProcessUpdate(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
var uid = update.Message.Chat.Id;
if (LOCK)
{
if (!ACM.CheckPermission(update.Message.From, Cmd(), botClient)) return;
}
else
{
if (!ACM.CheckPermission(uid, Cmd()))
{
ACM.GrantPermission(uid, Cmd());
await botClient.SendTextMessageAsync(
chatId: _acm.AdminId,
text: $"ACM: {update.Message.From.Id}\nL'utente {update.Message.From.FirstName} {update.Message.From.LastName} @{update.Message.From.Username}\nHa iniziato a usare il bot."
);
}
}
if (update.Type != UpdateType.Message)
return;
if (update.Message!.Type != MessageType.Text)
return;
if (update.Message.Text.Equals("/" + NAME))
{
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"🤫 Hai appena scoperto una funzione nascosta! 🤐🥶"
);
return;
}
var m = update.Message.Text
.Replace("\n", "")
.Replace("\r", "")
.Replace("<pre>", "")
.Replace("<code>", "")
.Replace("</pre>", "")
.Replace("</code>", "")
.Replace("'", "")
.Replace("à", "a")
.Replace("è", "e")
.Replace("é", "e")
.Replace("ì", "i")
.Replace("ò", "o")
.Replace("ù", "u")
.Replace(" ", "")
.Replace(" ", "")
.ToLower();
if (string.IsNullOrEmpty(m)) return;
var filtered = _questions.FindAll((Question q) =>
{
return q.Quest
.Replace("\n", "")
.Replace("\r", "")
.Replace("<pre>", "")
.Replace("<code>", "")
.Replace("</pre>", "")
.Replace("</code>", "")
.Replace("'", "")
.Replace("à", "a")
.Replace("è", "e")
.Replace("é", "e")
.Replace("ì", "i")
.Replace("ò", "o")
.Replace("ù", "u")
.Replace(" ", "")
.Replace(" ", "")
.ToLower()
.Contains(m);
});
if (!filtered.Any())
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"❌ No match :("
);
else
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"✅ Found {filtered.Count} matches!"
);
foreach (var q in filtered)
{
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"❓ Possible match:\n\n{q.Quest}"
);
await Task.Delay(250);
await botClient.SendTextMessageAsync(
chatId: uid,
text: $"✅ Correct answare for the match:\n\n{q.Answers[q.Correct]}"
);
await Task.Delay(500);
}
}
public string GetName()
{
return NAME;
}
public void ProcessUpdate(ITelegramBotClient botClient, global::Telegram.Bot.Types.Update update, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public List<Question> GetQuestions()
{
return _questions;
}
}
} **/

View file

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoUnBot.Modules.OttoLinux
{
public class OttoScore
{
public int Score { get; set; }
public int Correct { get; set; }
public int Wrong { get; set; }
public int Blank { get; set; }
}
}

View file

@ -0,0 +1,66 @@
// This feature is not maintained anymore
// it was exposing a webserver returning a json with all the questions and answers.
// It was originally intended for a web version of the bot, but was never completed.
using System.Net;
namespace SoUnBot.Modules.OttoLinux
{
public class PhotoServer
{
public PhotoServer(string baseDir)
{
using var listener = new HttpListener();
listener.Prefixes.Add("http://+:8001/");
listener.Start();
Console.WriteLine("PhotoServer is listening on port 8001...");
while (true)
{
HttpListenerContext ctx = listener.GetContext();
using HttpListenerResponse resp = ctx.Response;
resp.StatusCode = (int)HttpStatusCode.OK;
resp.StatusDescription = "Status OK";
resp.AddHeader("Access-Control-Allow-Origin", "*");
resp.AddHeader("Access-Control-Allow-Headers", "*");
resp.AddHeader("Access-Control-Allow-Methods", "GET");
if (ctx.Request.Url == null)
{
resp.StatusCode = (int)HttpStatusCode.BadRequest;
continue;
}
if (!File.Exists(baseDir + "/" + ctx.Request.Url.AbsolutePath))
{
resp.StatusCode = (int)HttpStatusCode.NotFound;
continue;
}
if (ctx.Request.Url.AbsolutePath.EndsWith("png"))
{
resp.AddHeader("Content-Type", "image/png");
}
else if (ctx.Request.Url.AbsolutePath.EndsWith("jpg"))
{
resp.AddHeader("Content-Type", "image/jpeg");
}
else
{
resp.StatusCode = (int)HttpStatusCode.BadRequest;
continue;
}
byte[] buffer = File.ReadAllBytes(baseDir + "/" + ctx.Request.Url.AbsolutePath);
resp.ContentLength64 = buffer.Length;
using Stream ros = resp.OutputStream;
try
{
ros.Write(buffer, 0, buffer.Length);
} catch { }
}
}
}
}

View file

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace SoUnBot.Modules.OttoLinux
{
public class Question
{
[JsonProperty("quest")]
public String Quest { get; set; }
[JsonProperty("answers")]
public List<string> Answers { get; }
[JsonProperty("correct")]
public int Correct { get; private set; }
[JsonProperty("image")]
public string Image { get; private set; }
public Question(String quest)
{
Quest = quest;
Answers = new List<string>();
Correct = 0;
}
public void AddAnswer(String answer, bool correct)
{
Answers.Add(answer);
Correct = correct ? Answers.Count - 1 : Correct;
}
public void Append(String quest)
{
Quest += quest;
}
}
}

View file

@ -0,0 +1,57 @@
// This feature is not maintained anymore
// it was exposing a webserver returning a json with all the questions and answers.
// It was originally intended for a web version of the bot, but was never completed.
/**using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
namespace SoUnBot.Modules.OttoLinux
{
internal class WebReverse
{
public WebReverse(Func<string, List<Question>> match)
{
using var listener = new HttpListener();
listener.Prefixes.Add("http://+:8001/");
listener.Start();
Console.WriteLine("Listening on port 8001...");
string pre = "";
while (true)
{
HttpListenerContext ctx = listener.GetContext();
using HttpListenerResponse resp = ctx.Response;
resp.StatusCode = (int)HttpStatusCode.OK;
resp.StatusDescription = "Status OK";
resp.AddHeader("Access-Control-Allow-Origin", "*");
resp.AddHeader("Access-Control-Allow-Headers", "*");
resp.AddHeader("Access-Control-Allow-Methods", "POST");
resp.AddHeader("Content-Type", "application/json");
var body = new StreamReader(ctx.Request.InputStream).ReadToEnd();
//if (body.Equals("")) body = pre;
pre = body;
string data = JsonConvert.SerializeObject(match(pre));
byte[] buffer = Encoding.UTF8.GetBytes(data);
resp.ContentLength64 = buffer.Length;
using Stream ros = resp.OutputStream;
try
{
ros.Write(buffer, 0, buffer.Length);
} catch { }
}
}
}
}
**/

60
Bot/Program.cs Normal file
View file

@ -0,0 +1,60 @@
using SoUnBot.AccessControl;
using SoUnBot.ModuleLoader;
using SoUnBot.Modules.OttoLinux;
using SoUnBot.Telegram;
string dataPath = Environment.GetEnvironmentVariable("DATA_PATH") ?? "BotData";
string aclPath = Environment.GetEnvironmentVariable("ACL_PATH") ?? "BotData/ACL";
string tgToken = Environment.GetEnvironmentVariable("TELEGRAM_TOKEN") ?? "this-string-is-not-a-token";
string tgAdminId = Environment.GetEnvironmentVariable("TELEGRAM_ADMIN_ID") ?? "000000";
string imagesPath = dataPath + "/Images";
Console.WriteLine("Welcome to SO un bot!");
long tgAdminLong;
if (!long.TryParse(tgAdminId, out tgAdminLong))
{
Console.WriteLine("Telegram Admin ID is invalid or unset");
return;
}
var acl = new AccessManager(aclPath, tgAdminLong);
var moduleLoader = new ModuleLoader();
try
{
foreach (string f in Directory.GetFiles(dataPath + "/Questions"))
{
if (f.EndsWith("txt"))
{
Console.WriteLine("Loading module " + Path.GetFileNameWithoutExtension(f));
moduleLoader.LoadModule(new BotGame(acl, Path.GetFileNameWithoutExtension(f), f, false, imagesPath));
}
else if (f.EndsWith("json"))
{
Console.WriteLine("Loading module " + Path.GetFileNameWithoutExtension(f));
moduleLoader.LoadModule(new BotGame(acl, Path.GetFileNameWithoutExtension(f), f, false, imagesPath, 3));
}
else
{
Console.WriteLine("Skipping " + Path.GetFileName(f) + " as the file extension is not supported");
}
}
foreach (string d in Directory.GetDirectories(dataPath + "/Questions"))
{
Console.WriteLine("Loading module " + Path.GetFileName(d));
moduleLoader.LoadModule(new BotGame(acl, Path.GetFileName(d), d, false, imagesPath, 2));
}
}
catch (System.Exception ex)
{
Console.WriteLine("There was an issue loading the module: " + ex.Message);
return;
}
Console.WriteLine("Starting Telegram bot listener...");
new TelegramBot(tgToken, acl, dataPath + "/motd.txt", moduleLoader.Modules);
// worst way ever to keep the main thread running, I know
while (true)
Thread.Sleep(10000);

16
Bot/SoUnBot.csproj Normal file
View file

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Telegram.Bot" Version="17.0.0" />
<PackageReference Include="Telegram.Bot.Extensions.Polling" Version="1.0.0" />
</ItemGroup>
</Project>

199
Bot/Telegram/TelegramBot.cs Normal file
View file

@ -0,0 +1,199 @@
using SoUnBot.AccessControl;
using SoUnBot.ModuleLoader;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
namespace SoUnBot.Telegram
{
internal class TelegramBot
{
private AccessManager _accessManager;
private string _moth_path;
private Dictionary<string, IModule> _modules;
public TelegramBotClient BotClient { get; private set; }
private Dictionary<long, IModule> _usersContext;
public TelegramBot(string token, AccessManager accessManager, string motd_path, Dictionary<string, IModule> modules)
{
_accessManager = accessManager;
_moth_path = motd_path;
_modules = modules;
_usersContext = new Dictionary<long, IModule>();
BotClient = new TelegramBotClient(token);
using var cts = new CancellationTokenSource();
// StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { } // receive all update types
};
BotClient.StartReceiving(
HandleUpdateAsync,
HandleErrorAsync,
receiverOptions,
cancellationToken: cts.Token);
GetMe();
}
private async void GetMe()
{
var me = await BotClient.GetMeAsync();
Console.WriteLine($"Start listening for @{me.Username}");
}
async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
try
{
long chatId;
if (update.Type == UpdateType.CallbackQuery)
{
chatId = update.CallbackQuery.From.Id;
if (update.CallbackQuery.Message.Text.StartsWith("ACM: ") && update.CallbackQuery.Data.Contains("Grant"))
{
long uid = int.Parse(update.CallbackQuery.Message.Text.Substring(5).Split('\n')[0]);
string perm = update.CallbackQuery.Message.Text.Split("Ha richiesto l'accesso a: ")[1];
_accessManager.GrantPermission(uid, perm);
await botClient.AnswerCallbackQueryAsync(
update.CallbackQuery.Id,
"Successo!"
);
await botClient.SendTextMessageAsync(
uid,
"✅ Congratulazioni! Hai ottenuto l'accesso a: " + perm
);
return;
}
if (update.CallbackQuery.Message.Text.StartsWith("ACM") && update.CallbackQuery.Data.Contains("🔆 Richiedi accesso"))
{
string perm = update.CallbackQuery.Message.Text.Split('`')[1];
_accessManager.AskPermission(update.CallbackQuery.From, perm, botClient);
await botClient.AnswerCallbackQueryAsync(
update.CallbackQuery.Id,
"Richiesta effettuata"
);
await botClient.EditMessageTextAsync(
update.CallbackQuery.From.Id,
update.CallbackQuery.Message.MessageId,
update.CallbackQuery.Message.Text,
replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData("Richiesto 〽️"))
);
return;
}
if (update.CallbackQuery.Message.Text.StartsWith("ACM")) {
return;
}
}
if (update.Type != UpdateType.Message) // this is temp
return;
if (update.Message!.Type != MessageType.Text)
return;
chatId = update.Message.Chat.Id;
if (update.Type == UpdateType.Message && update.Message!.Type == MessageType.Text && update.Message.Text.StartsWith("/spam"))
{
if (!_accessManager.CheckPermission(update.Message.From, "global.spam", botClient)) return;
await botClient.SendTextMessageAsync(
chatId: chatId,
text: "Invio annuncio in corso...");
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
SendToEveryone(botClient, chatId, update.Message.Text.Substring(6));
}).Start();
return;
}
if (update.Type == UpdateType.Message && update.Message!.Type == MessageType.Text && update.Message.Text == "/leave")
{
_usersContext.Remove(chatId);
}
if (_usersContext.ContainsKey(chatId))
{
_usersContext[chatId].ProcessUpdate(botClient, update, cancellationToken);
return;
}
if (update.Type == UpdateType.Message && update.Message!.Type == MessageType.Text)
{
var msg = update.Message.Text.StartsWith("/") ? update.Message.Text.Substring(1) : update.Message.Text;
if (_modules.ContainsKey(msg))
{
_usersContext.Add(chatId, _modules[msg]);
_modules[msg].ProcessUpdate(botClient, update, cancellationToken);
return;
}
}
string validModules = _modules.Keys.Select(i => "/" + i).Aggregate((a, b) => a + "\n" + b);
var motd = System.IO.File.ReadAllText(_moth_path);
// Echo received message text
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: motd);
}
catch(Exception e)
{
Console.WriteLine("Error handling the update: " + e.Message);
}
}
async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
if (exception is ApiRequestException apiRequestException)
{
await botClient.SendTextMessageAsync(_accessManager.AdminId, apiRequestException.ToString());
}
// Restart the bot (otherwise it would become an amoeba)
using var cts = new CancellationTokenSource();
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { }
};
BotClient.StartReceiving(
HandleUpdateAsync,
HandleErrorAsync,
receiverOptions,
cancellationToken: cts.Token);
}
private async void SendToEveryone(ITelegramBotClient botClient, long chatId, string text)
{
foreach (long user in _accessManager.Users())
{
try
{
Console.WriteLine("Sto spammando a" + user.ToString());
await botClient.SendTextMessageAsync(
chatId: user,
text: text
);
await Task.Delay(100);
}
catch
{
Console.WriteLine("Ho fallito");
}
}
await botClient.SendTextMessageAsync(
chatId: chatId,
text: "✅ Annunciato a tutti!");
}
}
}

5
Bot/run.sh Normal file
View file

@ -0,0 +1,5 @@
git pull origin main
docker stop SOBOT
docker rm SOBOT
docker build -t sobot3 .
docker run -d --name='SOBOT' --net='bridge' -e TZ="Europe/Berlin" -e HOST_OS="Unraid" -e HOST_HOSTNAME="Tower" -e HOST_CONTAINERNAME="SOBOT" -l net.unraid.docker.managed=dockerman -p 8001:8001 -v '/mnt/user/SSD/sobot_data':'/App/ACL':'rw' 'sobot3:latest'