/// <summary>
        /// 初始化 telegram
        /// </summary>
        private static void SetupTelegram()
        {
            HttpToSocks5Proxy proxy = new HttpToSocks5Proxy(Config.Telegram.ProxyHostname, Config.Telegram.ProxyPort);

            Telegram          = new TelegramBotClient(Config.Telegram.Token, proxy);
            TelegramChannelId = new ChatId(Config.Telegram.TargetId);
        }
        async void stalker_joke(TelegramBotClient Bot, Telegram.Bot.Types.ChatId ChatId)
        {
            string folder = path + "/res/shoc/";

            await Bot.SendPhotoAsync(ChatId, new InputFileStream(File.OpenRead(folder + "stalker_novice_" + R.Next(1, 6).ToString() + ".png")).Content);

            switch (R.Next(1, 4))
            {
            case 1:
                await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/stalker_1/novice/intro_joke_" + R.Next(1, 6).ToString() + ".ogg")).Content);

                await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/stalker_1/novice/joke_" + R.Next(1, 14).ToString() + ".ogg")).Content);

                break;

            case 2:
                await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/stalker_2/novice/intro_joke_" + R.Next(1, 6).ToString() + ".ogg")).Content);

                await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/stalker_2/novice/joke_" + R.Next(1, 16).ToString() + ".ogg")).Content);

                break;

            case 3:
                await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/stalker_3/novice/intro_joke_" + R.Next(1, 6).ToString() + ".ogg")).Content);

                await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/stalker_3/novice/joke_" + R.Next(1, 14).ToString() + ".ogg")).Content);

                break;
            }
        }
Ejemplo n.º 3
0
        public static async Task SendAsync(string message)
        {
            TelegramBotClient client = new TelegramBotClient("1312796762:AAHB-0erveBBjJfOvHfBrCJvAhbNRL8Koew");

            Telegram.Bot.Types.ChatId id = new Telegram.Bot.Types.ChatId(-1001199019089);
            await client.SendTextMessageAsync(id, message);
        }
        async void stalker_guitar(TelegramBotClient Bot, Telegram.Bot.Types.ChatId ChatId)
        {
            string folder = path + "/res/shoc/";

            await Bot.SendPhotoAsync(ChatId, new InputFileStream(File.OpenRead(folder + "stalker_novice_" + R.Next(1, 6).ToString() + ".png")).Content);

            await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/stalker_" + R.Next(1, 4).ToString() + "/novice/intro_music_" + R.Next(1, 6).ToString() + ".ogg")).Content);

            await Bot.SendVoiceAsync(ChatId, new InputFileStream(File.OpenRead(folder + "/fire/guitar_" + R.Next(1, 12).ToString() + ".ogg")).Content);
        }
Ejemplo n.º 5
0
        public static async Task <int> ForwardMessageAnonymously(Telegram.Bot.Types.ChatId ToChatId,
                                                                 bool DisableNotifications,
                                                                 Telegram.Bot.Types.Message Msg)
        {
            switch (Msg.Type)
            {
            case MessageType.Text:
                await Vars.Bot.SendTextMessageAsync(ToChatId, Msg.Text, ParseMode.Default, false, DisableNotifications);

                return(0);

            default:
                await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID, Vars.CurrentLang.Message_SupportTextMessagesOnly, ParseMode.Markdown, false, DisableNotifications, Msg.MessageId);

                return(1);
            }
        }
Ejemplo n.º 6
0
        public async Task <bool> Execute()
        {
            BotResponseModel jsonResult = await Calculate();

            string strFormattedResult = JsonConvert.SerializeObject(jsonResult, Formatting.Indented);
            string botToken           = _configuration.GetValue <string>("Bot:Token");

            Telegram.Bot.TelegramBotClient botClient = new Telegram.Bot.TelegramBotClient(botToken);
            BotSettingModel setting = _bot.LoadSetting();

            foreach (string receiver in setting.Receivers)
            {
                Telegram.Bot.Types.ChatId chatId = new Telegram.Bot.Types.ChatId(receiver);
                await botClient.SendTextMessageAsync(chatId, strFormattedResult);
            }
            return(true);
        }
