C#:
using Newtonsoft.Json;
using Oxide.Core.Libraries.Covalence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Oxide.Plugins
{
[Info("NameRewards", "Suslik", "1.1.1", ResourceId = 197)]
[Description("Gives the players rewards if their nickname contains desired word")]
class NameRewards : CovalencePlugin
{
#region Vars
private PluginConfig _config;
#endregion
#region Config
private class PluginConfig
{
[JsonProperty("Варианты текста, который должен быть в нике")]
public List<string> Texts = new List<string>();
[JsonProperty("Использовать регулярные выражения")]
public bool UseRegex;
[JsonProperty("Не учитывать регистр")]
public bool IgnoreCase;
[JsonProperty("Оповещать о получении привилегий/необходимости добавления текста")]
public bool Notify;
[JsonProperty("Формат сообщений в чате")]
public string ChatFormat;
[JsonProperty("Привилегии, которые будут выданы")]
public List<string> Permissions;
[JsonProperty("Группы, в которые игрок будет добавлен")]
public List<string> Groups;
public struct Message
{
public string LangKey;
public object[] Args;
public Message(string langKey, params object[] args)
{
LangKey = langKey;
Args = args;
}
}
public Message AvailableOptions()
{
switch (Texts.Count)
{
case 0:
return default(Message);
case 1:
return new Message("Not", Texts[0]);
default:
var result = $"\"{Texts[0]}\"";
for (var i = 1; i < Texts.Count-1; i++)
{
result += $", \"{Texts[i]}\"";
}
return new Message("NotMulti", result, $"\"{Texts[Texts.Count-1]}\"");
}
}
[JsonIgnore]
private Func<string, string, bool> _check;
[JsonIgnore]
private Func<string, string, bool> Check
{
get
{
if (_check != null)
return _check;
if (!UseRegex)
{
if (IgnoreCase)
_check = (x, y) => x.IndexOf(y, StringComparison.InvariantCultureIgnoreCase) != -1;
else
_check = (x, y) => x.Contains(y);
}
else
{
if (IgnoreCase)
_check = (x, y) => Regex.IsMatch(x, y, RegexOptions.IgnoreCase);
else
_check = Regex.IsMatch;
}
return _check;
}
}
#region Default Config
public static PluginConfig DefaultConfig => new PluginConfig
{
Texts = new List<string>{"Лучший сервер!"},
Notify = true,
IgnoreCase = true,
UseRegex = false,
ChatFormat = "[#green][NameRewards][/#] {0}",
Permissions = new List<string> { "kits.nickname", "nteleportation.nickname" },
Groups = new List<string> { "nickname" }
};
#endregion
public bool IsMatch(string text, out string found)
{
found = null;
foreach (var pattern in Texts)
{
if(!Check(text,pattern))
continue;
found = pattern;
return true;
}
return false;
}
}
#endregion
#region Config init
private bool CheckConfig()
{
var res = false;
//==version < 1.1.0==
var oldText = Config.Get("Текст, который должен быть в нике") as string;
if (oldText != null)
{
PrintWarning("Config file updated: multiple texts support, regex and case-insensitive switches added");
Config.Clear();
_config.UseRegex = false;
_config.IgnoreCase = true;
_config.Texts.Add(oldText);
res = true;
}
return res;
}
protected override void LoadDefaultConfig()
{
PrintWarning("Благодарим за приобретение плагина на сайте RustPlugin.ru.Если вы приобрели этот плагин на другом ресурсе знайте - это лишает вас гарантированных обновлений!");
_config = PluginConfig.DefaultConfig;
}
protected override void LoadConfig()
{
base.LoadConfig();
_config = Config.ReadObject<PluginConfig>();
if (CheckConfig())
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
#endregion
#region Localization
private void SendResponse(IPlayer player, string langKey, params object[] args)
{
var format = GetMsg(langKey, player.Id);
format = args.Length != 0 ? string.Format(format, args) : format;
player.Reply(string.Format(_config.ChatFormat,format));
}
private string GetMsg(string key, string playerid) => lang.GetMessage(key, this, playerid);
private string GetMsg(string key, ulong playerid = 0) =>
GetMsg(key, playerid == 0 ? null : playerid.ToString());
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["Granted"] = "You have \"{0}\" in your nickname! Enjoy your gifts!",
["Not"] = "You don't have \"{0}\" in your nickname!\nIf you want to get free gifts - add it to the nickanme and reconnect to the server!",
["NotMulti"] = "You don't have {0} or {1} in your nickname!\nIf you want to get free gifts - add it to the nickanme and reconnect to the server!"
}, this);
lang.RegisterMessages(new Dictionary<string, string>
{
["Granted"] = "У вас в нике есть текст \"{0}\"!\nНаслаждайтесь вашими привилегиями!",
["Not"] = "У вас в нике нет текста \"{0}\"!\nЕсли вы хотите получить подарки - добавьте этот текст к нику и перезайдите на сервер!",
["NotMulti"] = "У вас в нике нет текста {0} или {1}!\nЕсли вы хотите получить подарки - добавьте этот текст к нику и перезайдите на сервер!"
}, this, "ru");
}
#endregion
private void Init()
{
foreach (var player in covalence.Players.Connected)
{
OnUserConnected(player);
}
}
private void OnUserConnected(IPlayer player)
{
string found;
if (_config.IsMatch(player.Name, out found))
{
Grant(player);
if(_config.Notify)
SendResponse(player,"Granted",found);
return;
}
Revoke(player);
if (_config.Notify)
{
var message = _config.AvailableOptions();
if (string.IsNullOrEmpty(message.LangKey))
return;
SendResponse(player,message.LangKey,message.Args);
}
}
#region Grant|Revoke methods
private void Grant(IPlayer player)
{
foreach(var perm in _config.Permissions)
{
if (!permission.PermissionExists(perm))
{
PrintWarning($"Permission \"{perm}\" doesn't exists and wasn't granted to the player \"{player.Name}\"");
continue;
}
player.GrantPermission(perm);
}
foreach(var group in _config.Groups)
{
if (!permission.GroupExists(group))
{
PrintWarning($"Group \"{group}\" doesn't exists and the player \"{player.Name}\" wasn't added to it.");
continue;
}
player.AddToGroup(group);
}
}
private void Revoke(IPlayer player)
{
foreach (var perm in _config.Permissions)
{
if (!permission.PermissionExists(perm))
{
PrintWarning($"Permission \"{perm}\" doesn't exists and wasn't removed form the player \"{player.Name}\"");
continue;
}
player.RevokePermission(perm);
}
foreach (var group in _config.Groups)
{
if (!permission.GroupExists(group))
{
PrintWarning($"Group \"{group}\" doesn't exists and the player \"{player.Name}\" wasn't removed from it.");
continue;
}
player.RemoveFromGroup(group);
}
}
#endregion
}
}