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

FREE VKBot : 11.0.1 11.0.1

Нет прав для скачивания
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.Core.Plugins;
using Oxide.Game.Rust.Cui;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins {
    [Info("VKBot", "/https://blackplugin.ru/", "11.0.1")]
    class VKBot : RustPlugin {
        [PluginReference]
        Plugin Duel, ImageLibrary;
        static string apiver = "v=5.92";
        private bool OxideUpdateSended = false;
        private System.Random random = new System.Random();
        private bool NewWipe = false;
        JsonSerializerSettings jsonsettings;
        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", "foundation", "floor.frame", "floor.triangle", "floor", "foundation.steps", "foundation.triangle", "roof", "stairs.l", "stairs.u", "wall.doorway", "wall.frame", "wall.half", "wall.low", "wall.window", "wall", "wall.external.high.stone"
        }
        ;
        List<string> ExplosiveList = new List<string>() {
            "explosive.satchel.deployed", "grenade.f1.deployed", "grenade.beancan.deployed", "explosive.timed.deployed"
        }
        ;
        private List<ulong> BDayPlayers = new List<ulong>();
        class GiftItem {
            public string shortname;
            public ulong skinid;
            public int count;
        }
        class ServerInfo {
            public string name;
            public string online;
            public string slots;
            public string sleepers;
            public string map;
        }
        private Dictionary<BasePlayer, DateTime> GiftsList = new Dictionary<BasePlayer, DateTime>();
        private ConfigData config;
        private class ConfigData {
            [JsonProperty(PropertyName = "Ключи VK API, ID группы")]
            public VKAPITokens VKAPIT;
            [JsonProperty(PropertyName = "Настройки оповещений администраторов")]
            public AdminNotify AdmNotify;
            [JsonProperty(PropertyName = "Настройки оповещений в беседу")]
            public ChatNotify ChNotify;
            [JsonProperty(PropertyName = "Настройки статуса")]
            public StatusSettings StatusStg;
            [JsonProperty(PropertyName = "Оповещения при вайпе")]
            public WipeSettings WipeStg;
            [JsonProperty(PropertyName = "Награда за вступление в группу")]
            public GroupGifts GrGifts;
            [JsonProperty(PropertyName = "Награда для именинников")]
            public BDayGiftSet BDayGift;
            [JsonProperty(PropertyName = "Поддержка нескольких серверов")]
            public MultipleServersSettings MltServSet;
            [JsonProperty(PropertyName = "Топ игроки вайпа и промо")]
            public TopWPlPromoSet TopWPlayersPromo;
            [JsonProperty(PropertyName = "Настройки чат команд")]
            public CommandSettings CMDSet;
            [JsonProperty(PropertyName = "Динамическая обложка группы")]
            public DynamicGroupLabelSettings DGLSet;
            [JsonProperty(PropertyName = "Виджет сообщества")]
            public GroupWidgetSettings GrWgSet;
            [JsonProperty(PropertyName = "Настройки GUI меню")]
            public GUISettings GUISet;
            public class VKAPITokens {
                [JsonProperty(PropertyName = "VK Token группы (для сообщений)")]
                public string VKToken = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "VK Token приложения (для записей на стене и статуса)")]
                public string VKTokenApp = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "VKID группы")]
                public string GroupID = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "Ссылка на группу вк")]
                public string txtvk = "   Ссылка на нашу группу вк\n         https://vk.com/droprustof";
            }
            public class AdminNotify {
                [JsonProperty(PropertyName = "VkID модераторов (для отправки репортов)")]
                public string VkID = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "VkID администрации (для отправки всех уведомлений)")]
                public string VkOwnerID = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "Включить отправку сообщений администратору командой /report ?")]
                public bool SendReports = true;
                [JsonProperty(PropertyName = "Включить GUI для команды /report ?")]
                public bool GUIReports = false;
                [JsonProperty(PropertyName = "Очистка базы репортов при вайпе?")]
                public bool ReportsWipe = true;
                [JsonProperty(PropertyName = "Предупреждение о злоупотреблении функцией репортов")]
                public string ReportsNotify = "Наличие в тексте нецензурных выражений, оскорблений администрации или игроков сервера, а так же большое количество безсмысленных сообщений приведет к бану!";
                [JsonProperty(PropertyName = "Отправлять сообщение администратору о бане игрока?")]
                public bool UserBannedMsg = true;
                [JsonProperty(PropertyName = "Комментарий в обсуждения о бане игрока?")]
                public bool UserBannedTopic = false;
                [JsonProperty(PropertyName = "ID обсуждения")]
                public string BannedTopicID = "none";
                [JsonProperty(PropertyName = "Отправлять сообщение администратору о нерабочих плагинах?")]
                public bool PluginsCheckMsg = true;
                [JsonProperty(PropertyName = "Проверка обновлений Oxide")]
                public bool OxideCheckMsg = false;
            }
            public class ChatNotify {
                [JsonProperty(PropertyName = "VK Token приложения (лучше использовать отдельную страницу для получения токена)")]
                public string ChNotfToken = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "ID беседы")]
                public string ChatID = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "Включить отправку оповещений в беседу?")]
                public bool ChNotfEnabled = false;
                [JsonProperty(PropertyName = "Дополнительная отправка оповещений в личку администраторам?")]
                public bool AdmMsg = false;
                [JsonProperty(PropertyName = "Список оповещений отправляемых в беседу (доступно: reports, wipe, bans, plugins)")]
                public string ChNotfSet = "reports, wipe, bans, plugins";
            }
            public class StatusSettings {
                [JsonProperty(PropertyName = "Обновлять статус в группе? Если стоит /false/ статистика собираться не будет")]
                public bool UpdateStatus = true;
                [JsonProperty(PropertyName = "Вид статуса (1 - текущий сервер, 2 - список серверов, необходим Rust:IO на каждом сервере)")]
                public int StatusSet = 1;
                [JsonProperty(PropertyName = "Онлайн в статусе вида '125/200'")]
                public bool OnlWmaxslots = false;
                [JsonProperty(PropertyName = "Таймер обновления статуса (минуты)")]
                public int UpdateTimer = 30;
                [JsonProperty(PropertyName = "Формат статуса")]
                public string StatusText = "{usertext}.Сервер вайпнут: {wipedate}.Онлайн игроков: {onlinecounter}.Спящих: {sleepers}.Добыто дерева: {woodcounter}.Добыто серы: {sulfurecounter}.Выпущено ракет: {rocketscounter}.Время обновления: {updatetime}.Использовано взрывчатки: {explosivecounter}.Создано чертежей: {blueprintsconter}.{connect}";
                [JsonProperty(PropertyName = "Список счетчиков, которые будут отображаться в виде emoji")]
                public string EmojiCounterList = "onlinecounter, rocketscounter, blueprintsconter, explosivecounter, wipedate";
                [JsonProperty(PropertyName = "Ссылка на коннект сервера вида /connect 111.111.111.11:11111/")]
                public string Connecturl = "connect 111.111.111.11:11111";
                [JsonProperty(PropertyName = "Текст для статуса")]
                public string StatusUT = "Сервер 1";
            }
            public class WipeSettings {
                [JsonProperty(PropertyName = "Отправлять пост в группу после вайпа?")]
                public bool WPostB = false;
                [JsonProperty(PropertyName = "Текст поста о вайпе")]
                public string WPostMsg = "Заполните эти поля, и выполните команду o.reload VKBot";
                [JsonProperty(PropertyName = "Добавить изображение к посту о вайпе?")]
                public bool WPostAttB = false;
                [JsonProperty(PropertyName = "Ссылка на изображение к посту о вайпе вида 'photo-1_265827614' (изображение должно быть в альбоме группы)")]
                public string WPostAtt = "photo-1_265827614";
                [JsonProperty(PropertyName = "Отправлять сообщение администратору о вайпе?")]
                public bool WPostMsgAdmin = true;
                [JsonProperty(PropertyName = "Отправлять игрокам сообщение о вайпе автоматически?")]
                public bool WMsgPlayers = false;
                [JsonProperty(PropertyName = "Текст сообщения игрокам о вайпе (сообщение отправляется только тем кто подписался командой /vk wipealerts)")]
                public string WMsgText = "Сервер вайпнут! Залетай скорее!";
                [JsonProperty(PropertyName = "Игнорировать команду /vk wipealerts? (если включено, сообщение о вайпе будет отправляться всем)")]
                public bool WCMDIgnore = false;
                [JsonProperty(PropertyName = "Смена названия группы после вайпа")]
                public bool GrNameChange = false;
                [JsonProperty(PropertyName = "Название группы (переменная {wipedate} отображает дату последнего вайпа)")]
                public string GrName = "ServerName | WIPE {wipedate}";
            }
            public class GroupGifts {
                [JsonProperty(PropertyName = "Выдавать подарок игроку за вступление в группу ВК?")]
                public bool VKGroupGifts = true;
                [JsonProperty(PropertyName = "Подарок за вступление в группу (команда, если стоит none выдаются предметы из файла data/VKBot.json).Пример: grantperm {steamid} vkraidalert.allow 7d")]
                public string VKGroupGiftCMD = "none";
                [JsonProperty(PropertyName = "Описание команды")]
                public string GiftCMDdesc = "Оповещения о рейде на 7 дней";
                [JsonProperty(PropertyName = "Ссылка на группу ВК")]
                public string VKGroupUrl = "vk.com/tumblerzverya";
                [JsonProperty(PropertyName = "Оповещения в общий чат о получении награды")]
                public bool GiftsBool = true;
                [JsonProperty(PropertyName = "Включить оповещения для игроков не получивших награду за вступление в группу?")]
                public bool VKGGNotify = true;
                [JsonProperty(PropertyName = "Интервал оповещений для игроков не получивших награду за вступление в группу (в минутах)")]
                public int VKGGTimer = 30;
                [JsonProperty(PropertyName = "Выдавать награду каждый вайп?")]
                public bool GiftsWipe = true;
            }
            public class BDayGiftSet {
                [JsonProperty(PropertyName = "Включить награду для именинников?")]
                public bool BDayEnabled = true;
                [JsonProperty(PropertyName = "Группа для именинников")]
                public string BDayGroup = "bdaygroup";
                [JsonProperty(PropertyName = "Оповещения в общий чат о именинниках")]
                public bool BDayNotify = false;
            }
            public class MultipleServersSettings {
                [JsonProperty(PropertyName = "Включить поддержку несколько серверов?")]
                public bool MSSEnable = false;
                [JsonProperty(PropertyName = "Номер сервера")]
                public int ServerNumber = 1;
                [JsonProperty(PropertyName = "Сервер 1 IP:PORT (пример: 111.111.111.111:28015)")]
                public string Server1ip = "none";
                [JsonProperty(PropertyName = "Название сервера 1 (если стоит none, используется номер)")]
                public string Server1name = "none";
                [JsonProperty(PropertyName = "Сервер 2 IP:PORT (пример: 111.111.111.111:28015)")]
                public string Server2ip = "none";
                [JsonProperty(PropertyName = "Название сервера 2 (если стоит none, используется номер)")]
                public string Server2name = "none";
                [JsonProperty(PropertyName = "Сервер 3 IP:PORT (пример: 111.111.111.111:28015)")]
                public string Server3ip = "none";
                [JsonProperty(PropertyName = "Название сервера 3 (если стоит none, используется номер)")]
                public string Server3name = "none";
                [JsonProperty(PropertyName = "Сервер 4 IP:PORT (пример: 111.111.111.111:28015)")]
                public string Server4ip = "none";
                [JsonProperty(PropertyName = "Название сервера 4 (если стоит none, используется номер)")]
                public string Server4name = "none";
                [JsonProperty(PropertyName = "Сервер 5 IP:PORT (пример: 111.111.111.111:28015)")]
                public string Server5ip = "none";
                [JsonProperty(PropertyName = "Название сервера 5 (если стоит none, используется номер)")]
                public string Server5name = "none";
                [JsonProperty(PropertyName = "Онлайн в emoji?")]
                public bool EmojiStatus = true;
            }
            public class TopWPlPromoSet {
                [JsonProperty(PropertyName = "Включить топ игроков вайпа")]
                public bool TopWPlEnabled = true;
                [JsonProperty(PropertyName = "Включить отправку промо кодов за топ?")]
                public bool TopPlPromoGift = false;
                [JsonProperty(PropertyName = "Пост на стене группы о топ игроках вайпа")]
                public bool TopPlPost = true;
                [JsonProperty(PropertyName = "Ссылка на изображение к посту вида 'photo-1_265827614' (изображение должно быть в альбоме группы), оставить 'none' если не нужно")]
                public string TopPlPostAtt = "none";
                [JsonProperty(PropertyName = "Промо для топ рэйдера")]
                public string TopRaiderPromo = "topraider";
                [JsonProperty(PropertyName = "Ссылка на изображение к сообщению топ рейдеру вида 'photo-1_265827614' (изображение должно быть в альбоме группы), оставить 'none' если не нужно")]
                public string TopRaiderPromoAtt = "none";
                [JsonProperty(PropertyName = "Промо для топ килера")]
                public string TopKillerPromo = "topkiller";
                [JsonProperty(PropertyName = "Ссылка на изображение к сообщению топ киллеру вида 'photo-1_265827614' (изображение должно быть в альбоме группы), оставить 'none' если не нужно")]
                public string TopKillerPromoAtt = "none";
                [JsonProperty(PropertyName = "Промо для топ фармера")]
                public string TopFarmerPromo = "topfarmer";
                [JsonProperty(PropertyName = "Ссылка на изображение к сообщению топ фармеру вида 'photo-1_265827614' (изображение должно быть в альбоме группы), оставить 'none' если не нужно")]
                public string TopFarmerPromoAtt = "none";
                [JsonProperty(PropertyName = "Ссылка на донат магазин")]
                public string StoreUrl = "server.gamestores.ru";
                [JsonProperty(PropertyName = "Автоматическая генерация промокодов после вайпа")]
                public bool GenRandomPromo = false;
            }
            public class CommandSettings {
                [JsonProperty(PropertyName = "Включить репорт систему?")]
                public bool ReportStatus = false;
                [JsonProperty(PropertyName = "Команда отправки сообщения администратору")]
                public string CMDreport = "report";
            }
            public class DynamicGroupLabelSettings {
                [JsonProperty(PropertyName = "Включить динамическую обложку?")]
                public bool DLEnable = false;
                [JsonProperty(PropertyName = "Ссылка на скрипт обновления")]
                public string DLUrl = "none";
                [JsonProperty(PropertyName = "Таймер обновления (в минутах)")]
                public int DLTimer = 10;
                [JsonProperty(PropertyName = "Обложка с онлайном нескольких серверов (все настройки ниже игнорируются)")]
                public bool DLMSEnable = false;
                [JsonProperty(PropertyName = "Текст блока 1 (доступны все переменные как в статусе)")]
                public string DLText1 = "none";
                [JsonProperty(PropertyName = "Текст блока 2 (доступны все переменные как в статусе)")]
                public string DLText2 = "none";
                [JsonProperty(PropertyName = "Текст блока 3 (доступны все переменные как в статусе)")]
                public string DLText3 = "none";
                [JsonProperty(PropertyName = "Текст блока 4 (доступны все переменные как в статусе)")]
                public string DLText4 = "none";
                [JsonProperty(PropertyName = "Текст блока 5 (доступны все переменные как в статусе)")]
                public string DLText5 = "none";
                [JsonProperty(PropertyName = "Текст блока 6 (доступны все переменные как в статусе)")]
                public string DLText6 = "none";
                [JsonProperty(PropertyName = "Текст блока 7 (доступны все переменные как в статусе)")]
                public string DLText7 = "none";
                [JsonProperty(PropertyName = "Включить вывод топ игроков на обложку?")]
                public bool TPLabel = false;
            }
            public class GroupWidgetSettings {
                [JsonProperty(PropertyName = "Включить обновление виджета?")]
                public bool WgEnable = false;
                [JsonProperty(PropertyName = "Таймер обновления (минуты)")]
                public int UpdateTimer = 3;
                [JsonProperty(PropertyName = "Заголовок виджета")]
                public string WgTitle = "Мониторинг серверов";
                [JsonProperty(PropertyName = "Ключ приложения для работы с виджетом (Инструкция - https://goo.gl/LpZujf)")]
                public string WgToken = "none";
                [JsonProperty(PropertyName = "Текст дополнительной ссылки (если стоит none, не используется)")]
                public string URLTitle = "none";
                [JsonProperty(PropertyName = "Дополнительная ссылка (разрешены только vk.com ссылки)")]
                public string URL = "none";
            }
            public class GUISettings {
                [JsonProperty(PropertyName = "Ссылка на логотип сервера")]
                public string Logo = "https://i.imgur.com/QNZykaS.png";
                [JsonProperty(PropertyName = "Позиция GUI AnchorMin (дефолт 0.347 0.218)")]
                public string AnchorMin = "0.347 0.218";
                [JsonProperty(PropertyName = "Позиция GUI AnchorMax (дефолт 0.643 0.782)")]
                public string AnchorMax = "0.643 0.782";
                [JsonProperty(PropertyName = "Цвет фона меню")]
                public string BgColor = "#00000099";
                [JsonProperty(PropertyName = "Цвет кнопки ЗАКРЫТЬ")]
                public string BCloseColor = "#DB0000ff";
                [JsonProperty(PropertyName = "Цвет кнопки ПОЛУЧИТЬ КОД")]
                public string BSendColor = "#1FEF00ff";
                [JsonProperty(PropertyName = "Цвет остальных кнопок")]
                public string BMenuColor = "#494949ff";
            }
        }
        private void LoadVariables() {
            bool changed = false;
            Config.Settings.DefaultValueHandling = DefaultValueHandling.Populate;
            config = Config.ReadObject<ConfigData>();
            if (config.AdmNotify == null) {
                config.AdmNotify = new ConfigData.AdminNotify();
                changed = true;
            }
            if (config.ChNotify == null) {
                config.ChNotify = new ConfigData.ChatNotify();
                changed = true;
            }
            if (config.WipeStg == null) {
                config.WipeStg = new ConfigData.WipeSettings();
                changed = true;
            }
            if (config.GrGifts == null) {
                config.GrGifts = new ConfigData.GroupGifts();
                changed = true;
            }
            if (config.TopWPlayersPromo == null) {
                config.TopWPlayersPromo = new ConfigData.TopWPlPromoSet();
                changed = true;
            }
            if (config.CMDSet == null) {
                config.CMDSet = new ConfigData.CommandSettings();
                changed = true;
            }
            if (config.DGLSet == null) {
                config.DGLSet = new ConfigData.DynamicGroupLabelSettings();
                changed = true;
            }
            if (config.GrWgSet == null) {
                config.GrWgSet = new ConfigData.GroupWidgetSettings();
                changed = true;
            }
            if (config.GUISet == null) {
                config.GUISet = new ConfigData.GUISettings();
                changed = true;
            }
            if (config.GUISet.Logo == "https://i.imgur.com/QNZykaS.png" && ConVar.Server.headerimage != string.Empty) config.GUISet.Logo = ConVar.Server.headerimage;
            Config.WriteObject(config, true);
            if (changed) PrintWarning("Конфигурационный файл обновлен");
        }
        protected override void LoadDefaultConfig() {
            var configData = new ConfigData {
                VKAPIT = new ConfigData.VKAPITokens(), AdmNotify = new ConfigData.AdminNotify(), ChNotify = new ConfigData.ChatNotify(), StatusStg = new ConfigData.StatusSettings(), WipeStg = new ConfigData.WipeSettings(), GrGifts = new ConfigData.GroupGifts(), BDayGift = new ConfigData.BDayGiftSet(), MltServSet = new ConfigData.MultipleServersSettings(), TopWPlayersPromo = new ConfigData.TopWPlPromoSet(), CMDSet = new ConfigData.CommandSettings(), DGLSet = new ConfigData.DynamicGroupLabelSettings(), GrWgSet = new ConfigData.GroupWidgetSettings(), GUISet = new ConfigData.GUISettings()
            }
            ;
            Config.WriteObject(configData, true);
        }
        class DataStorageStats {
            public int WoodGath;
            public int SulfureGath;
            public int Rockets;
            public int Blueprints;
            public int Explosive;
            public int Reports;
            public List<GiftItem> Gifts;
            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 string VkOwnerID;
            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;
            public string LastSeen;
        }
        class DataStorageReports {
            public Dictionary<int, REPORT> VKReportsData = new Dictionary<int, REPORT>();
            public DataStorageReports() {
            }
        }
        class REPORT {
            public ulong UserID;
            public string Name;
            public string Text;
        }
        DataStorageStats statdata;
        DataStorageUsers usersdata;
        DataStorageReports reportsdata;
        private DynamicConfigFile VKBData;
        private DynamicConfigFile StatData;
        private DynamicConfigFile ReportsData;
        void LoadData() {
            try {
                statdata = Interface.GetMod().DataFileSystem.ReadObject<DataStorageStats>("VKBot");
                usersdata = Interface.GetMod().DataFileSystem.ReadObject<DataStorageUsers>("VKBotUsers");
                reportsdata = Interface.GetMod().DataFileSystem.ReadObject<DataStorageReports>("VKBotReports");
            }
            catch {
                statdata = new DataStorageStats();
                usersdata = new DataStorageUsers();
                reportsdata = new DataStorageReports();
            }
        }
        private void OnServerInitialized() {
            PrintWarning(" ");
            LoadVariables();
            if (!config.AdmNotify.GUIReports) {
                Unsubscribe(nameof(OnServerCommand));
                Unsubscribe(nameof(OnPlayerCommand));
            }
            VKBData = Interface.Oxide.DataFileSystem.GetFile("VKBotUsers");
            StatData = Interface.Oxide.DataFileSystem.GetFile("VKBot");
            ReportsData = Interface.Oxide.DataFileSystem.GetFile("VKBotReports");
            ImageLibrary.Call("AddImage", VkICO, ".VkICO");
            ImageLibrary.Call("AddImage", GiftICO, ".GiftICO");
            ImageLibrary.Call("AddImage", AlertICO, ".AlertICO");
            ImageLibrary.Call("AddImage", "https://gspics.org/images/2024/07/01/0zF5iN.png", "BackgroundImage");
            ImageLibrary.Call("AddImage", "https://i.ibb.co/rbnB64d/0cxybrs.png", "ButtonBlock");
            ImageLibrary.Call("AddImage", "https://i.ibb.co/vxbzBdr/1AMYOO9.png", "alerts");
            ImageLibrary.Call("AddImage", "https://i.ibb.co/vxbzBdr/1AMYOO9.png", "alerts1");
            ImageLibrary.Call("AddImage", "https://i.ibb.co/hYf91T3/8seJ7Wi.png", "alertvkback");
            ImageLibrary.Call("AddImage", "https://i.ibb.co/LtZ6b4F/Kz4YbZH.png", "vkdeleteback");
            ImageLibrary.Call("AddImage", "https://i.ibb.co/hF6hqdj/GnyEmwq.png", "giftrewardback");
            permission.RegisterPermission(AlertPermission, this);
            string msg2 = null;
            msg2 = $"[VKBot] Сервер успешно загружен.";
            LoadData();
            if (statdata.Gifts == null) {
                statdata.Gifts = new List<GiftItem>() {
                    new GiftItem {
                        shortname = "supply.signal", count = 1, skinid = 0
                    }
                    , new GiftItem {
                        shortname = "pookie.bear", count = 2, skinid = 0
                    }
                }
                ;
                StatData.WriteObject(statdata);
            }
            if (config.CMDSet.ReportStatus == true) {
                cmd.AddChatCommand(config.CMDSet.CMDreport, this, "SendReport");
            }
            CheckAdminID();
            if (NewWipe) WipeFunctions();
            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("status");
                }
                );
            }
            if (config.GrWgSet.WgEnable) {
                if (config.GrWgSet.WgToken == "none") PrintWarning($"Ошибка обновления виджета! В файле конфигурации не указан ключ!");
                else timer.Repeat(config.GrWgSet.UpdateTimer * 60, 0, () => {
                    UpdateMultiServerStatus("widget");
                }
                );
            }
            if (config.DGLSet.DLEnable && config.DGLSet.DLUrl != "none") {
                timer.Repeat(config.DGLSet.DLTimer * 60, 0, () => {
                    if (config.DGLSet.DLMSEnable) {
                        UpdateMultiServerStatus("label");
                    }
                    else {
                        UpdateVKLabel();
                    }
                }
                );
            }
            if (config.GrGifts.VKGGNotify) timer.Repeat(config.GrGifts.VKGGTimer * 60, 0, GiftNotifier);
            if (config.AdmNotify.PluginsCheckMsg) CheckPlugins();
            if (config.AdmNotify.OxideCheckMsg) CheckOxideUpdate();
            SendVkMessage(config.AdmNotify.VkOwnerID, msg2);
        }
        private void OnServerSave() {
            if (config.TopWPlayersPromo.TopWPlEnabled) VKBData.WriteObject(usersdata);
            if (config.StatusStg.UpdateStatus || config.DGLSet.DLEnable) StatData.WriteObject(statdata);
        }
        private void Init() {
            cmd.AddChatCommand("regvk", this, "VKcommand");
            cmd.AddConsoleCommand("updatestatus", this, "UStatus");
            cmd.AddConsoleCommand("updatewidget", this, "UWidget");
            cmd.AddConsoleCommand("updatelabel", this, "ULabel");
            cmd.AddConsoleCommand("sendmsgadmin", this, "MsgAdmin");
            cmd.AddConsoleCommand("wipealerts", this, "WipeAlerts");
            cmd.AddConsoleCommand("userinfo", this, "GetUserInfo");
            cmd.AddConsoleCommand("report.answer", this, "ReportAnswer");
            cmd.AddConsoleCommand("reports.list", this, "ReportList");
            cmd.AddConsoleCommand("report.wipe", this, "ReportClear");
            cmd.AddConsoleCommand("usersdata.update", this, "UpdateUsersData");
            jsonsettings = new JsonSerializerSettings();
            jsonsettings.Converters.Add(new KeyValuePairConverter());
        }
        private void Loaded() => LoadMessages();
        private void Unload() {
            if (config.AdmNotify.SendReports) ReportsData.WriteObject(reportsdata);
            if (config.StatusStg.UpdateStatus || config.DGLSet.DLEnable) StatData.WriteObject(statdata);
            if (config.TopWPlayersPromo.TopWPlEnabled) VKBData.WriteObject(usersdata);
            if (config.BDayGift.BDayEnabled && BDayPlayers.Count > 0) {
                foreach (var id in BDayPlayers) permission.RemoveUserGroup(id.ToString(), config.BDayGift.BDayGroup);
                BDayPlayers.Clear();
            }
            UnloadAllGUI();
        }
        private void OnNewSave(string filename) => NewWipe = true;
        private void OnPlayerInit(BasePlayer player) {
            if (usersdata.VKUsersData.ContainsKey(player.userID) && usersdata.VKUsersData[player.userID].Name != player.displayName) {
                usersdata.VKUsersData[player.userID].Name = player.displayName;
                VKBData.WriteObject(usersdata);
            }
            if (OpenReportUI.Contains(player)) OpenReportUI.Remove(player);
        }
        private void OnPlayerSleepEnded(BasePlayer player) {
            if (!usersdata.VKUsersData.ContainsKey(player.userID)) return;
            if (!config.BDayGift.BDayEnabled) return;
            if (config.BDayGift.BDayEnabled && permission.GroupExists(config.BDayGift.BDayGroup)) {
                if (permission.UserHasGroup(player.userID.ToString(), config.BDayGift.BDayGroup)) return;
                var bday = usersdata.VKUsersData[player.userID].Bdate;
                if (bday == null || bday == "noinfo") return;
                if (bday.Split('.').Length == 3) bday.Remove(bday.Length - 5, 5);
                if (bday == DateTime.Now.ToString("d.M", CultureInfo.InvariantCulture)) {
                    permission.AddUserGroup(player.userID.ToString(), config.BDayGift.BDayGroup);
                    PrintToChat(player, string.Format(GetMsg("ПоздравлениеИгрока")));
                    Log("bday", $"Игрок {player.displayName} добавлен в группу {config.BDayGift.BDayGroup}");
                    BDayPlayers.Add(player.userID);
                    if (config.BDayGift.BDayNotify) Server.Broadcast(string.Format(GetMsg("ДеньРожденияИгрока"), player.displayName));
                }
            }
        }
        private void OnPlayerDisconnected(BasePlayer player, string reason) {
            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}");
                }
            }
            if (OpenReportUI.Contains(player)) OpenReportUI.Remove(player);
            if (usersdata.VKUsersData.ContainsKey(player.userID)) {
                usersdata.VKUsersData[player.userID].LastSeen = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
                VKBData.WriteObject(usersdata);
            }
        }
        private void OnPlayerBanned(string name, ulong id, string address, string reason, 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 (config.AdmNotify.UserBannedTopic && config.AdmNotify.BannedTopicID != "null") AddComentToBoard(config.AdmNotify.BannedTopicID, msg2);
            if (config.AdmNotify.UserBannedMsg) {
                if (usersdata.VKUsersData.ContainsKey(id) && usersdata.VKUsersData[id].Confirmed) msg2 = msg2 + $".Ссылка на профиль ВК: vk.com/id{usersdata.VKUsersData[id].VkID}";
                if (config.ChNotify.ChNotfEnabled && config.ChNotify.ChNotfSet.Contains("bans")) {
                    SendChatMessage(config.ChNotify.ChatID, msg2);
                    if (config.ChNotify.AdmMsg) SendVkMessage(config.AdmNotify.VkID, msg2);
                }
                else SendVkMessage(config.AdmNotify.VkID, msg2);
            }
        }
        private void OnItemResearch(ResearchTable table, Item targetItem, BasePlayer player) {
            if (config.StatusStg.UpdateStatus || config.DGLSet.DLEnable) statdata.Blueprints++;
        }
        private void OnDispenserGather(ResourceDispenser dispenser, BaseEntity entity, Item item) {
            if (config.StatusStg.UpdateStatus || config.DGLSet.DLEnable) {
                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 || config.DGLSet.DLEnable) && item.info.shortname == "sulfur.ore") statdata.SulfureGath = statdata.SulfureGath + item.amount;
            if (config.TopWPlayersPromo.TopWPlEnabled && 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 || config.DGLSet.DLEnable) {
                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 && 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 || config.DGLSet.DLEnable) statdata.Rockets++;
        }
        private void OnExplosiveThrown(BasePlayer player, BaseEntity entity) {
            if (config.StatusStg.UpdateStatus || config.DGLSet.DLEnable && ExplosiveList.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, attacker);
                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, BasePlayer attacker) {
            if (IsNPC(player)) return;
            if (!usersdata.VKUsersData.ContainsKey(attacker.userID)) return;
            if (!player.IsConnected) return;
            if (Duel && (bool)Duel?.Call("IsDuelPlayer", player)) return;
            usersdata.VKUsersData[attacker.userID].Kills++;
        }
        private void WipeFunctions() {
            if (config.StatusStg.UpdateStatus) {
                statdata.Blueprints = 0;
                statdata.Rockets = 0;
                statdata.SulfureGath = 0;
                statdata.WoodGath = 0;
                statdata.Explosive = 0;
                StatData.WriteObject(statdata);
                if (config.StatusStg.StatusSet == 1) Update1ServerStatus();
                if (config.StatusStg.StatusSet == 2) UpdateMultiServerStatus("status");
            }
            if (config.WipeStg.WPostMsgAdmin) {
                string msg2 = "[VKBot] Сервер ";
                if (config.MltServSet.MSSEnable) msg2 = msg2 + config.MltServSet.ServerNumber.ToString() + " ";
                if (ConVar.Server.levelurl != string.Empty) msg2 = msg2 + $"вайпнут.Установлена карта: {ConVar.Server.levelurl}.";
                else msg2 = msg2 + $"вайпнут.Установлена карта: {ConVar.Server.level}.Размер: {ConVar.Server.worldsize}.Сид: {ConVar.Server.seed}";
                if (config.ChNotify.ChNotfEnabled && config.ChNotify.ChNotfSet.Contains("wipe")) {
                    SendChatMessage(config.ChNotify.ChatID, msg2);
                    if (config.ChNotify.AdmMsg) SendVkMessage(config.AdmNotify.VkOwnerID, msg2);
                }
                else SendVkMessage(config.AdmNotify.VkOwnerID, 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) {
                if (usersdata.VKUsersData.Count != 0) {
                    for (int i = 0; i < usersdata.VKUsersData.Count; 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.GenRandomPromo) SetRandomPromo();
                }
                if (usersdata.VKUsersData.Count != 0) {
                    for (int i = 0; i < usersdata.VKUsersData.Count; 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();
            if (config.AdmNotify.SendReports && config.AdmNotify.ReportsWipe) {
                reportsdata.VKReportsData.Clear();
                ReportsData.WriteObject(reportsdata);
                statdata.Reports = 0;
                StatData.WriteObject(statdata);
            }
            if (config.WipeStg.GrNameChange) {
                string wipedate = WipeDate();
                string text = config.WipeStg.GrName.Replace("{wipedate}", wipedate);
                webrequest.Enqueue("https://api.vk.com/method/groups.edit?group_id=" + config.VKAPIT.GroupID + "&title=" + text + "&" + apiver + "&access_token=" + config.VKAPIT.VKTokenApp, null, (code, response) => {
                    var json = JObject.Parse(response);
                    string Result = (string)json["response"];
                    if (Result == "1") PrintWarning($"Новое имя группы - {text}");
                    else {
                        PrintWarning("Ошибка смены имени группы.Логи - /oxide/logs/VKBot/");
                        Log("Errors", $"group title not changed.Error: {response}");
                    }
                }
                , this);
            }
        }
        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;
            if (usersdata.VKUsersData.Count != 0) {
                for (int i = 0; i < usersdata.VKUsersData.Count; i++) {
                    if (config.WipeStg.WCMDIgnore || usersdata.VKUsersData.ElementAt(i).Value.WipeMsg) {
                        if (!ServerUsers.BanListString().Contains(usersdata.VKUsersData.ElementAt(i).Value.UserID.ToString())) {
                            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);
        }
        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("status");
            }
            else PrintWarning($"Функция обновления статуса отключена.");
        }
        private void UpdateUsersData(ConsoleSystem.Arg arg) {
            if (arg.IsAdmin != true) return;
            DeleteOldUsers(arg.Args?[0]);
        }
        private void UWidget(ConsoleSystem.Arg arg) {
            if (arg.IsAdmin != true) return;
            if (config.GrWgSet.WgEnable) {
                if (config.GrWgSet.WgToken == "none") {
                    PrintWarning($"Ошибка! В файле конфигурации не указан ключ!");
                    return;
                }
                UpdateMultiServerStatus("widget");
            }
            else PrintWarning($"Функция обновления статуса отключена.");
        }
        private string PrepareStatus(string input, string target) {
            string text = input;
            string temp = "";
            temp = GetOnline();
            if (target == "status" && config.StatusStg.EmojiCounterList.Contains("onlinecounter")) temp = EmojiCounters(temp);
            if (input.Contains("{onlinecounter}")) text = text.Replace("{onlinecounter}", temp);
            temp = BasePlayer.sleepingPlayerList.Count.ToString();
            if (target == "status" && config.StatusStg.EmojiCounterList.Contains("sleepers")) temp = EmojiCounters(temp);
            if (input.Contains("{sleepers}")) text = text.Replace("{sleepers}", temp);
            temp = statdata.WoodGath.ToString();
            if (target == "status" && config.StatusStg.EmojiCounterList.Contains("woodcounter")) temp = EmojiCounters(temp);
            if (input.Contains("{woodcounter}")) text = text.Replace("{woodcounter}", temp);
            temp = statdata.SulfureGath.ToString();
            if (target == "status" && config.StatusStg.EmojiCounterList.Contains("sulfurecounter")) temp = EmojiCounters(temp);
            if (input.Contains("{sulfurecounter}")) text = text.Replace("{sulfurecounter}", temp);
            temp = statdata.Rockets.ToString();
            if (target == "status" && config.StatusStg.EmojiCounterList.Contains("rocketscounter")) temp = EmojiCounters(temp);
            if (input.Contains("{rocketscounter}")) text = text.Replace("{rocketscounter}", temp);
            temp = statdata.Blueprints.ToString();
// ... [Code preview truncated due to length. Full source in attached file] ...

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