Ejemplo n.º 7
0
        public static void endClassTime(Telegram.Bot.Types.ChatId id)                                                                         //Обработка команды "конец пары"
        {
            string[] timeArr = new string[] { "9,45,00", "11,25,00", "13,05,00", "15,15,00", "16,55,00", "18,35,00" };                        //Массив с временеем окончания пар

            for (int i = 1; i < timeArr.Length; i++)                                                                                          //Проходим по всему расписанию
            {
                var      timeArrStr1 = timeArr[i - 1].Split(',');                                                                             //Разбиваю элемент массива на время
                var      today       = (DateTime.Now).ToShortDateString().Split('.');                                                         //Получаю дату сегодняшнего дня в формате ДД.ММ.ГГ
                DateTime dateTime    = new DateTime(int.Parse(today[2]), int.Parse(today[1]), int.Parse(today[0]), int.Parse(timeArrStr1[0]), //Указываю дату конца первой пары
                                                    int.Parse(timeArrStr1[1]), int.Parse(timeArrStr1[2]));

                var      timeArrStr2 = timeArr[i].Split(',');
                DateTime dateTime1   = new DateTime(int.Parse(today[2]), int.Parse(today[1]), int.Parse(today[0]), int.Parse(timeArrStr2[0]), //Указываю дату конца второй пары
                                                    int.Parse(timeArrStr2[1]), int.Parse(timeArrStr2[2]));


                if (DateTime.Now > dateTime && DateTime.Now < dateTime1)                         //Еслли текущее время больше предыдущей пары и меньше текущей пары отнимаем от текущей пары текущее время
                {
                    var dif = dateTime1.Subtract(DateTime.Now);                                  //отнимаю время
                    var res = String.Format("{0}:{1}:{2}", dif.Hours, dif.Minutes, dif.Seconds); //форматирую строку
                    bot.SendTextMessageAsync(id, res);                                           //вывожу в чат бот
                    break;
                }
                if (DateTime.Now < dateTime)                                                     //Если текущее время меньше предыдуущей пары , значит мы на этой паре
                {
                    var dif = dateTime.Subtract(DateTime.Now);                                   //отнимаю время
                    var res = String.Format("{0}:{1}:{2}", dif.Hours, dif.Minutes, dif.Seconds); //форматирую строку
                    bot.SendTextMessageAsync(id, res);                                           //вывожу в чат бот
                    break;
                }
                if (i == timeArr.Length - 1)                          //Если доходим до конца массива значит пары закончились
                {
                    bot.SendTextMessageAsync(id, "Пары закончились"); //говорим о том что  пары закончились
                    break;
                }
            }
        }
Ejemplo n.º 8
0
        public static void setka(Telegram.Bot.Types.ChatId id)
        {
            /*
             * !!!!!!ФОРМАТ В БД ТИПА 01.01.2000!!!!!!
             * twoDates - массив из БД с двумя датами
             * сплитую по точке эти две даты
             * отнимаю от дат текущую дату
             * получаю дни
             * вывожу дни
             */
            var ee = DataBase.getDate();

            String[] twoDates = DataBase.getDate().Result;
            Thread.Sleep(2000);
            var      fromSetka     = twoDates[0].Split('.');
            DateTime dateFromSetka = new DateTime(int.Parse(fromSetka[2]), int.Parse(fromSetka[1]), int.Parse(fromSetka[0]));
            var      fromWeek      = twoDates[1].Split('.');
            DateTime dateFromWeek  = new DateTime(int.Parse(fromWeek[2]), int.Parse(fromWeek[1]), int.Parse(fromWeek[0]));

            var betweenSetka = dateFromSetka.Subtract(DateTime.Now);
            var betweenWeek  = dateFromWeek.Subtract(DateTime.Now);

            bot.SendTextMessageAsync(id, $"Дней до начала сессии осталось: {betweenSetka.Days}. До начала зачетной недели: {betweenWeek.Days}");
        }
Ejemplo n.º 9
0
        private static string getChatNome(Telegram.Bot.Types.ChatId chatID)
        {
            string nomeChat = null;

            try
            {
                Telegram.Bot.Types.Chat chat = botClient.GetChatAsync(chatID).Result;

                if (chat.Type == Telegram.Bot.Types.Enums.ChatType.Channel || chat.Type == Telegram.Bot.Types.Enums.ChatType.Group || chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup && chat.Title.Length > 0)
                {
                    nomeChat += chat.Title;
                }
                if (chat.Type == Telegram.Bot.Types.Enums.ChatType.Private && chat.FirstName.Length > 0)
                {
                    if (!String.IsNullOrEmpty(nomeChat))
                    {
                        nomeChat += ' ';
                    }
                    nomeChat += chat.FirstName;
                }
                if (chat.Type == Telegram.Bot.Types.Enums.ChatType.Private && chat.LastName.Length > 0)
                {
                    if (!String.IsNullOrEmpty(nomeChat))
                    {
                        nomeChat += ' ';
                    }
                    nomeChat += chat.LastName;
                }
            }
            catch
            {
                nomeChat = "indefinido";
            }

            return(nomeChat);
        }
