Иконка ресурса

FREE VKBot : 1.6 1.6

Нет прав для скачивания
C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Oxide.Core;
using Oxide.Core.Configuration;
using Oxide.Game.Rust.Cui;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins {
    [Info("VKBot", "SkiTles", "1.6")]
    class VKBot : RustPlugin {
        //Данный плагин принадлежит группе vk.com/vkbotrust
        //Данный плагин предоставляется в существующей форме,
        //"как есть", без каких бы то ни было явных или
        //подразумеваемых гарантий, разработчик не несет
        //ответственность в случае его неправильного использования.#region Variables
        private System.Random random = new System.Random();
        private string opc;
        private string stw;
        private string sts;
        private string str;
        private string stb;
        private string ste;
        private string wd;
        private string su;
        private string msg;
        private string cone;
        private string slprs;
        private string mapfile;
        private bool NewWipe = false;
        JsonSerializerSettings jsonsettings;
        private bool OxideUpdateNotice = false;
        private Dictionary<ulong, ulong> PlayersCheckList = new Dictionary<ulong, ulong>();
        private int serverOxideVersion;
        private List<string> allowedentity = new List<string>() {
            "door", "wall.window.bars.metal", "wall.window.bars.toptier", "wall.external", "gates.external.high", "floor.ladder", "embrasure", "floor.grill", "wall.frame.fence", "wall.frame.cell"
        }
        ;
        private List<ulong> BDayPlayers = new List<ulong>();
#endregion
#region Config
        private ConfigData config;
        private class ConfigData {
            [JsonProperty(PropertyName = "Ключи VK API, ID группы")]
            public VKAPITokens VKAPIT {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Настройки оповещений администраторов")]
            public AdminNotify AdmNotify {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Настройки статуса")]
            public StatusSettings StatusStg {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Оповещения при вайпе")]
            public WipeSettings WipeStg {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Награда за вступление в группу")]
            public GroupGifts GrGifts {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Награда для именинников")]
            public BDayGiftSet BDayGift {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Настройки текста в уведомлениях в чат")]
            public TextSettings TxtSet {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Поддержка нескольких серверов")]
            public MultipleServersSettings MltServSet {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Проверка игроков на читы")]
            public PlayersCheckingSettings PlChkSet {
                get;
                set;
            }
            [JsonProperty(PropertyName = "Топ игроки вайпа и промо")]
            public TopWPlPromoSet TopWPlayersPromo {
                get;
                set;
            }
            public class VKAPITokens {
                [JsonProperty(PropertyName = "VK Token группы (для сообщений)")]
                [DefaultValue("Заполните эти поля, и выполните команду o.reload VKBot")]
                public string VKToken {
                    get;
                    set;
                }
                = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "VK Token приложения (для записей на стене и статуса)")]
                [DefaultValue("Заполните эти поля, и выполните команду o.reload VKBot")]
                public string VKTokenApp {
                    get;
                    set;
                }
                = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "VKID группы")]
                [DefaultValue("Заполните эти поля, и выполните команду o.reload VKBot")]
                public string GroupID {
                    get;
                    set;
                }
                = "Заполните эти поля, и выполните команду o.reload VKBot";
            }
            public class AdminNotify {
                [JsonProperty(PropertyName = "VkID администраторов (пример /11111, 22222/)")]
                [DefaultValue("Заполните эти поля, и выполните команду o.reload VKBot")]
                public string VkID {
                    get;
                    set;
                }
                = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "Включить отправку сообщений администратору командой /report ?")]
                [DefaultValue(true)]
                public bool SendReports {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Предупреждение о злоупотреблении функцией репортов")]
                [DefaultValue("Наличие в тексте нецензурных выражений, оскорблений администрации или игроков сервера, а так же большое количество безсмысленных сообщений приведет к бану!")]
                public string ReportsNotify {
                    get;
                    set;
                }
                = "Наличие в тексте нецензурных выражений, оскорблений администрации или игроков сервера, а так же большое количество безсмысленных сообщений приведет к бану!";
                [JsonProperty(PropertyName = "Отправлять сообщение администратору о бане игрока?")]
                [DefaultValue(true)]
                public bool UserBannedMsg {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Отправлять сообщение администратору о выходе нового обновления Oxide?")]
                [DefaultValue(true)]
                public bool OxideNewVersionMsg {
                    get;
                    set;
                }
                = true;
            }
            public class StatusSettings {
                [JsonProperty(PropertyName = "Обновлять статус в группе? Если стоит /false/ статистика собираться не будет")]
                [DefaultValue(true)]
                public bool UpdateStatus {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Вид статуса (1 - текущий сервер, 2 - список серверов, необходим Rust:IO на каждом сервере)")]
                [DefaultValue(1)]
                public int StatusSet {
                    get;
                    set;
                }
                = 1;
                [JsonProperty(PropertyName = "Онлайн в статусе вида '125/200'")]
                [DefaultValue(false)]
                public bool OnlWmaxslots {
                    get;
                    set;
                }
                = false;
                [JsonProperty(PropertyName = "Таймер обновления статуса (минуты)")]
                [DefaultValue(30)]
                public int UpdateTimer {
                    get;
                    set;
                }
                = 30;
                [JsonProperty(PropertyName = "Формат статуса")]
                [DefaultValue("{usertext}.Сервер вайпнут: {wipedate}.Онлайн игроков: {onlinecounter}.Спящих: {sleepers}.Добыто дерева: {woodcounter}.Добыто серы: {sulfurecounter}.Выпущено ракет: {rocketscounter}.Использовано взрывчатки: {explosivecounter}.Создано чертежей: {blueprintsconter}.{connect}")]
                public string StatusText {
                    get;
                    set;
                }
                = "{usertext}.Сервер вайпнут: {wipedate}.Онлайн игроков: {onlinecounter}.Добыто дерева: {woodcounter}.Добыто серы: {sulfurecounter}.Выпущено ракет: {rocketscounter}.Использовано взрывчатки: {explosivecounter}.Создано чертежей: {blueprintsconter}.{connect}";
                [JsonProperty(PropertyName = "Список счетчиков, которые будут отображаться в виде emoji")]
                [DefaultValue("onlinecounter, rocketscounter, blueprintsconter, explosivecounter, wipedate")]
                public string EmojiCounterList {
                    get;
                    set;
                }
                = "onlinecounter, rocketscounter, blueprintsconter, explosivecounter, wipedate";
                [JsonProperty(PropertyName = "Ссылка на коннект сервера вида /connect 111.111.111.11:11111/")]
                [DefaultValue("connect 111.111.111.11:11111")]
                public string connecturl {
                    get;
                    set;
                }
                = "connect 111.111.111.11:11111";
                [JsonProperty(PropertyName = "Текст для статуса")]
                [DefaultValue("Сервер 1")]
                public string StatusUT {
                    get;
                    set;
                }
                = "Сервер 1";
            }
            public class WipeSettings {
                [JsonProperty(PropertyName = "Отправлять пост в группу после вайпа?")]
                [DefaultValue(false)]
                public bool WPostB {
                    get;
                    set;
                }
                = false;
                [JsonProperty(PropertyName = "Текст поста о вайпе")]
                [DefaultValue("Заполните эти поля, и выполните команду o.reload VKBot")]
                public string WPostMsg {
                    get;
                    set;
                }
                = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "Добавить изображение к посту о вайпе?")]
                [DefaultValue(false)]
                public bool WPostAttB {
                    get;
                    set;
                }
                = false;
                [JsonProperty(PropertyName = "Ссылка на изображение к посту о вайпе вида 'photo-1_265827614' (изображение должно быть в альбоме группы)")]
                [DefaultValue("photo-1_265827614")]
                public string WPostAtt {
                    get;
                    set;
                }
                = "photo-1_265827614";
                [JsonProperty(PropertyName = "Отправлять сообщение администратору о вайпе?")]
                [DefaultValue(true)]
                public bool WPostMsgAdmin {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Отправлять игрокам сообщение о вайпе автоматически?")]
                [DefaultValue(false)]
                public bool WMsgPlayers {
                    get;
                    set;
                }
                = false;
                [JsonProperty(PropertyName = "Текст сообщения игрокам о вайпе (сообщение отправляется только тем кто подписался командой /vk wipealerts)")]
                [DefaultValue("Сервер вайпнут! Залетай скорее!")]
                public string WMsgText {
                    get;
                    set;
                }
                = "Сервер вайпнут! Залетай скорее!";
                [JsonProperty(PropertyName = "Игнорировать команду /vk wipealerts? (если включено, сообщение о вайпе будет отправляться всем)")]
                [DefaultValue(false)]
                public bool WCMDIgnore {
                    get;
                    set;
                }
                = false;
            }
            public class GroupGifts {
                [JsonProperty(PropertyName = "Выдавать подарок игроку за вступление в группу ВК?")]
                [DefaultValue(true)]
                public bool VKGroupGifts {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Подарки за вступление в группу (shortname предмета, количество)")]
                [DefaultValue(null)]
                public Dictionary<string, object> VKGroupGiftList {
                    get;
                    set;
                }
                = new Dictionary<string, object> {
                    {
                        "supply.signal", 1
                    }
                    , {
                        "pookie.bear", 2
                    }
                }
                ;
                [JsonProperty(PropertyName = "Ссылка на группу ВК")]
                [DefaultValue("vk.com/1234")]
                public string VKGroupUrl {
                    get;
                    set;
                }
                = "vk.com/1234";
                [JsonProperty(PropertyName = "Оповещения в общий чат о получении награды")]
                [DefaultValue(true)]
                public bool GiftsBool {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Включить оповещения для игроков не получивших награду за вступление в группу?")]
                [DefaultValue(true)]
                public bool VKGGNotify {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Интервал оповещений для игроков не получивших награду за вступление в группу (в минутах)")]
                [DefaultValue(30)]
                public int VKGGTimer {
                    get;
                    set;
                }
                = 30;
                [JsonProperty(PropertyName = "Выдавать награду каждый вайп?")]
                [DefaultValue(true)]
                public bool GiftsWipe {
                    get;
                    set;
                }
                = true;
            }
            public class BDayGiftSet {
                [JsonProperty(PropertyName = "Включить награду для именинников?")]
                [DefaultValue(true)]
                public bool BDayEnabled {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Группа для именинников")]
                [DefaultValue("bdaygroup")]
                public string BDayGroup {
                    get;
                    set;
                }
                = "bdaygroup";
                [JsonProperty(PropertyName = "Текст поздравления")]
                [DefaultValue("<size=17><color=#990404>Администрация сервера поздравляет вас с днем рождения! В качестве подарка мы добавили вас в группу с рейтами x4 и китом bday!</color></size>")]
                public string BDayText {
                    get;
                    set;
                }
                = "<size=17><color=#990404>Администрация сервера поздравляет вас с днем рождения! В качестве подарка мы добавили вас в группу с рейтами x4 и китом bday!</color></size>";
                [JsonProperty(PropertyName = "Оповещения в общий чат о имениннках")]
                [DefaultValue(false)]
                public bool BDayNotify {
                    get;
                    set;
                }
                = false;
            }
            public class TextSettings {
                [JsonProperty(PropertyName = "Размер текста")]
                [DefaultValue("17")]
                public string TxtSize {
                    get;
                    set;
                }
                = "17";
                [JsonProperty(PropertyName = "Цвет выделенного текста")]
                [DefaultValue("#990404")]
                public string TxtColor {
                    get;
                    set;
                }
                = "#990404";
            }
            public class MultipleServersSettings {
                [JsonProperty(PropertyName = "Включить поддержку несколько серверов?")]
                [DefaultValue(false)]
                public bool MSSEnable {
                    get;
                    set;
                }
                = false;
                [JsonProperty(PropertyName = "Номер сервера")]
                [DefaultValue(1)]
                public int ServerNumber {
                    get;
                    set;
                }
                = 1;
                [JsonProperty(PropertyName = "Сервер 1 IP:PORT (пример: 111.111.111.111:28015)")]
                [DefaultValue("none")]
                public string Server1ip {
                    get;
                    set;
                }
                = "none";
                [JsonProperty(PropertyName = "Сервер 2 IP:PORT (пример: 111.111.111.111:28015)")]
                [DefaultValue("none")]
                public string Server2ip {
                    get;
                    set;
                }
                = "none";
                [JsonProperty(PropertyName = "Сервер 3 IP:PORT (пример: 111.111.111.111:28015)")]
                [DefaultValue("none")]
                public string Server3ip {
                    get;
                    set;
                }
                = "none";
                [JsonProperty(PropertyName = "Сервер 4 IP:PORT (пример: 111.111.111.111:28015)")]
                [DefaultValue("none")]
                public string Server4ip {
                    get;
                    set;
                }
                = "none";
                [JsonProperty(PropertyName = "Сервер 5 IP:PORT (пример: 111.111.111.111:28015)")]
                [DefaultValue("none")]
                public string Server5ip {
                    get;
                    set;
                }
                = "none";
                [JsonProperty(PropertyName = "Онлайн в emoji?")]
                [DefaultValue(true)]
                public bool EmojiStatus {
                    get;
                    set;
                }
                = true;
            }
            public class PlayersCheckingSettings {
                [JsonProperty(PropertyName = "Текст уведомления")]
                [DefaultValue("<color=#990404>Модератор вызвал вас на проверку.</color> \nНапишите свой скайп с помощью команды <color=#990404>/skype <НИК в СКАЙПЕ>.</color>\nЕсли вы покините сервер, Вы будете забанены на нашем проекте серверов.")]
                public string PlCheckText {
                    get;
                    set;
                }
                = "<color=#990404>Модератор вызвал вас на проверку.</color> \nНапишите свой скайп с помощью команды <color=#990404>/skype <НИК в СКАЙПЕ>.</color>\nЕсли вы покините сервер, Вы будете забанены на нашем проекте серверов.";
                [JsonProperty(PropertyName = "Размер текста")]
                [DefaultValue(17)]
                public int PlCheckSize {
                    get;
                    set;
                }
                = 17;
                [JsonProperty(PropertyName = "Привилегия для команд /alert и /unalert")]
                [DefaultValue("vkbot.checkplayers")]
                public string PlCheckPerm {
                    get;
                    set;
                }
                = "vkbot.checkplayers";
                [JsonProperty(PropertyName = "Позиция GUI AnchorMin (дефолт 0 0.826)")]
                [DefaultValue("0 0.826")]
                public string GUIAnchorMin {
                    get;
                    set;
                }
                = "0 0.826";
                [JsonProperty(PropertyName = "Позиция GUI AnchorMax (дефолт 1 0.965)")]
                [DefaultValue("1 0.965")]
                public string GUIAnchorMax {
                    get;
                    set;
                }
                = "1 0.965";
            }
            public class TopWPlPromoSet {
                [JsonProperty(PropertyName = "Включить топ игроков вайпа")]
                [DefaultValue(true)]
                public bool TopWPlEnabled {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Включить отправку промо кодов за топ?")]
                [DefaultValue(false)]
                public bool TopPlPromoGift {
                    get;
                    set;
                }
                = false;
                [JsonProperty(PropertyName = "Пост на стене группы о топ игроках вайпа")]
                [DefaultValue(true)]
                public bool TopPlPost {
                    get;
                    set;
                }
                = true;
                [JsonProperty(PropertyName = "Промо для топ рэйдера")]
                [DefaultValue("topraider")]
                public string TopRaiderPromo {
                    get;
                    set;
                }
                = "topraider";
                [JsonProperty(PropertyName = "Промо для топ килера")]
                [DefaultValue("topkiller")]
                public string TopKillerPromo {
                    get;
                    set;
                }
                = "topkiller";
                [JsonProperty(PropertyName = "Промо для топ фармера")]
                [DefaultValue("topfarmer")]
                public string TopFarmerPromo {
                    get;
                    set;
                }
                = "topfarmer";
                [JsonProperty(PropertyName = "Ссылка на донат магазин")]
                [DefaultValue("server.gamestores.ru")]
                public string StoreUrl {
                    get;
                    set;
                }
                = "server.gamestores.ru";
                [JsonProperty(PropertyName = "Автоматическая генерация промокодов после вайпа")]
                [DefaultValue(false)]
                public bool GenRandomPromo {
                    get;
                    set;
                }
                = false;
            }
        }
        private void LoadVariables() {
            Config.Settings.DefaultValueHandling = DefaultValueHandling.Populate;
            config = Config.ReadObject<ConfigData>();
            Config.WriteObject(config, true);
        }
        protected override void LoadDefaultConfig() {
            var configData = new ConfigData {
                VKAPIT = new ConfigData.VKAPITokens(), AdmNotify = new ConfigData.AdminNotify(), StatusStg = new ConfigData.StatusSettings(), WipeStg = new ConfigData.WipeSettings(), GrGifts = new ConfigData.GroupGifts(), BDayGift = new ConfigData.BDayGiftSet(), TxtSet = new ConfigData.TextSettings(), MltServSet = new ConfigData.MultipleServersSettings(), PlChkSet = new ConfigData.PlayersCheckingSettings(), TopWPlayersPromo = new ConfigData.TopWPlPromoSet()
            }
            ;
            Config.WriteObject(configData, true);
            PrintWarning("Поддержи разработчика! Вступи в группу vk.com/vkbotrust");
        }
#endregion
#region Datastorage
        class DataStorageStats {
            public int WoodGath;
            public int SulfureGath;
            public int Rockets;
            public int Blueprints;
            public int Explosive;
            public DataStorageStats() {
            }
        }
        class DataStorageUsers {
            public Dictionary<ulong, VKUDATA> VKUsersData = new Dictionary<ulong, VKUDATA>();
            public DataStorageUsers() {
            }
        }
        class VKUDATA {
            public ulong UserID;
            public string Name;
            public string VkID;
            public int ConfirmCode;
            public bool Confirmed;
            public bool GiftRecived;
            public string LastRaidNotice;
            public bool WipeMsg;
            public string Bdate;
            public int Raids;
            public int Kills;
            public int Farm;
        }
        DataStorageStats statdata;
        DataStorageUsers usersdata;
        private DynamicConfigFile VKBData;
        private DynamicConfigFile StatData;
        void LoadData() {
            try {
                statdata = Interface.GetMod().DataFileSystem.ReadObject<DataStorageStats>("VKBot");
                usersdata = Interface.GetMod().DataFileSystem.ReadObject<DataStorageUsers>("VKBotUsers");
            }
            catch {
                statdata = new DataStorageStats();
                usersdata = new DataStorageUsers();
            }
        }
#endregion
#region Oxidehooks
        void OnServerInitialized() {
            LoadVariables();
            VKBData = Interface.Oxide.DataFileSystem.GetFile("VKBotUsers");
            StatData = Interface.Oxide.DataFileSystem.GetFile("VKBot");
            LoadData();
            if (!permission.PermissionExists(config.PlChkSet.PlCheckPerm)) permission.RegisterPermission(config.PlChkSet.PlCheckPerm, this);
            if (NewWipe) {
                WipeFunctions(mapfile);
            }
            if (config.StatusStg.UpdateStatus) {
                if (config.StatusStg.StatusSet == 1) {
                    timer.Repeat(config.StatusStg.UpdateTimer * 60, 0, Update1ServerStatus);
                }
                if (config.StatusStg.StatusSet == 2) {
                    timer.Repeat(config.StatusStg.UpdateTimer * 60, 0, UpdateMultiServerStatus);
                }
            }
            if (config.GrGifts.VKGGNotify) {
                timer.Repeat(config.GrGifts.VKGGTimer * 60, 0, GiftNotifier);
            }
            if (config.AdmNotify.OxideNewVersionMsg) {
                CheckOxideCommits();
                timer.Repeat(3600, 0, CheckOxideCommits);
            }
        }
        void OnServerSave() {
            if (config.TopWPlayersPromo.TopWPlEnabled) {
                VKBData.WriteObject(usersdata);
            }
        }
        private void Init() {
            cmd.AddChatCommand("report", this, "SendReport");
            cmd.AddChatCommand("vk", this, "VKcommand");
            cmd.AddConsoleCommand("updatestatus", this, "UStatus");
            cmd.AddConsoleCommand("sendmsgadmin", this, "MsgAdmin");
            cmd.AddConsoleCommand("wipealerts", this, "WipeAlerts");
            cmd.AddChatCommand("alert", this, "StartCheckPlayer");
            cmd.AddChatCommand("unalert", this, "StopCheckPlayer");
            cmd.AddChatCommand("skype", this, "SkypeSending");
            cmd.AddConsoleCommand("userinfo", this, "GetUserInfo");
            jsonsettings = new JsonSerializerSettings();
            jsonsettings.Converters.Add(new KeyValuePairConverter());
            serverOxideVersion = Convert.ToInt32(Manager.GetPlugin("RustCore").Version.Patch);
        }
        void Unload() {
            if (config.StatusStg.UpdateStatus) {
                StatData.WriteObject(statdata);
            }
            if (config.TopWPlayersPromo.TopWPlEnabled) {
                VKBData.WriteObject(usersdata);
            }
            if (PlayersCheckList.Count == 0) return;
            for (int i = 0; i < PlayersCheckList.Count; i++) {
                var playerid = PlayersCheckList.ElementAt(i).Value;
                var player = BasePlayer.FindByID(playerid);
                if (player != null) {
                    StopGui(player);
                }
            }
            PlayersCheckList.Clear();
            if (config.BDayGift.BDayEnabled && BDayPlayers.Count > 0) {
                foreach (var id in BDayPlayers) {
                    permission.RemoveUserGroup(id.ToString(), config.BDayGift.BDayGroup);
                    Puts($"Список игроков bday очищен");
                    //debug
                }
                BDayPlayers.Clear();
            }
        }
        void OnNewSave(string filename) {
            NewWipe = true;
            mapfile = filename;
        }
        void OnPlayerInit(BasePlayer player) {
            if (usersdata.VKUsersData.ContainsKey(player.userID)) {
                if (usersdata.VKUsersData[player.userID].Name != player.displayName) {
                    usersdata.VKUsersData[player.userID].Name = player.displayName;
                    VKBData.WriteObject(usersdata);
                }
                if (usersdata.VKUsersData[player.userID].Bdate == null) {
                    AddBdate(player);
                }
            }
        }
        void OnPlayerSleepEnded(BasePlayer player) {
            if (!usersdata.VKUsersData.ContainsKey(player.userID)) return;
            if (config.BDayGift.BDayEnabled && permission.GroupExists(config.BDayGift.BDayGroup)) {
                if (permission.UserHasGroup(player.userID.ToString(), config.BDayGift.BDayGroup)) return;
                var today = DateTime.Now.ToString("d.M", CultureInfo.InvariantCulture);
                var bday = usersdata.VKUsersData[player.userID].Bdate;
                if (bday == null || bday == "noinfo") return;
                string[] array = bday.Split('.');
                if (array.Length == 3) {
                    bday = bday.Remove(bday.Length - 5, 5);
                }
                if (bday == today) {
                    permission.AddUserGroup(player.userID.ToString(), config.BDayGift.BDayGroup);
                    PrintToChat(player, String.Format(config.BDayGift.BDayText));
                    Log("bday", $"Игрок {player.displayName} добавлен в группу {config.BDayGift.BDayGroup}");
                    BDayPlayers.Add(player.userID);
                    if (config.BDayGift.BDayNotify) {
                        Server.Broadcast(String.Format($"<size={config.TxtSet.TxtSize}>Администрация сервера поздравляет игрока <color={config.TxtSet.TxtColor}>{player.displayName}</color> с Днем Рождения!</size>"));
                    }
                }
            }
        }
        void OnPlayerDisconnected(BasePlayer player, string reason) {
            if (PlayersCheckList.Count > 0 && PlayersCheckList.ContainsValue(player.userID)) {
                CuiHelper.DestroyUi(player, "AlertGUI");
                BasePlayer moder = null;
                for (int i = 0; i < PlayersCheckList.Count; i++) {
                    if (PlayersCheckList.ElementAt(i).Value == player.userID) {
                        ulong moderid = PlayersCheckList.ElementAt(i).Key;
                        moder = BasePlayer.FindByID(moderid);
                        PlayersCheckList.Remove(moderid);
                        if (moder != null) {
                            PrintToChat(moder, $"Игрок вызванный на проверку покинул сервер.Причина: {reason}");
                        }
                    }
                }
            }
            if (PlayersCheckList.Count > 0 && PlayersCheckList.ContainsKey(player.userID)) {
                ulong targetid;
                PlayersCheckList.TryGetValue(player.userID, out targetid);
                BasePlayer target = BasePlayer.FindByID(targetid);
                if (target != null) {
                    CuiHelper.DestroyUi(target, "AlertGUI");
                    PrintToChat(target, $"Модератор отключился от сервера, ожидайте следующей проверки.");
                }
                PlayersCheckList.Remove(player.userID);
            }
            if (config.BDayGift.BDayEnabled && permission.GroupExists(config.BDayGift.BDayGroup)) {
                if (BDayPlayers.Contains(player.userID)) {
                    permission.RemoveUserGroup(player.userID.ToString(), config.BDayGift.BDayGroup);
                    BDayPlayers.Remove(player.userID);
                    Log("bday", $"Игрок {player.displayName} удален из группы {config.BDayGift.BDayGroup}");
                }
            }
        }
#endregion
#region Stats
        private void OnItemResearch(ResearchTable table, Item targetItem, BasePlayer player) {
            if (config.StatusStg.UpdateStatus) {
                statdata.Blueprints++;
            }
        }
        private void OnDispenserGather(ResourceDispenser dispenser, BaseEntity entity, Item item) {
            if (config.StatusStg.UpdateStatus) {
                if (item.info.shortname == "wood") {
                    statdata.WoodGath = statdata.WoodGath + item.amount;
                }
                if (item.info.shortname == "sulfur.ore") {
                    statdata.SulfureGath = statdata.SulfureGath + item.amount;
                }
            }
            if (config.TopWPlayersPromo.TopWPlEnabled) {
                BasePlayer player = entity.ToPlayer();
                if (player == null) return;
                if (usersdata.VKUsersData.ContainsKey(player.userID)) {
                    usersdata.VKUsersData[player.userID].Farm = usersdata.VKUsersData[player.userID].Farm + item.amount;
                }
            }
        }
        private void OnDispenserBonus(ResourceDispenser dispenser, BasePlayer player, Item item) {
            if (config.StatusStg.UpdateStatus && item.info.shortname == "sulfur.ore") {
                statdata.SulfureGath = statdata.SulfureGath + item.amount;
            }
            if (config.TopWPlayersPromo.TopWPlEnabled) {
                if (usersdata.VKUsersData.ContainsKey(player.userID)) {
                    usersdata.VKUsersData[player.userID].Farm = usersdata.VKUsersData[player.userID].Farm + item.amount;
                }
            }
        }
        private void OnCollectiblePickup(Item item, BasePlayer player) {
            if (config.StatusStg.UpdateStatus) {
                if (item.info.shortname == "wood") {
                    statdata.WoodGath = statdata.WoodGath + item.amount;
                }
                if (item.info.shortname == "sulfur.ore") {
                    statdata.SulfureGath = statdata.SulfureGath + item.amount;
                }
            }
            if (config.TopWPlayersPromo.TopWPlEnabled) {
                if (usersdata.VKUsersData.ContainsKey(player.userID)) {
                    usersdata.VKUsersData[player.userID].Farm = usersdata.VKUsersData[player.userID].Farm + item.amount;
                }
            }
        }
        private void OnRocketLaunched(BasePlayer player, BaseEntity entity) {
            if (config.StatusStg.UpdateStatus) {
                statdata.Rockets++;
            }
        }
        private void OnExplosiveThrown(BasePlayer player, BaseEntity entity) {
            if (config.StatusStg.UpdateStatus) {
                List<object> include = new List<object>() {
                    "explosive.satchel.deployed", "grenade.f1.deployed", "grenade.beancan.deployed", "explosive.timed.deployed"
                }
                ;
                if (include.Contains(entity.ShortPrefabName)) {
                    statdata.Explosive++;
                }
            }
        }
        void OnEntityDeath(BaseCombatEntity entity, HitInfo hitInfo) {
            if (config.TopWPlayersPromo.TopWPlEnabled) {
                if (entity.name.Contains("corpse")) return;
                if (hitInfo == null) return;
                var attacker = hitInfo.Initiator?.ToPlayer();
                if (attacker == null) return;
                if (entity is BasePlayer) {
                    CheckDeath(entity.ToPlayer(), hitInfo);
                }
                if (entity is BaseEntity) {
                    if (hitInfo.damageTypes.GetMajorityDamageType() != Rust.DamageType.Explosion && hitInfo.damageTypes.GetMajorityDamageType() != Rust.DamageType.Heat && hitInfo.damageTypes.GetMajorityDamageType() != Rust.DamageType.Bullet) return;
                    if (attacker.userID == entity.OwnerID) return;
                    BuildingBlock block = entity.GetComponent<BuildingBlock>();
                    if (block != null) {
                        if (block.currentGrade.gradeBase.type.ToString() == "Twigs" || block.currentGrade.gradeBase.type.ToString() == "Wood") {
                            return;
                        }
                    }
                    else {
                        bool ok = false;
                        foreach (var ent in allowedentity) {
                            if (entity.LookupPrefab().name.Contains(ent)) {
                                ok = true;
                            }
                        }
                        if (!ok) return;
                    }
                    if (entity.OwnerID == 0) return;
                    if (usersdata.VKUsersData.ContainsKey(attacker.userID)) {
                        usersdata.VKUsersData[attacker.userID].Raids++;
                    }
                }
            }
        }
        private void CheckDeath(BasePlayer player, HitInfo info) {
            if (info == null) return;
            var attacker = info.Initiator?.ToPlayer();
            if (attacker == null || attacker == player) return;
            if (!usersdata.VKUsersData.ContainsKey(attacker.userID)) return;
            if (!player.IsConnected) return;
            usersdata.VKUsersData[attacker.userID].Kills++;
        }
#endregion
#region Wipe
        private void WipeFunctions(string filename) {
            if (config.StatusStg.UpdateStatus) {
                statdata.Blueprints = 0;
                statdata.Rockets = 0;
                statdata.SulfureGath = 0;
                statdata.WoodGath = 0;
                statdata.Explosive = 0;
                StatData.WriteObject(statdata);
                NewWipe = false;
                if (config.StatusStg.StatusSet == 1) {
                    Update1ServerStatus();
                }
                if (config.StatusStg.StatusSet == 2) {
                    UpdateMultiServerStatus();
                }
            }
            if (config.WipeStg.WPostMsgAdmin) {
                string s = filename;
                string[] array = s.Split('/');
                int t = array.Length - 1;
                string savename = array[t];
                string[] mapname = savename.Split('.');
                string msg2 = null;
                if (config.MltServSet.MSSEnable) {
                    msg2 = $"[VKBot] Сервер {config.MltServSet.ServerNumber.ToString()} вайпнут.Установлена карта: {mapname[0]}.Размер: {mapname[1]}.Сид: {mapname[2]}";
                }
                else {
                    msg2 = $"[VKBot] Сервер вайпнут.Установлена карта: {mapname[0]}.Размер: {mapname[1]}.Сид: {mapname[2]}";
                }
                SendVkMessage(config.AdmNotify.VkID, msg2);
            }
            if (config.WipeStg.WPostB) {
                if (config.WipeStg.WPostAttB) {
                    SendVkWall($"{config.WipeStg.WPostMsg}&attachments={config.WipeStg.WPostAtt}");
                }
                else {
                    SendVkWall($"{config.WipeStg.WPostMsg}");
                }
            }
            if (config.GrGifts.GiftsWipe) {
                int amount = usersdata.VKUsersData.Count;
                if (amount != 0) {
                    for (int i = 0; i < amount; i++) {
                        usersdata.VKUsersData.ElementAt(i).Value.GiftRecived = false;
                    }
                    VKBData.WriteObject(usersdata);
                }
            }
            if (config.TopWPlayersPromo.TopWPlEnabled) {
                if (config.TopWPlayersPromo.TopPlPost || config.TopWPlayersPromo.TopPlPromoGift) {
                    SendPromoMsgsAndPost();
                    if (config.TopWPlayersPromo.TopPlPromoGift && config.TopWPlayersPromo.GenRandomPromo) {
                        SetRandomPromo();
                    }
                }
                int amount = usersdata.VKUsersData.Count;
                if (amount != 0) {
                    for (int i = 0; i < amount; i++) {
                        usersdata.VKUsersData.ElementAt(i).Value.Farm = 0;
                        usersdata.VKUsersData.ElementAt(i).Value.Kills = 0;
                        usersdata.VKUsersData.ElementAt(i).Value.Raids = 0;
                    }
                    VKBData.WriteObject(usersdata);
                }
            }
            if (config.WipeStg.WMsgPlayers) {
                WipeAlertsSend();
            }
        }
        private void WipeAlerts(ConsoleSystem.Arg arg) {
            if (arg.IsAdmin != true) {
                return;
            }
            WipeAlertsSend();
        }
        private void WipeAlertsSend() {
            List<string> UserList = new List<string>();
            string userlist = "";
            int usercount = 0;
            int amount = usersdata.VKUsersData.Count;
            if (amount != 0) {
                for (int i = 0; i < amount; i++) {
                    if (config.WipeStg.WCMDIgnore || usersdata.VKUsersData.ElementAt(i).Value.WipeMsg) {
                        if (usercount == 100) {
                            UserList.Add(userlist);
                            userlist = "";
                            usercount = 0;
                        }
                        if (usercount > 0) {
                            userlist = userlist + ", ";
                        }
                        userlist = userlist + usersdata.VKUsersData.ElementAt(i).Value.VkID;
                        usercount++;
                    }
                }
            }
            if (userlist == "" && UserList.Count == 0) {
                PrintWarning($"Список адресатов рассылки о вайпе пуст.");
                return;
            }
            if (UserList.Count > 0) {
                foreach (var list in UserList) {
                    SendVkMessage(list, config.WipeStg.WMsgText);
                }
            }
            SendVkMessage(userlist, config.WipeStg.WMsgText);
        }
#endregion
#region MainMethods
        private void UStatus(ConsoleSystem.Arg arg) {
            if (arg.IsAdmin != true) {
                return;
            }
            if (config.StatusStg.UpdateStatus) {
                if (config.StatusStg.StatusSet == 1) {
                    Update1ServerStatus();
                }
                if (config.StatusStg.StatusSet == 2) {
                    UpdateMultiServerStatus();
                }
            }
            else {
                PrintWarning($"Функция обновления статуса отключена.Status update disabled");
            }
        }
        void OnPlayerBanned(string name, ulong id, string address, string reason) {
            if (config.AdmNotify.UserBannedMsg) {
                string msg2 = null;
                if (config.MltServSet.MSSEnable) {
                    msg2 = $"[Сервер {config.MltServSet.ServerNumber.ToString()}] Игрок {name} ({id}) был забанен на сервере.Причина: {reason}.Ссылка на профиль стим: steamcommunity.com/profiles/{id}/";
                }
                else {
                    msg2 = $"Игрок {name} ({id}) был забанен на сервере.Причина: {reason}.Ссылка на профиль стим: steamcommunity.com/profiles/{id}/";
                }
                if (usersdata.VKUsersData.ContainsKey(id) && usersdata.VKUsersData[id].Confirmed) {
                    msg2 = msg2 + $".Ссылка на профиль ВК: vk.com/id{usersdata.VKUsersData[id].VkID}";
                }
                SendVkMessage(config.AdmNotify.VkID, msg2);
            }
        }
        private void SendReport(BasePlayer player, string cmd, string[] args) {
            if (config.AdmNotify.SendReports) {
                if (args.Length > 0) {
                    string text = string.Join(" ", args.Skip(0).ToArray());
                    string reciverID = config.AdmNotify.VkID;
                    string reporttext = "[VKBot]";
                    if (config.MltServSet.MSSEnable) {
                        reporttext = reporttext + " [Сервер " + config.MltServSet.ServerNumber.ToString() + "]\n";
                    }
                    reporttext = reporttext + player.displayName + "(" + player.UserIDString + ")";
                    if (usersdata.VKUsersData.ContainsKey(player.userID)) {
                        if (usersdata.VKUsersData[player.userID].Confirmed) {
                            reporttext = reporttext + ".ВК: vk.com/id" + usersdata.VKUsersData[player.userID].VkID;
                        }
                        else {
                            reporttext = reporttext + ".ВК: vk.com/id" + usersdata.VKUsersData[player.userID].VkID + " (не подтвержден)";
                        }
                    }
                    reporttext = reporttext + "\nСообщение: " + text;
                    SendVkMessage(reciverID, reporttext);
                    Log("Log", $"{player.displayName} ({player.userID}): написал администратору: {reporttext}");
                    PrintToChat(player, String.Format($"<size={config.TxtSet.TxtSize}>Ваше сообщение было отправлено администратору.\n <color={config.TxtSet.TxtColor}>ВНИМАНИЕ! </color> {config.AdmNotify.ReportsNotify}</size>"));
                }
                else {
                    PrintToChat(player, String.Format($"<size={config.TxtSet.TxtSize}>Введите команду <color={config.TxtSet.TxtColor}>/report сообщение</color>.Текст сообщения будет отправлен администратору.\n <color={config.TxtSet.TxtColor}>ВНИМАНИЕ! </color> {config.AdmNotify.ReportsNotify}</size>"));
                    return;
                }
            }
            else {
                PrintToChat(player, String.Format("Данная функция отключена администратором."));
            }
        }
        private void AddBdate(BasePlayer player) {
            if (usersdata.VKUsersData[player.userID].Bdate != null) return;
            string Userid = null;
            string userid = usersdata.VKUsersData[player.userID].VkID;
            string url2 = "https://api.vk.com/method/users.get?user_ids=" + userid + "&v=5.69&fields=bdate&access_token=" + config.VKAPIT.VKToken;
            webrequest.Enqueue(url2, null, (code, response) => {
                var json = JObject.Parse(response);
                Userid = (string)json["response"][0]["id"];
                if (Userid == null) return;
                usersdata.VKUsersData[player.userID].Bdate = "noinfo";
                var bdate = (string)json["response"][0]["bdate"];
                if (bdate != null) {
                    usersdata.VKUsersData[player.userID].Bdate = bdate;
                }
                VKBData.WriteObject(usersdata);
            }
            , this);
        }
        private void CheckVkUser(BasePlayer player, string url) {
            string Userid = null;
            string[] arr1 = url.Split('/');
            int num = arr1.Length - 1;
            string vkname = arr1[num];
            string url2 = "https://api.vk.com/method/users.get?user_ids=" + vkname + "&v=5.69&fields=bdate&access_token=" + config.VKAPIT.VKToken;
            webrequest.Enqueue(u
// ... [Code preview truncated due to length. Full source in attached file] ...

Автор
15FPS
Скачиваний
0
Просмотры
1
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок
Сверху