Ejemplo n.º 10
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            try
            {
                var replacedInput = ReplaceValues(inputString, data);
                switch (group)
                {
                case UtilityGroup.List:
                    var  list     = data.Variables.GetList(listName);
                    var  list2    = data.Variables.GetList(secondListName);
                    var  item     = ReplaceValues(listItem, data);
                    var  index    = int.Parse(ReplaceValues(listIndex, data));
                    CVar variable = null;

                    switch (listAction)
                    {
                    case ListAction.Create:
                        data.Variables.Set(new CVar(variableName, new List <string>(), isCapture));
                        break;

                    case ListAction.Length:
                        data.Variables.Set(new CVar(variableName, list.Count().ToString(), isCapture));
                        break;

                    case ListAction.Join:
                        data.Variables.Set(new CVar(variableName, string.Join(separator, list), isCapture));
                        break;

                    case ListAction.Sort:
                        var sorted = list.Select(e => e).ToList();         // Clone the list so we don't edit the original one
                        if (Numeric)
                        {
                            var nums = sorted.Select(e => double.Parse(e, CultureInfo.InvariantCulture)).ToList();
                            nums.Sort();
                            sorted = nums.Select(e => e.ToString()).ToList();
                        }
                        else
                        {
                            sorted.Sort();
                        }
                        if (!Ascending)
                        {
                            sorted.Reverse();
                        }
                        data.Variables.Set(new CVar(variableName, sorted, isCapture));
                        break;

                    case ListAction.Concat:
                        data.Variables.Set(new CVar(variableName, list.Concat(list2).ToList(), isCapture));
                        break;

                    case ListAction.Intersection:
                        data.Variables.Set(new CVar(variableName, list.Intersect(list2).ToList(), isCapture));
                        break;

                    case ListAction.Difference:
                        data.Variables.Set(new CVar(variableName, list.Except(list2).ToList(), isCapture));
                        break;

                    case ListAction.Zip:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (a, b) => a + b).ToList(), isCapture));
                        break;

                    case ListAction.Map:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v), isCapture));
                        break;

                    case ListAction.Add:
                        // TODO: Refactor this
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.Insert(index, item);
                        break;

                    case ListAction.Remove:
                        // TODO: Refactor this
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.RemoveAt(index);
                        break;

                    case ListAction.RemoveValues:
                        data.Variables.Set(new CVar(variableName, list.Where(l => !Condition.Verify(new KeycheckCondition
                        {
                            Left     = ReplaceValues(l, data),
                            Comparer = ListElementComparer,
                            Right    = ListComparisonTerm
                        })).ToList(), isCapture));
                        break;

                    case ListAction.RemoveDuplicates:
                        data.Variables.Set(new CVar(variableName, list.Distinct().ToList(), isCapture));
                        break;

                    case ListAction.Random:
                        data.Variables.Set(new CVar(variableName, list[data.random.Next(list.Count)], isCapture));
                        break;

                    case ListAction.Shuffle:
                        // This makes a copy of the original list
                        var listCopy = list.ToArray().ToList();
                        listCopy.Shuffle(data.random);
                        data.Variables.Set(new CVar(variableName, listCopy, isCapture));
                        break;

                    default:
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {listAction} on file {listName}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Variable:
                    string single;
                    switch (varAction)
                    {
                    case VarAction.Split:
                        single = data.Variables.GetSingle(varName);
                        data.Variables.Set(new CVar(variableName, single.Split(new string[] { ReplaceValues(splitSeparator, data) }, StringSplitOptions.None).ToList(), isCapture));
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {varAction} on variable {varName}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Conversion:
                    byte[] conversionInputBytes = replacedInput.ConvertFrom(conversionFrom);
                    var    conversionResult     = conversionInputBytes.ConvertTo(conversionTo);
                    data.Variables.Set(new CVar(variableName, conversionResult, isCapture));
                    data.Log(new LogEntry($"Executed conversion {conversionFrom} to {conversionTo} on input {replacedInput} with outcome {conversionResult}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.File:
                    var file = ReplaceValues(filePath, data);
                    Files.ThrowIfNotInCWD(file);

                    switch (fileAction)
                    {
                    case FileAction.Exists:
                        data.Variables.Set(new CVar(variableName, File.Exists(file).ToString(), isCapture));
                        break;

                    case FileAction.Read:
                        lock (FileLocker.GetLock(file))
                            data.Variables.Set(new CVar(variableName, File.ReadAllText(file), isCapture));
                        break;

                    case FileAction.ReadLines:
                        lock (FileLocker.GetLock(file))
                            data.Variables.Set(new CVar(variableName, File.ReadAllLines(file).ToList(), isCapture));
                        break;

                    case FileAction.Write:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.WriteAllText(file, replacedInput.Unescape());
                        break;

                    case FileAction.WriteLines:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.WriteAllLines(file, ReplaceValuesRecursive(inputString, data).Select(i => i.Unescape()));
                        break;

                    case FileAction.Append:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.AppendAllText(file, replacedInput.Unescape());
                        break;

                    case FileAction.AppendLines:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.AppendAllLines(file, ReplaceValuesRecursive(inputString, data).Select(i => i.Unescape()));
                        break;

                    case FileAction.Copy:
                        var fileCopyLocation = ReplaceValues(inputString, data);
                        Files.ThrowIfNotInCWD(fileCopyLocation);
                        Files.CreatePath(fileCopyLocation);
                        lock (FileLocker.GetLock(file))
                            lock (FileLocker.GetLock(fileCopyLocation))
                                File.Copy(file, fileCopyLocation);
                        break;

                    case FileAction.Move:
                        var fileMoveLocation = ReplaceValues(inputString, data);
                        Files.ThrowIfNotInCWD(fileMoveLocation);
                        Files.CreatePath(fileMoveLocation);
                        lock (FileLocker.GetLock(file))
                            lock (FileLocker.GetLock(fileMoveLocation))
                                File.Move(file, fileMoveLocation);
                        break;

                    case FileAction.Delete:
                        // No deletion if the file is in use (DB/OpenBullet.db cannot be deleted but instead DB/OpenBullet-BackupCopy.db)
                        // If another process is just reading the file it will be deleted
                        lock (FileLocker.GetLock(file))
                            File.Delete(file);
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {fileAction} on file {file}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Folder:
                    var folder = ReplaceValues(folderPath, data);
                    Files.ThrowIfNotInCWD(folder);

                    switch (folderAction)
                    {
                    case FolderAction.Exists:
                        data.Variables.Set(new CVar(variableName, Directory.Exists(folder).ToString(), isCapture));
                        break;

                    case FolderAction.Create:
                        data.Variables.Set(new CVar(variableName, Directory.CreateDirectory(folder).ToString(), isCapture));
                        break;

                    case FolderAction.Delete:
                        // All files in the folder will be deleted expect the ones that are in use
                        // DB/OpenBullet.db cannot be deleted but instead DB/OpenBullet-BackupCopy.db
                        // If another process is just reading a file in the folder it will be deleted
                        Directory.Delete(folder, true);
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {folderAction} on folder {folder}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Telegram:
                    lock (tlgLocker)
                    {
                        var bot = new TelegramBotClient(BotToken);
                        Telegram.Bot.Types.ChatId chatId = null;
                        try
                        {
                            if (ChatId.StartsWith("@"))
                            {
                                chatId = new Telegram.Bot.Types.ChatId(ChatId);
                            }
                            else
                            {
                                chatId = new Telegram.Bot.Types.ChatId(int.Parse(ChatId));
                            }
                        }
                        catch { data.Log(new LogEntry("Chat Id is invalid", Colors.Red)); }
                        var s = 0;
                        while (s < 20)
                        {
                            var result = bot.SendTextMessageAsync(chatId, ReplaceValues(string.Join("\n", Messages), data), ParseMode).Result;
                            if (result == null)
                            {
                                data.Log(new LogEntry("Message sent not successfully!!", Colors.Red));
                                data.Log(new LogEntry("Sleep 100ms", Colors.Yellow));
                                Thread.Sleep(100);
                                s++;
                                continue;
                            }
                            data.Log(new LogEntry("Message sent successfully!", Colors.LimeGreen));
                            break;
                        }
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); if (ex.InnerException != null)
                                   {
                                       data.Log(new LogEntry(ex.InnerException.Message, Colors.Tomato));
                                   }
            }
        }
Ejemplo n.º 11
0
 public static void map(Telegram.Bot.Types.ChatId id)                             //Обработка команды "Карта"
 {
     bot.SendPhotoAsync(id, "https://istu-bot.000webhostapp.com/images/map.jpg"); //Берем фотографию с хоста и выводим ее
 }
Ejemplo n.º 12
0
 public static void timetable(Telegram.Bot.Types.ChatId id)                            //Обработка команды "Расписание"
 {
     bot.SendTextMessageAsync(id, "Посмотри вот тут: https://www.istu.edu/schedule/"); //Говорим что пар нет
 }
Ejemplo n.º 13
0
 public static void hello(Telegram.Bot.Types.ChatId id) //Обработка команды "Привет"
 {
     bot.SendTextMessageAsync(id, "Hello!");
 }
Ejemplo n.º 14
0
 public static void events(Telegram.Bot.Types.ChatId id)                            //Обработка команды "Расписание"
 {
     bot.SendTextMessageAsync(id, "Посмотри вот тут: https://vk.com/golos_irnitu"); //Говорим что пар нет
 }
Ejemplo n.º 15
0
        private static void telegramEnviarMensagem(Telegram.Bot.Types.ChatId chatID, string mensagem, bool disablePreview)
        {
            botClient.SendTextMessageAsync(chatID, mensagem, Telegram.Bot.Types.Enums.ParseMode.Markdown, disablePreview);

            Console.WriteLine("Mensagem enviada para " + getChatNome(chatID) + " (" + chatID + ')');
        }